Compare commits

..

20 Commits

Author SHA1 Message Date
Dandaedre a20abc677b ci: update coverage tooling for modern Cargo
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-11-21 14:38:53 +01:00
Dandaedre 5ff3f7673f test: cover scan workers and recalibrate coverage floor
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-11-21 13:39:50 +01:00
Dandaedre bc552348d6 fix: replace chrono and update rustix for RustSec
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-11-20 18:22:58 +01:00
Dandaedre 82a495092d docs: add project icon and disclose LLM-assisted development
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-11-20 16:47:47 +01:00
Dandaedre 891b300f86 fix: reconnect once after unusable instrument identification
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-20 16:48:10 +02:00
Dandaedre be8f9e1ebf chore: prepare 0.1.5 desktop release
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-20 16:39:55 +02:00
Dandaedre 075d0461d7 docs: guide new users through a first scan with screenshots
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-20 16:38:08 +02:00
Dandaedre 616e75a82d ci: remove superseded standalone macOS build 2026-10-20 16:34:40 +02:00
Dandaedre acb591e313 ci: add macOS targets to automated releases
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-20 16:33:25 +02:00
Dandaedre 8ed07cb60e feat: automate macOS cross-compilation with Zig
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-20 15:13:37 +02:00
Dandaedre 03503eebbc release: bump 0.1.4
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-08 12:52:10 +02:00
Dandaedre 9ea53a042b feat: add live plot navigation and peak overlay 2026-10-08 12:51:59 +02:00
Dandaedre 78bd22023c feat: add live scan mode
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-08 09:39:05 +02:00
Dandaedre 82eaffc17b release: bump 0.1.3-rc.5 2026-10-08 08:21:35 +02:00
Dandaedre f8280b35bc feat: improve scan workflow reliability 2026-10-08 08:21:20 +02:00
Dandaedre 8a0e7bd9b1 fix: validate CSV before logger startup
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-07 16:48:26 +02:00
Dandaedre 96b4bfb13a release: bump 0.1.3-rc.4
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-10-07 16:15:57 +02:00
Dandaedre 7c36bdf998 feat: add interactive CSV plot navigation 2026-10-07 16:15:26 +02:00
Dandaedre df9f61da63 release: bump 0.1.3-rc.3
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-07 10:03:24 +02:00
Dandaedre fd9c820a59 feat: support tinySA Ultra+ ZS406 2026-10-07 10:03:05 +02:00
47 changed files with 3490 additions and 458 deletions

196
Cargo.lock generated
View File

@ -32,15 +32,6 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "android_system_properties"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.104" version = "1.0.104"
@ -155,16 +146,6 @@ dependencies = [
"rustversion", "rustversion",
] ]
[[package]]
name = "cc"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
version = "1.0.5" version = "1.0.5"
@ -177,19 +158,6 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
"iana-time-zone",
"js-sys",
"num-traits",
"wasm-bindgen",
"windows-link",
]
[[package]] [[package]]
name = "color-eyre" name = "color-eyre"
version = "0.6.5" version = "0.6.5"
@ -468,12 +436,6 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
[[package]] [[package]]
name = "finl_unicode" name = "finl_unicode"
version = "1.5.0" version = "1.5.0"
@ -488,11 +450,11 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]] [[package]]
name = "flexi_logger" name = "flexi_logger"
version = "0.29.8" version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88a5a6882b2e137c4f2664562995865084eb5a00611fba30c582ef10354c4ad8" checksum = "5e87b74024da93123949cca26cb6e366744234fdd4d7914eb3dfeab0baa82d51"
dependencies = [ dependencies = [
"chrono", "jiff",
"log", "log",
"nu-ansi-term", "nu-ansi-term",
"regex", "regex",
@ -608,30 +570,6 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "iana-time-zone"
version = "0.1.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]] [[package]]
name = "ident_case" name = "ident_case"
version = "1.0.1" version = "1.0.1"
@ -701,6 +639,58 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jiff"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5d126d72eb017f10b302e73bdeca446bea405ee449af4d9e7866d6b082d83e"
dependencies = [
"jiff-core",
"jiff-static",
"jiff-tzdb-platform",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
]
[[package]]
name = "jiff-core"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8"
dependencies = [
"log",
]
[[package]]
name = "jiff-static"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0127e9bde3c6130d6169e7d8d68676e4be69c4bf7573c308b6f960a5089c428"
dependencies = [
"jiff-core",
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "jiff-tzdb"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12e71a1b68a875a44a33bb7a1dd84392cb77145a3367a552a3cfe6a4f5cf3afc"
[[package]]
name = "jiff-tzdb-platform"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc65b284afcfa8f6cf189c7274c805505314a7ab975c60e1f548bff56525420e"
dependencies = [
"jiff-tzdb",
]
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.106" version = "0.3.106"
@ -1167,6 +1157,15 @@ version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
[[package]]
name = "portable-atomic-util"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
dependencies = [
"portable-atomic",
]
[[package]] [[package]]
name = "powerfmt" name = "powerfmt"
version = "0.2.0" version = "0.2.0"
@ -1374,9 +1373,9 @@ dependencies = [
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "1.1.5" version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"errno", "errno",
@ -1487,12 +1486,6 @@ dependencies = [
"lazy_static", "lazy_static",
] ]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]] [[package]]
name = "signal-hook" name = "signal-hook"
version = "0.3.18" version = "0.3.18"
@ -1756,11 +1749,11 @@ checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]] [[package]]
name = "tiny-wb" name = "tiny-wb"
version = "0.1.3-rc.2" version = "0.1.5"
dependencies = [ dependencies = [
"chrono",
"color-eyre", "color-eyre",
"flexi_logger", "flexi_logger",
"jiff",
"log", "log",
"ratatui", "ratatui",
"serde", "serde",
@ -2121,65 +2114,12 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "windows-link" name = "windows-link"
version = "0.2.1" version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.52.0" version = "0.52.0"

View File

@ -1,8 +1,8 @@
[package] [package]
name = "tiny-wb" name = "tiny-wb"
version = "0.1.3-rc.2" version = "0.1.5"
edition = "2021" edition = "2021"
rust-version = "1.88.0" rust-version = "1.91.0"
license = "MIT" license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/idle-org/tiny-wb" repository = "https://proxy.dandaedre.com/gitea/idle-org/tiny-wb"
@ -49,9 +49,9 @@ path = "tests/mock_device.rs"
required-features = ["mock"] required-features = ["mock"]
[dependencies] [dependencies]
chrono = "0.4.38"
color-eyre = { version = "0.6.3", optional = true } color-eyre = { version = "0.6.3", optional = true }
flexi_logger = { version = "0.29.0", optional = true } flexi_logger = { version = "0.32.0", optional = true }
jiff = "1.0.1"
log = "0.4.22" log = "0.4.22"
ratatui = { version = "=0.30.2", optional = true } ratatui = { version = "=0.30.2", optional = true }
serde = { version = "1.0.210", features = ["derive"] } serde = { version = "1.0.210", features = ["derive"] }

4
Jenkinsfile vendored
View File

@ -16,12 +16,12 @@ pipeline {
RUST_BACKTRACE = '1' RUST_BACKTRACE = '1'
// LTS-like compatibility floor verified by the dedicated MSRV stage. // LTS-like compatibility floor verified by the dedicated MSRV stage.
MSRV = '1.88.0' MSRV = '1.91.0'
// Supply-chain tools are pinned for reproducible policy behavior. // Supply-chain tools are pinned for reproducible policy behavior.
CARGO_AUDIT_VERSION = '0.22.2' CARGO_AUDIT_VERSION = '0.22.2'
CARGO_DENY_VERSION = '0.20.2' CARGO_DENY_VERSION = '0.20.2'
CARGO_LLVM_COV_VERSION = '0.6.16' CARGO_LLVM_COV_VERSION = '0.9.1'
BADGE_ROOT = '/mnt/assets/coverage' BADGE_ROOT = '/mnt/assets/coverage'
BADGE_OWNER = 'idle-org' BADGE_OWNER = 'idle-org'
BADGE_PROJECT = 'tiny-wb' BADGE_PROJECT = 'tiny-wb'

158
README.md
View File

@ -1,89 +1,125 @@
# tiny-wb <p align="center">
<img src="docs/images/project-icon.png" width="96" height="96" alt="tiny-wb icon">
</p>
<h1 align="center">tiny-wb</h1>
![tiny-wb version](https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/version.svg) ![tiny-wb version](https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/version.svg)
![Test status](https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/test.svg) ![Test status](https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/test.svg)
![Line coverage](https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/coverage.svg) ![Line coverage](https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/coverage.svg)
`tiny-wb` is an interactive terminal application for acquiring a frequency Scan a frequency range with your **tinySA**, see the spectrum in your terminal,
sweep from a tinySA over its USB serial console, plotting the result, and and save the measurements as CSV. Start with one scan; no configuration-file
exporting it as CSV. It is intended for tinySA users who want a repeatable scan editing is needed.
workflow and for Rust applications that need its reusable acquisition library.
## Support status ## Open source and development
- tinySA Basic low and high inputs are supported through 960 MHz, subject to tiny-wb is open-source software under the [MIT license](LICENSE). Its
the instrument's path limits. development includes LLM-generated or LLM-assisted work, with human review.
- tinySA Ultra and Ultra+ detection and acquisition are implemented for the It is used in professional settings; supported workflows and current
shared 0.1–800 MHz normal range, but still await physical hardware limitations are documented in this repository.
qualification.
See the [compatibility matrix](docs/tiny-wb-operations.md#compatibility-matrix) ## Get running
and [Ultra support scope](docs/ultra-support.md) before relying on a particular
model, range, or mode.
## Requirements You need a powered tinySA Basic, Ultra or supported Ultra+, a **data-capable USB
cable**, and access to its serial port. Close other software using the tinySA.
For a first communications check, leave external RF sources disconnected.
Before connecting a signal, read the [safe-operation guide](docs/tinysa-field-guide.md#safe-operation-read-before-connecting-a-signal).
- Rust 1.88.0 or newer To build from source, install Rust **1.91 or newer**, then run:
- A powered tinySA Basic, Ultra, or Ultra+ and a data-capable USB cable
- Permission to open the instrument's serial port
Do not connect an unknown RF source directly to a tinySA. Use suitable external
attenuation for transmitters and a DC block where a DC component may be present.
Read the [safe-operation guidance](docs/tinysa-field-guide.md#safe-operation-read-before-connecting-a-signal)
before connecting a signal.
## Build and run
From the repository root:
```console ```console
cargo run --release git clone https://proxy.dandaedre.com/gitea/idle-org/tiny-wb.git
cd tiny-wb
cargo run --locked --release
``` ```
On Linux the serial device is commonly `/dev/ttyACM0`; on Windows it appears as Already have the checkout? Run just the last command from its root. On Linux,
a COM port. If the port cannot be opened, follow the building also requires the libudev development package and `pkg-config`; this
[serial-permission guidance](docs/tiny-wb-operations.md#serial-permissions). checkout's linker configuration uses `lld`.
Use Left/Right or `h`/`l` to select a field, Up/Down or `k`/`j` to change it, ## Your first scan
Enter to advance, and `q` or Escape to quit. A successful scan displays a trace
and writes a collision-safe `scan_*.csv` file in the current directory. CSV
frequencies are in MHz and levels are in dBm.
## Configuration and documentation 1. **Connect by USB and choose the port.** On the connection screen, select your
tinySA's port with the arrow keys. Linux commonly uses `/dev/ttyACM0`; Windows
uses a COM port. On macOS, select the enumerated USB serial device. Leave the
baud rate at **115200** for the first attempt and press **Enter**.
2. **Choose a small range.** Try **Start 280**, **Stop 320** (MHz), **Points 1001**,
and **Repeat 1**. This range uses the Basic's low input and is also within the
supported Ultra normal range. For a connected RF signal, use the appropriate
instrument input and safe signal level.
3. **Enter the values.** **Left/Right** selects a field. Type digits for a
frequency or point count, then press **Enter** to apply that value. Use
**Up/Down** to adjust a value, including Repeat. Once all fields are set,
press **Enter** again to start the scan.
4. **Read the plot.** Wait for the scan to finish. Frequency runs left to right
in **MHz**; level is in **dBm**. A higher point means a stronger signal.
The app automatically saves a `scan_*.csv` in your current directory.
The selected settings are saved to `config.toml`, or to the path in ![Scan setup with Start 280 MHz, Stop 320 MHz, 1001 points and Repeat 1](docs/images/scan-settings.png)
`TINY_WB_CONFIG`. Start with the commented [default configuration](config/default.toml)
and consult the [configuration guide](docs/configuration.md) for validation,
units, output, and logging settings.
- [Compatibility, operation, and troubleshooting](docs/tiny-wb-operations.md) *Scan settings in the real application. Screenshots use the mock device; no
- [Hardware validation checklist](docs/hardware-validation.md) physical instrument or RF source is needed to reproduce this demonstration.*
- [USB console and `scanraw` protocol](docs/usb-protocol.md)
- [Documentation index](docs/README.md)
## Development ![Completed simulated scan with a peak near 300 MHz and the visible-peak readout enabled](docs/images/scan-result.png)
The core protocol, transport, acquisition, and CSV code can be tested without *Example result from simulated data, with **m** pressed to show the peak.
a terminal or physical instrument: Your real trace will depend on the signals and measurement setup.*
## Explore and save
| Key on the result screen | Action |
| --- | --- |
| `m` | Show or hide the strongest visible sample's frequency and level |
| `+` / `-` | Zoom in / out |
| Left / Right | Pan across the frequency range |
| `0` | Return to the full range |
| `r` | Repeat the same scan and save a new CSV |
| `n` | Edit the settings for a new scan |
| `q` | Quit |
CSV columns are **frequency in MHz, level in dBm**; by default there is no
header. Each successful scan gets a new filename. To reopen a saved scan
without connecting a device, replace `scan.csv` with your file:
```console ```console
cargo fmt --all -- --check cargo run --locked --release -- --view scan.csv
cargo test --locked --all-targets --all-features
cargo clippy --locked --all-targets --all-features -- -D warnings
``` ```
Run the complete local CI sequence in Want repeated sweeps? Start with `cargo run --locked --release -- --live`, then
[Security, dependency policy, and MSRV](docs/security-and-ci.md#local-verification). choose the connection and range as above. In live mode, **s** saves the visible
See the [architecture guide](docs/architecture.md), trace and **q** stops after the current sweep and saves it. See
[testing guide](docs/testing.md), and [contributor instructions](AGENTS.md) [live controls](docs/tiny-wb-operations.md#live-display) for averaging and hold modes.
before changing behavior.
## Support ## If something does not work
Report bugs in the [project issue tracker](https://proxy.dandaedre.com/gitea/idle-org/tiny-wb/issues). - **No port, or access denied?** Check the USB cable, close other serial software,
Include the details from the and follow the [serial-permission guide](docs/tiny-wb-operations.md#serial-permissions).
[reproducible bug-report checklist](docs/tiny-wb-operations.md#reproducible-bug-report-checklist). - **Timeout or no instrument detected?** Check the selected port and power, then
consult [troubleshooting](docs/tiny-wb-operations.md#troubleshooting).
- **No tinySA yet?** Follow the [mock-device walkthrough](docs/mock-device.md)
to try the same screens and CSV workflow with simulated data.
## License Settings are saved automatically in `config.toml`. See the
[configuration guide](docs/configuration.md) for output directories, keyboard
bindings and the `TINY_WB_CONFIG` override.
tiny-wb is available under the [MIT License](LICENSE). ## Supported instruments and more
Basic low/high acquisition is supported through 960 MHz, subject to input-path
limits. Ultra-family normal-mode support covers 0.1–800 MHz; detected Ultra+
ZS406 devices also support 0.1–900 MHz and opt-in Ultra mode through 5.4 GHz.
ZS407 extended mode and harmonic reception are not supported. Check the
[compatibility matrix](docs/tiny-wb-operations.md#compatibility-matrix) and
[Ultra support scope](docs/ultra-support.md) before choosing a wider range.
Hardware communications checks do not establish RF accuracy.
- [Operations and detailed controls](docs/tiny-wb-operations.md)
- [Linux, Windows and macOS release builds](docs/releases.md)
- [Reusable Rust library](docs/library.md)
- [Development and verification](docs/security-and-ci.md#local-verification)
- [Documentation index](docs/README.md) · [Contributor instructions](AGENTS.md)
Report bugs in the [issue tracker](https://proxy.dandaedre.com/gitea/idle-org/tiny-wb/issues)
with the [reproduction details](docs/tiny-wb-operations.md#reproducible-bug-report-checklist).
Licensed under the [MIT License](LICENSE).

View File

@ -27,6 +27,10 @@ preferred_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]
# Detect Basic versus Ultra from version/info and apply the corresponding scan # Detect Basic versus Ultra from version/info and apply the corresponding scan
# profile. `basic` or `ultra` can require (but never fake) an expected family. # profile. `basic` or `ultra` can require (but never fake) an expected family.
device_model = "auto" device_model = "auto"
# Permit a detected ZS406 to enter Ultra mode for analyzer scans above its
# 900 MHz normal-mode ceiling, up to 5.4 GHz. This changes instrument state and
# acknowledges Ultra-mode alias/spur/LO-leakage limitations; it never enables RF output.
enable_ultra_mode = false
# Select the detected model's native scanraw bias: Basic 128, Ultra 174. # Select the detected model's native scanraw bias: Basic 128, Ultra 174.
auto_zero_offset = true auto_zero_offset = true
# Manual fallback used only when auto_zero_offset is false. The selected value # Manual fallback used only when auto_zero_offset is false. The selected value
@ -48,6 +52,14 @@ poll_interval_ms = 16
chart_min_dbm = -128.0 chart_min_dbm = -128.0
chart_max_dbm = 0.0 chart_max_dbm = 0.0
[ui.bindings]
# Plot navigation. Values are single characters or left/right/home.
zoom_in = ["+", "="]
zoom_out = ["-"]
pan_left = ["left", "h"]
pan_right = ["right", "l"]
reset_view = ["0", "home"]
[output] [output]
directory = "." directory = "."
filename_prefix = "scan" filename_prefix = "scan"

View File

@ -1,4 +1,5 @@
# Synthetic Ultra identity/syntax; production supports the common 0.1–800 MHz range. # Synthetic generic Ultra identity/syntax. Production additionally recognizes
# explicit ZS406 identity for normal scans through 900 MHz and opt-in Ultra mode.
model = "ultra" model = "ultra"
echo = true echo = true
read_chunk_bytes = 7 read_chunk_bytes = 7

View File

@ -51,6 +51,7 @@ grows into many chapters, the files are already organized so that a future
- [Testing](testing.md): regression seams and hardware verification boundaries. - [Testing](testing.md): regression seams and hardware verification boundaries.
- [Agent/contributor guidance](../AGENTS.md): code structure, comments, documentation and atomic commits. - [Agent/contributor guidance](../AGENTS.md): code structure, comments, documentation and atomic commits.
- [Releases](releases.md): release wrapper, prerequisites, collision checks and publication policy. - [Releases](releases.md): release wrapper, prerequisites, collision checks and publication policy.
- [macOS cross-compilation](macos.md): automated Apple Silicon and Intel builds from Linux.
- [Basic and Ultra support](ultra-support.md): implemented range, model detection and qualification status. - [Basic and Ultra support](ultra-support.md): implemented range, model detection and qualification status.
- [Feature roadmap](roadmap.md): model-aware Basic/Ultra completion tasks. - [Feature roadmap](roadmap.md): model-aware Basic/Ultra completion tasks.
- [Implementation task backlog](../task.md): detailed milestones and optional stretch goals. - [Implementation task backlog](../task.md): detailed milestones and optional stretch goals.

View File

@ -19,10 +19,11 @@ widgets, port discovery, worker threads, or the application's working directory.
| `src/mock/` | Opt-in bounded device simulation and stream server. | | `src/mock/` | Opt-in bounded device simulation and stream server. |
| `examples/mock-tinysa-server.rs` | Portable TCP listener for the mock, outside release binaries. | | `examples/mock-tinysa-server.rs` | Portable TCP listener for the mock, outside release binaries. |
| `src/acquisition.rs` | Command ordering, progress events, frame decoding and resume attempts. | | `src/acquisition.rs` | Command ordering, progress events, frame decoding and resume attempts. |
| `src/export.rs` | CSV serialization to a writer and collision-safe file export. | | `src/export.rs` | CSV parsing/serialization over I/O traits and collision-safe file export. |
| `src/main.rs` | Load configuration, start diagnostics, enumerate ports and manage terminal lifetime. | | `src/live.rs` | Bounded rolling average, hold and decay calculations over explicit sweeps. |
| `src/main.rs` | Select single/live/direct-view mode, load configuration, start diagnostics, enumerate ports when needed and manage terminal lifetime. |
| `src/error.rs` | Application/UI boundary errors with original context. | | `src/error.rs` | Application/UI boundary errors with original context. |
| `src/scan.rs` | Open the configured connection, adapt core events to shared progress, and export successful acquisitions. | | `src/scan.rs` | Open the configured connection, reopen once after empty/unknown identity, adapt core events to shared progress, and export successful acquisitions. |
| `src/ui/mod.rs` | Screen transitions, keyboard handling, worker startup and progress reconciliation. | | `src/ui/mod.rs` | Screen transitions, keyboard handling, worker startup and progress reconciliation. |
| `src/ui/state.rs` | UI state, configured port/baud choices and bounded numeric input. | | `src/ui/state.rs` | UI state, configured port/baud choices and bounded numeric input. |
| `src/ui/view.rs` | Ratatui rendering and selection styling. | | `src/ui/view.rs` | Ratatui rendering and selection styling. |
@ -68,8 +69,12 @@ the original error's message instead of a second exhaustive mapping.
```text ```text
SelectingConnection -> SelectingScan -> Scanning -> Complete -> exit SelectingConnection -> SelectingScan -> Scanning -> Complete -> exit
^ | |
+---- n -------+ +-- r --> Scanning
| | | | | |
+------------------+-------------+-> Error -> exit +------------------+-------------+-> Error -> exit
CSV file -------------------------------------> Complete -> exit
--live: SelectingConnection -> SelectingScan -> Live --stop+save--> exit
``` ```
The constructor takes configuration and enumerated ports as values, without The constructor takes configuration and enumerated ports as values, without
@ -77,9 +82,23 @@ reading files. Selection is clamped before rendering, including empty lists.
Before a scan starts, the controller validates the complete selected settings Before a scan starts, the controller validates the complete selected settings
and request, atomically saves settings, then starts a worker. The controller and request, atomically saves settings, then starts a worker. The controller
reconciles worker status before drawing; rendering does not consume samples. reconciles worker status before drawing; rendering does not consume samples.
The complete screen owns one named plot with an independent frequency viewport.
An acquired result can repeat its retained request/settings or return to the
prefilled scan editor; a standalone CSV remains view-only.
Zooming and panning mutate only that viewport, not sample data. This plot
boundary can grow into a tabbed collection without coupling CSV parsing or
acquisition to Ratatui.
Live mode uses repeated complete snapshots over one configured connection. The
worker publishes only decoded sweeps into a bounded `TraceBuffer`; rendering
copies at most once per completed sweep. Stop and save requests cross the shared
state boundary, while device I/O and CSV creation remain in the worker. Native
continuous `scanraw` is intentionally deferred because it needs verified abort
syntax and stream resynchronization.
The terminal guard restores terminal modes on ordinary returns and unwinding. The terminal guard restores terminal modes on ordinary returns and unwinding.
Configuration, logging and enumeration errors occur before terminal takeover. Configuration and direct-view CSV errors occur before logger initialization;
logging and enumeration errors occur before terminal takeover.
Process termination or release-mode panic abort cannot be recovered by a guard. Process termination or release-mode panic abort cannot be recovered by a guard.
## Acquisition and protocol boundary ## Acquisition and protocol boundary
@ -148,7 +167,7 @@ See [configuration](configuration.md) for settings, paths and exact behavior.
The core uses standard-library byte decoding instead of `packed_struct`, and The core uses standard-library byte decoding instead of `packed_struct`, and
buffered framing instead of a separate direct `memchr` dependency. Transitive buffered framing instead of a separate direct `memchr` dependency. Transitive
`memchr` use elsewhere in the graph is unrelated. Serde/TOML handle settings; `memchr` use elsewhere in the graph is unrelated. Serde/TOML handle settings;
serialport, Ratatui, chrono, log/flexi_logger, color-eyre and thiserror retain serialport, Ratatui, jiff, log/flexi_logger, color-eyre and thiserror retain
their device, presentation, timestamp and error-reporting roles. their device, presentation, timestamp and error-reporting roles.
Library consumers can omit terminal and serial dependencies; see [feature selection](library.md). Library consumers can omit terminal and serial dependencies; see [feature selection](library.md).

View File

@ -31,23 +31,26 @@ points = 10001
repeat = 1 repeat = 1
``` ```
Start/stop frequencies are **MHz**. The Basic envelope remains 0–960 MHz, Start/stop frequencies are **MHz**. The shared entry envelope is 0–5,400 MHz,
with stop at least 10 MHz; the protocol separately rejects spans that cannot with stop at least 10 MHz; detected model/revision policy applies before the
use one input path. Values must be ordered. The selected baud rate must be in instrument is mutated. Basic remains limited to 960 MHz, generic Ultra to 800
`serial.baudrates`; points and repeat must fit the configured bounds. MHz, and ZS406 normal mode to 900 MHz. Values must be ordered. The selected baud
rate must be in `serial.baudrates`; points and repeat must fit the configured bounds.
| Section | Settings and units | | Section | Settings and units |
| --- | --- | | --- | --- |
| `serial` | Read timeout and command/settling/pre-scan delays in milliseconds; bounded text response size in bytes; baud-rate choices and preferred ports. | | `serial` | Read timeout and command/settling/pre-scan delays in milliseconds; bounded text response size in bytes; baud-rate choices and preferred ports. |
| `scan` | Raw zero offset in dB, frequency/sample keyboard steps, sample/repeat limits, frequency-axis convention, and legacy pre-scan toggle. | | `scan` | Raw zero offset in dB, explicit ZS406 Ultra-mode opt-in, frequency/sample keyboard steps, sample/repeat limits, frequency-axis convention, and legacy pre-scan toggle. |
| `ui` | Event polling interval in milliseconds and finite increasing chart bounds in dBm. | | `ui` | Event polling interval in milliseconds, finite increasing chart bounds in dBm, and plot navigation bindings. |
| `output` | CSV directory, filename prefix, and optional column header. | | `output` | CSV directory, filename prefix, and optional column header. |
| `logging` | Logger filter expression and destination directory. | | `logging` | Logger filter expression and destination directory. |
`scan.device_model = "auto"` detects the family before changing settings. `scan.device_model = "auto"` detects the family before changing settings.
`scan.auto_zero_offset = true` selects Basic 128 or Ultra 174 and verifies the `scan.auto_zero_offset = true` selects Basic 128 or Ultra 174 and verifies the
`zero` readback. To retain a manual `scan.zero_offset`, set automatic selection `zero` readback. To retain a manual `scan.zero_offset`, set automatic selection
to false. See [support and migration](ultra-support.md). The wire record has no to false. `scan.enable_ultra_mode = true` explicitly permits a detected ZS406
to receive above 900 MHz through 5.4 GHz; it is false by default and never
enables generator output. See [support and migration](ultra-support.md). The wire record has no
model-specific padding; see [level conversion](usb-protocol.md#level-conversion-and-zero). model-specific padding; see [level conversion](usb-protocol.md#level-conversion-and-zero).
For example, this partial file changes the serial timeout and output format For example, this partial file changes the serial timeout and output format
@ -78,6 +81,20 @@ files that explicitly contain `frequency_axis = "inclusive"` keep their old
labels; partial configurations that omit the key adopt the corrected default. labels; partial configurations that omit the key adopt the corrected default.
See [frequency assignment](usb-protocol.md#frequency-assignment). See [frequency assignment](usb-protocol.md#frequency-assignment).
`[ui.bindings]` configures completed, CSV, and live plot navigation. Each action
is a nonempty array of unique bindings. A binding is one printable character or
`left`, `right`, or `home`; bindings cannot overlap between actions and `q`
remains reserved for exit. The defaults are:
```toml
[ui.bindings]
zoom_in = ["+", "="]
zoom_out = ["-"]
pan_left = ["left", "h"]
pan_right = ["right", "l"]
reset_view = ["0", "home"]
```
The preparatory `scan START STOP 290 101` remains enabled by default with The preparatory `scan START STOP 290 101` remains enabled by default with
`scan.legacy_pre_scan = true` for compatibility. Its undocumented output mask `scan.legacy_pre_scan = true` for compatibility. Its undocumented output mask
is not a tunable protocol contract. Disable the step only after checking the is not a tunable protocol contract. Disable the step only after checking the

View File

@ -2,7 +2,7 @@
This checklist qualifies one physical instrument and firmware build. A passing This checklist qualifies one physical instrument and firmware build. A passing
mock or CI run is not hardware evidence. Run the validator once with a tinySA mock or CI run is not hardware evidence. Run the validator once with a tinySA
Basic and once with a tinySA Ultra; keep their reports separate. Basic and once with each supported tinySA Ultra profile; keep reports separate.
## Before each run ## Before each run
@ -13,6 +13,7 @@ Basic and once with a tinySA Ultra; keep their reports separate.
can open the USB serial port without running the validator as root. can open the USB serial port without running the validator as root.
- [ ] If the front-panel configuration matters, save a preset. The validator - [ ] If the front-panel configuration matters, save a preset. The validator
changes repeat, raw zero offset, input mode, sweep limits, and pause state. changes repeat, raw zero offset, input mode, sweep limits, and pause state.
The ZS406 profile also enables Ultra mode, which firmware may retain.
From the repository root, run exactly one command: From the repository root, run exactly one command:
@ -26,6 +27,12 @@ For an Ultra, use:
scripts/test-hardware.sh ultra scripts/test-hardware.sh ultra
``` ```
For the ZS406 normal and non-harmonic Ultra ranges, use:
```console
scripts/test-hardware.sh zs406
```
The script asks when to unplug and plug the instrument so it can detect the new The script asks when to unplug and plug the instrument so it can detect the new
serial port. If discovery is ambiguous, choose from the displayed ports. To skip serial port. If discovery is ambiguous, choose from the displayed ports. To skip
discovery, pass `--port /dev/ttyACM0` or `--port COM7`. It builds the validator, discovery, pass `--port /dev/ttyACM0` or `--port COM7`. It builds the validator,
@ -76,6 +83,30 @@ or above 350 MHz, level accuracy, or frequency accuracy. Those require
model-aware acquisition and a controlled reference source; do not infer them model-aware acquisition and a controlled reference source; do not infer them
from this communications test. from this communications test.
## ZS406 range acceptance
- [ ] The rear label says ZS406 and identity reports `ZS406` or hardware V0.4.6.
- [ ] `normal` (0.1–900 MHz) and `ultra` (900 MHz–5.4 GHz) each report `PASS`
and create 101-row CSV files with units headers.
- [ ] The report records `enable_ultra_mode=false` for `normal`, `true` for
`ultra`, and `raw_level_offset_db=174` for both.
- [ ] The live front-panel sweep resumes and the final `zs406-report.txt` records
affirmative operator confirmation.
This validates identity, accepted sweep bounds, command ordering, binary
framing and finite decoded values across both ranges. With no controlled RF
source it does not establish frequency accuracy, level accuracy, sensitivity,
spur rejection or the authenticity of displayed signals.
### Recorded ZS406 evidence
The ZS406 acquisition profile was validated on physical hardware on 2026-10-07
with hardware V0.4.6 and firmware `tinySA4_v1.4-197-gaa78ccc`. The 100 kHz–900
MHz normal scan and 900 MHz–5.4 GHz Ultra scan each returned 101 finite samples,
confirmed the requested sweep boundaries, produced CSV output, and resumed the
front-panel sweep. The RF input was unconnected. This is communications,
range-acceptance and workflow evidence, not RF frequency or level calibration.
## Failure record ## Failure record
- [ ] Keep the generated report and any completed CSV; do not edit them. - [ ] Keep the generated report and any completed CSV; do not edit them.

20
docs/images/README.md Normal file
View File

@ -0,0 +1,20 @@
# README screenshots
`scan-settings.png` and `scan-result.png` show the real tiny-wb terminal UI,
captured on 2026-10-20 from a Linux release binary. Input comes from the
[Basic mock device](../mock-device.md), not a physical instrument. The screenshot
binary identifies itself as `0.1.4-8ed07cb`; later release/documentation changes
did not change this UI.
To reproduce the screens, follow the mock-device walkthrough using a temporary
copy of the client settings. Set start to 280 MHz, stop to 320 MHz, points to
1001 and repeat to 1. Capture the scan-settings screen after confirming the
connection; start the scan and press `m` on the completed plot to show its peak.
The mock's peak is near 300 MHz. The displayed CSV filename varies with time.
These PNGs were rendered from the application's captured pseudo-terminal output
using pyte 0.8.2 and Pillow 13.0.0, with DejaVu Sans Mono and a dark terminal
palette. The setup screen is 132 columns by 13 rows; the result is 132 by 26.
Colors were enabled (`NO_COLOR` unset). No UI labels or trace values were drawn
by hand. The mock run completed acquisition and exported one CSV in a temporary
directory. Screenshot tooling is not an application or build dependency.

View File

@ -0,0 +1,5 @@
# Project icon provenance
`project-icon.png` is the existing tiny-wb repository avatar, retrieved from the
maintainer's Gitea repository on 2026-11-20 and reused unchanged for the project
README and Idle organisation profile. No new logo or license is introduced.

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 KiB

BIN
docs/images/scan-result.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@ -1,7 +1,7 @@
# Rust library integration # Rust library integration
The package builds both `tiny_wb` (Rust library) and `tiny-wb` (terminal app). The package builds both `tiny_wb` (Rust library) and `tiny-wb` (terminal app).
Rust 1.88 or newer is required. To integrate a checkout without terminal, serial, Rust 1.91 or newer is required. To integrate a checkout without terminal, serial,
libudev or Windows resource dependencies: libudev or Windows resource dependencies:
```toml ```toml
@ -29,7 +29,10 @@ or inject your own adapter. Transport deadlines belong to the adapter; an
arbitrary blocking `Read` implementation cannot be interrupted by the shell. arbitrary blocking `Read` implementation cannot be interrupted by the shell.
`acquisition::acquire` accepts a validated Basic `ScanRequest`, scan/timing `acquisition::acquire` accepts a validated Basic `ScanRequest`, scan/timing
settings and a progress callback, and returns samples without opening files. settings and a progress callback, and returns samples without opening files.
`export::write_csv` writes those samples to any writer. `export::write_csv` writes those samples to any writer. `export::read_csv`
loads the same two-column, optionally headed format from any `BufRead` source;
it validates finite values and nondecreasing MHz frequencies without depending
on the terminal renderer.
```rust ```rust
use tiny_wb::{config::Config, connection::open_connection, use tiny_wb::{config::Config, connection::open_connection,

58
docs/macos.md Normal file
View File

@ -0,0 +1,58 @@
# Building macOS binaries from Linux
Use the [release workflow](releases.md) with a working Podman or Docker backend
and a publisher supporting automated Apple builds:
```console
./release.sh --compile-only
```
This builds and packages Apple Silicon and Intel macOS alongside Linux and
Windows. To build only the Apple targets:
```console
./release.sh --compile-only --target aarch64-apple-darwin --target x86_64-apple-darwin
```
Select the backend with `CROSS_CONTAINER_ENGINE=podman` or `docker`. Network
access is needed for initial container and crate downloads. No Mac, host Xcode
installation or publication token is required. The standalone Apple build
wrapper has been removed; the publisher owns compilation and packaging.
## Toolchain and outputs
[`rust-release.toml`](../rust-release.toml) declares the immutable cargo-zigbuild
image digest, SDK path and **macOS 13.0** deployment minimum for both Apple
architectures. See the [release contract and prerequisites](releases.md) for
tool installation, artifact naming and the compiler/SDK policy. The upstream
[cargo-zigbuild Dockerfile](https://github.com/rust-cross/cargo-zigbuild/blob/main/Dockerfile)
documents SDK provenance; our configured digest identifies the actual image.
The SDK supplies IOKit and CoreFoundation for the existing `serialport`
dependency. The normal default features include terminal UI and serial transport.
Linux's libudev and Windows's resource compiler are not needed for Apple targets.
The publisher prints its output directory under ignored `dist/release-*/`.
Each Apple target produces a standalone executable and a cargo-binstall `.tgz`
archive, covered by the common `SHA256SUMS`. These are separate Mach-O binaries;
there is no universal binary, `.app` bundle, Developer ID signature or notarization.
## Verification
Run the normal [local quality gates](security-and-ci.md#local-verification),
`python3 scripts/test-release.py`, and the compile-only command above.
The publisher checks Apple architecture, `LC_BUILD_VERSION` minimum of 13.0,
system dynamic dependencies, archive layout and checksums. Inspect the printed
output directory and run `sha256sum -c SHA256SUMS` from that directory.
Linux cannot execute the Apple binaries, so their runtime checks are skipped.
The [recorded four-target verification](releases.md#macos-migration-verification-on-2026-10-20)
used rootless Podman and passed these checks for both Apple architectures.
Docker execution, native macOS terminal interaction, serial enumeration, actual
USB acquisition, Gatekeeper behavior, Jenkins and publication remain unverified.
On a Mac, first run `./tiny-wb --help`, then use the
[mock-device workflow](mock-device.md) for simulated acquisition and the
[hardware validation guide](hardware-validation.md) for a physical instrument.
Choose the actual enumerated macOS serial device in the UI; Linux/Windows
preferred port names in the defaults are preferences, not required devices.

View File

@ -80,7 +80,9 @@ Other commands or invalid arguments return an explicit error. No calibration,
RF output, display capture, arbitrary firmware behavior or complete console RF output, display capture, arbitrary firmware behavior or complete console
emulation is claimed. The Ultra profile exercises automatic detection, native emulation is claimed. The Ultra profile exercises automatic detection, native
offset readback and low-input acquisition. Production Ultra scans are limited offset readback and low-input acquisition. Production Ultra scans are limited
to 0.1–800 MHz; the mock's larger synthetic range is not a production capability. to its detected model/revision policy; the mock's larger synthetic range is not
a production capability. ZS406 limits are covered by identity-policy transcript
tests rather than inferred from this generic Ultra mock.
See [support scope](ultra-support.md). See [support scope](ultra-support.md).
Samples use the reviewed firmware's integer-divided, single-precision Samples use the reviewed firmware's integer-divided, single-precision

View File

@ -0,0 +1,35 @@
# tiny-wb 0.1.5
This release adds Apple Silicon and Intel macOS downloads alongside Linux and
Windows. The README now walks new users through a first scan, with screenshots
of the real application using clearly labelled simulated data.
## Downloads
Choose the archive for your computer, extract it, and run `tiny-wb` (or
`tiny-wb.exe` on Windows) from a terminal:
| Platform | Target |
| --- | --- |
| Linux x86-64 (glibc, system libudev required) | `x86_64-unknown-linux-gnu` |
| Windows x86-64 | `x86_64-pc-windows-gnu` |
| macOS Apple Silicon | `aarch64-apple-darwin` |
| macOS Intel | `x86_64-apple-darwin` |
Each target has a `.tgz` archive and a standalone executable. `SHA256SUMS`
covers all eight payload files.
macOS requires version 13.0 or newer. These are separate, unsigned and
unnotarized command-line executables, not universal binaries or `.app` bundles.
The release pipeline checks Mach-O architecture, deployment minimum, system
library paths, archive layout and checksums. Native macOS execution and USB
hardware behavior remain unverified by this Linux release workflow.
## Release workflow
All four targets now use `release.sh` and `rust_realease`. Apple builds use the
pinned cargo-zigbuild image; Linux and Windows use Cross. The obsolete standalone
macOS build script and its tests have been removed.
See the [README](https://proxy.dandaedre.com/gitea/idle-org/tiny-wb/src/tag/0.1.5/README.md)
for setup, your first scan, result controls and CSV export.

View File

@ -1,5 +1,10 @@
# Releasing tiny-wb # Releasing tiny-wb
The release matrix includes Linux, Windows, Apple Silicon and Intel macOS.
Apple builds require a Linux release host and macOS 13.0 or newer to run.
See [macOS cross-compilation](macos.md) for platform requirements and native
validation.
`release.sh` delegates to the deliberately named `release.sh` delegates to the deliberately named
[`rust_realease`](https://proxy.dandaedre.com/gitea/idle-org/rust_realease). [`rust_realease`](https://proxy.dandaedre.com/gitea/idle-org/rust_realease).
It is based on the It is based on the
@ -17,8 +22,8 @@ with a dry run and obtain publication authorization separately.
| Binary | `tiny-wb` (`tiny-wb.exe` on Windows); the library is not a release binary. | | Binary | `tiny-wb` (`tiny-wb.exe` on Windows); the library is not a release binary. |
| Version | Literal `[package].version` in `Cargo.toml`; never duplicated in the wrapper. | | Version | Literal `[package].version` in `Cargo.toml`; never duplicated in the wrapper. |
| Tag | Package version without a prefix, preserving existing tags such as `0.1.1`. | | Tag | Package version without a prefix, preserving existing tags such as `0.1.1`. |
| Profile | `release`, for both targets; the older custom `windows` profile is not selected. | | Profile | `release`, for all four targets; the older custom `windows` profile is not selected. |
| Targets | `x86_64-unknown-linux-gnu`, `x86_64-pc-windows-gnu`. | | Targets | `x86_64-unknown-linux-gnu`, `x86_64-pc-windows-gnu`, `aarch64-apple-darwin`, `x86_64-apple-darwin`. |
| Artifacts | Both cargo-binstall `.tgz` archives and standalone executables, plus `SHA256SUMS`. | | Artifacts | Both cargo-binstall `.tgz` archives and standalone executables, plus `SHA256SUMS`. |
| Builds | Locked dependencies; tracked `Cargo.lock`; review toolchain/container inputs for repeatability. | | Builds | Locked dependencies; tracked `Cargo.lock`; review toolchain/container inputs for repeatability. |
| Public repository | `https://proxy.dandaedre.com/gitea/idle-org/tiny-wb`. | | Public repository | `https://proxy.dandaedre.com/gitea/idle-org/tiny-wb`. |
@ -28,9 +33,9 @@ with a dry run and obtain publication authorization separately.
`rust-release.toml` sets the target matrix, profile, tag prefix, lock policy, `rust-release.toml` sets the target matrix, profile, tag prefix, lock policy,
`GITEA_TOKEN` variable and exact origin-to-public-URL fallback. This avoids `GITEA_TOKEN` variable and exact origin-to-public-URL fallback. This avoids
copying the publisher's musl/ARM defaults: tiny-wb uses system libudev on Linux, copying the publisher's musl/ARM defaults: tiny-wb uses system libudev on Linux,
and its documented desktop platforms are Linux and Windows. FreeBSD remains and Apple targets use the publisher's direct cargo-zigbuild backend. FreeBSD
a CI host, not an additional promised release artifact. Target builds are not remains a CI host, not an additional promised release artifact. Cross-compilation
yet verified. Do not infer compatibility merely from the configured matrix. does not establish native runtime or hardware compatibility.
The fallback does not rewrite the Git origin. `Cargo.toml` records the public The fallback does not rewrite the Git origin. `Cargo.toml` records the public
repository and the publisher-compatible binstall archive layout. Tag URLs lack repository and the publisher-compatible binstall archive layout. Tag URLs lack
@ -41,6 +46,10 @@ tiny-wb-x86_64-unknown-linux-gnu-v0.1.1.tgz
tiny-wb-x86_64-unknown-linux-gnu-v0.1.1 tiny-wb-x86_64-unknown-linux-gnu-v0.1.1
tiny-wb-x86_64-pc-windows-gnu-v0.1.1.tgz tiny-wb-x86_64-pc-windows-gnu-v0.1.1.tgz
tiny-wb-x86_64-pc-windows-gnu-v0.1.1.exe tiny-wb-x86_64-pc-windows-gnu-v0.1.1.exe
tiny-wb-aarch64-apple-darwin-v0.1.1.tgz
tiny-wb-aarch64-apple-darwin-v0.1.1
tiny-wb-x86_64-apple-darwin-v0.1.1.tgz
tiny-wb-x86_64-apple-darwin-v0.1.1
SHA256SUMS SHA256SUMS
``` ```
@ -55,10 +64,10 @@ is published to crates.io. This workflow does not run `cargo publish`.
Required: Git, Cargo/Rust (at least the declared MSRV), `rust_realease`, Cross, Required: Git, Cargo/Rust (at least the declared MSRV), `rust_realease`, Cross,
and a usable Docker or Podman backend. Archives additionally need cargo-binstall and a usable Docker or Podman backend. Archives additionally need cargo-binstall
for installation verification. Local wrapper tests use Python 3.11+ (`tomllib`). for installation verification. Local wrapper tests use Python 3.11+ (`tomllib`).
There is currently no repository pin for the publisher; the inspected upstream Use a publisher containing automated Apple support, released upstream in
source identifies itself as version 0.1.4. Confirm its installed version and `0.1.6-rc.3`; older publishers may reject `[build.apple]`. There is no repository
help before use. Tool installation is a maintainer action, not performed by pin for the publisher. Confirm its installed version and help before use.
the wrapper. Upstream's preferred installation command is: Tool installation is a maintainer action, not performed by the wrapper. Upstream's preferred installation command is:
```console ```console
cargo binstall --git https://proxy.dandaedre.com/gitea/idle-org/rust_realease rust_realease cargo binstall --git https://proxy.dandaedre.com/gitea/idle-org/rust_realease rust_realease
@ -82,6 +91,20 @@ from the repository root because the publisher rejects root `pre-build`,
image's Debian/Ubuntu repositories. A caller-supplied `CROSS_CONFIG` is image's Debian/Ubuntu repositories. A caller-supplied `CROSS_CONFIG` is
intentionally replaced so releases use the reviewed, tracked configuration. intentionally replaced so releases use the reviewed, tracked configuration.
The Apple image digest, deployment minimum and SDK path are explicit in
`[build.apple]`. `CROSS_CONTAINER_ENGINE` selects the engine for both backends;
Apple builds ignore `CROSS_CONFIG`. All targets use the same release entry point.
The publisher checks Mach-O architecture, deployment minimum and system
library paths, then packages the binaries into the same release as Cross outputs.
The four-target matrix produces eight payload assets plus `SHA256SUMS`.
Apple executables are unsigned and unnotarized; there is no universal binary or
`.app` bundle. Runtime verification is explicitly skipped on Linux.
This migration follows the upstream
[automated macOS release guide](https://proxy.dandaedre.com/gitea/idle-org/rust_realease/raw/branch/main/docs/automated-macos-releases.md),
reviewed on 2026-10-20. Its reported four-target build is upstream evidence,
not a native macOS or hardware test of this checkout.
## Token handling and commands ## Token handling and commands
Store a token in a readable regular file outside the checkout, with only the Store a token in a readable regular file outside the checkout, with only the
@ -102,15 +125,19 @@ Compile-only builds do not access Gitea and need no token:
contacting Gitea. Inspect `SHA256SUMS`, archive members, executables and the contacting Gitea. Inspect `SHA256SUMS`, archive members, executables and the
binstall layout before publication. binstall layout before publication.
For authenticated dry runs and publication, set `TOKEN_FILE` in your shell to Preview the configured matrix without a token or containers:
the existing token file's path; it is not a checked-in setting:
```console ```console
./release.sh "$TOKEN_FILE" --dry-run rust_realease . --package tiny-wb --artifact-format both --dry-run
``` ```
A dry run must report the correct package, version, unprefixed tag, both targets, Dry-run and compile-only are separate modes. Dry-run does not build, create
asset names and public HTTPS destination without changing files, refs or releases. artifacts or contact the release API. For publication, set `TOKEN_FILE`
in your shell to the existing token file's path; it is not a checked-in setting.
A dry run must report the correct package, version, unprefixed tag, all four targets,
each backend, Apple image/SDK/minimum, asset names and public HTTPS destination
without changing files, refs or releases.
A successful dry run is required but does not replace collision inspection. A successful dry run is required but does not replace collision inspection.
After all readiness checks and separate publication authorization: After all readiness checks and separate publication authorization:
@ -152,14 +179,38 @@ Before publication:
Any collision stops publication. `--replace-assets` requires inspection and Any collision stops publication. `--replace-assets` requires inspection and
explicit approval to replace those exact assets; replacement is not atomic. explicit approval to replace those exact assets; replacement is not atomic.
An existing empty release can be reused only after tag/version checks pass. An existing empty release can be reused only after tag/version checks pass.
6. Run the real wrapper dry run. Resolve every prerequisite or metadata error. 6. Run the publisher dry run shown above. Resolve every prerequisite or metadata error.
Repeat tag and release/asset inspection immediately before live publication. Repeat tag and release/asset inspection immediately before live publication.
The publisher normalizes archive metadata, but this is not a bit-for-bit build The publisher normalizes archive metadata, but this is not a bit-for-bit build
reproducibility claim. Rust toolchains and Cross image digests are not pinned reproducibility claim. Host Rust toolchains and Cross image digests are not pinned
here, and `build.rs` embeds a Git revision. Record those inputs per release. here (the Apple image is pinned), and `build.rs` embeds a Git revision. Record
those inputs per release.
Use `--recompile` if a matching publisher build cache must not be reused. Use `--recompile` if a matching publisher build cache must not be reused.
## macOS migration verification on 2026-10-20
With installed `rust_realease 0.1.6-rc.3`, running
`CROSS_CONTAINER_ENGINE=podman ./release.sh --compile-only` built all four
configured targets in 177.2 seconds. It produced eight payload files and
`SHA256SUMS` under ignored `dist/release-4HIRgC/` for package version 0.1.4.
All eight checksums passed an independent `sha256sum -c SHA256SUMS` check.
The publisher validated both Apple architectures, macOS minimum 13.0, system
dynamic dependencies, archive layout and checksums; macOS runtime was skipped.
Formatting, MSRV, locked checks/tests and feature matrix, Rustdoc, Clippy,
native release build, release/macOS wrapper tests, badge tests, shell syntax
and changed local documentation links passed. Mock TCP tests required localhost
listener access outside the sandbox. No Rust behavior or Cargo dependencies
changed. ShellCheck was unavailable.
The dry run printed the expected four-target plan but reported the missing
local `0.1.4` tag (and sandbox-restricted Podman access). The compile-only run
used Podman outside the sandbox. This does not establish publication readiness:
tag/remote collision checks must still be completed for the chosen release.
Native macOS execution, hardware, Jenkins and publication were not tested.
No token was needed, and no release, tag or push was performed.
## Inspection recorded on 2026-10-04 ## Inspection recorded on 2026-10-04
- Package and binary: `tiny-wb` 0.1.1. Expected tag: `0.1.1`, not `v0.1.1`. - Package and binary: `tiny-wb` 0.1.1. Expected tag: `0.1.1`, not `v0.1.1`.

View File

@ -31,10 +31,10 @@ See [library integration](library.md) and [mock scope](mock-device.md).
## Priority 0 — trustworthy model-aware acquisition ## Priority 0 — trustworthy model-aware acquisition
Initial family detection, native-offset readback and common Ultra normal-range Initial family/revision detection, native-offset readback, common Ultra
planning are implemented; see [support status](ultra-support.md). The broader normal-range planning and the ZS406 non-harmonic Ultra profile are implemented;
P01–P04 acceptance gates below remain open pending revision-specific profiles see [support status](ultra-support.md). The broader P01–P04 acceptance gates
and hardware qualification. remain open pending further revision profiles and RF accuracy qualification.
- [ ] P01 **Inventory and capability negotiation** (depends F01–F04). Capture - [ ] P01 **Inventory and capability negotiation** (depends F01–F04). Capture
`version`, `info`, `help` and matching firmware commit/build options for Basic `version`, `info`, `help` and matching firmware commit/build options for Basic

View File

@ -7,7 +7,7 @@ runs `cargo-audit` plus `cargo-deny`. No other hardening tools are in scope.
## Rust compatibility floor ## Rust compatibility floor
The declared and CI-tested minimum supported Rust version (MSRV) is The declared and CI-tested minimum supported Rust version (MSRV) is
**Rust 1.88.0**. This is an LTS-like project policy rather than an upstream Rust **Rust 1.91.0**. This is an LTS-like project policy rather than an upstream Rust
LTS designation: Rust itself does not publish LTS toolchains. LTS designation: Rust itself does not publish LTS toolchains.
The application code and the former Ratatui 0.28 dependency could be made to The application code and the former Ratatui 0.28 dependency could be made to
@ -15,14 +15,23 @@ compile with older compilers, but that graph contained the unmaintained `paste`
crate and `lru` releases covered by RustSec soundness advisories. Ratatui 0.30.0 crate and `lru` releases covered by RustSec soundness advisories. Ratatui 0.30.0
still locked an affected optional `lru` and a vulnerable `time`. Ratatui 0.30.2 still locked an affected optional `lru` and a vulnerable `time`. Ratatui 0.30.2
is the first tested upstream line that clears those findings, and it declares is the first tested upstream line that clears those findings, and it declares
Rust 1.88.0. The project therefore treats 1.88.0 as the lowest supported clean Rust 1.88.0. That established the previous compatibility floor.
graph rather than adding advisory exceptions or local dependency patches.
`Cargo.toml` declares `rust-version = "1.88.0"`. CI installs that exact On 2026-11-20, [RUSTSEC-2026-0543](https://rustsec.org/advisories/RUSTSEC-2026-0543)
required removing chrono (all versions are unmaintained). CSV export and the
hardware-validation example now use jiff, preserving local-time filenames and
six fractional digits. flexi_logger 0.32 removes its transitive chrono dependency
and requires Rust 1.91.0, which is the new build and CI floor. Existing logging
settings remain compatible; source builders must upgrade their Rust toolchain.
The locked rustix is also updated to at least 1.1.6 for
[RUSTSEC-2026-0486](https://rustsec.org/advisories/RUSTSEC-2026-0486).
Neither advisory is ignored.
`Cargo.toml` declares `rust-version = "1.91.0"`. CI installs that exact
toolchain and runs: toolchain and runs:
```console ```console
cargo +1.88.0 check --locked --all-targets --all-features cargo +1.91.0 check --locked --all-targets --all-features
``` ```
The normal CI jobs use current stable Rust, while the MSRV job prevents source The normal CI jobs use current stable Rust, while the MSRV job prevents source
@ -118,7 +127,7 @@ Run from the repository root, in this order:
cargo audit --deny warnings cargo audit --deny warnings
cargo deny check cargo deny check
cargo fmt --all -- --check cargo fmt --all -- --check
cargo +1.88.0 check --locked --all-targets --all-features cargo +1.91.0 check --locked --all-targets --all-features
cargo check --locked --all-targets --all-features cargo check --locked --all-targets --all-features
cargo test --locked --all-targets --all-features cargo test --locked --all-targets --all-features
cargo test --locked --no-default-features --lib cargo test --locked --no-default-features --lib
@ -153,12 +162,12 @@ Repository identity and `main` were verified against the origin remote, its
HEAD, and Gitea repository metadata. The version comes from `Cargo.toml` via HEAD, and Gitea repository metadata. The version comes from `Cargo.toml` via
`cargo metadata --no-deps --locked --format-version 1`, never a Jenkins constant. `cargo metadata --no-deps --locked --format-version 1`, never a Jenkins constant.
Coverage uses pinned `cargo-llvm-cov` 0.6.16 and Rust's `llvm-tools-preview` Coverage uses pinned `cargo-llvm-cov` 0.9.1 and Rust's `llvm-tools-preview`
component. The worker also needs `jq`. Install the prerequisites and run: component. The worker also needs `jq`. Install the prerequisites and run:
```console ```console
rustup component add llvm-tools-preview rustup component add llvm-tools-preview
cargo install --locked --version 0.6.16 cargo-llvm-cov cargo install --locked --version 0.9.1 cargo-llvm-cov
mkdir -p coverage mkdir -p coverage
cargo coverage cargo coverage
``` ```
@ -170,12 +179,17 @@ cargo llvm-cov --locked --all-targets --all-features --ignore-filename-regex /re
``` ```
The enforced line-coverage floor is **85%**, measured across the library and The enforced line-coverage floor is **85%**, measured across the library and
application without excluding production sources. Local measurement on 2026-10-04 was **1,852 of 2,038 lines (90.87%)**. application without excluding production sources. Local measurement on 2026-11-21
with the pinned tool was **3,731 of 4,078 lines (91.49%)** after adding loopback
worker tests for complete single-scan export and live capture, deferred save,
and graceful shutdown.
The suite includes library, application, mock/loopback integration and startup The suite includes library, application, mock/loopback integration and startup
tests, plus separately run Rustdoc examples. Tests tests, plus separately run Rustdoc examples. Tests
cover configuration, protocol, transport, acquisition, export, UI, startup and cover configuration, protocol, transport, acquisition, export, UI, startup and
mock device behavior. The floor leaves some headroom for mock device behavior. The floor leaves headroom for platform differences; it is
platform differences; it is not evidence of device/firmware correctness. not evidence of device/firmware correctness. Version 0.9.1 excludes in-source
test bodies from the report while retaining every production module, so adding
tests does not increase the acceptance denominator.
`scripts/collect-coverage.sh` runs that command, validates the overall line `scripts/collect-coverage.sh` runs that command, validates the overall line
percentage from temporary `coverage/summary.json`, renders the coverage badge, percentage from temporary `coverage/summary.json`, renders the coverage badge,
@ -184,7 +198,7 @@ build's test and coverage markers only after unit/integration tests, Rustdoc tes
The release smoke test remains a nonfatal diagnostic. The release smoke test remains a nonfatal diagnostic.
The collector removes any stale summary before running Cargo and displays only The collector removes any stale summary before running Cargo and displays only
`Final line coverage: 90.87%` on success. Compiler and test output is saved to `Final line coverage: 91.49%` on success. Compiler and test output is saved to
ignored `coverage/coverage.log` in the workspace; failures print a short error ignored `coverage/coverage.log` in the workspace; failures print a short error
pointing to that log and preserve Cargo's exit status. Missing or invalid pointing to that log and preserve Cargo's exit status. Missing or invalid
summaries fail explicitly. No per-file coverage listing is printed, and failed summaries fail explicitly. No per-file coverage listing is printed, and failed
@ -197,14 +211,24 @@ Dependency sources under `/root/.cargo/registry/src/` escaped the pinned tool's
default Cargo-home-based filter. The log does not establish why that default default Cargo-home-based filter. The log does not establish why that default
filter missed these paths. The alias explicitly filters filter missed these paths. The alias explicitly filters
`/registry/src/` paths so dependency caches are excluded regardless of their `/registry/src/` paths so dependency caches are excluded regardless of their
home directory. All tiny-wb production sources and the **85%** floor remain home directory. At that time, all tiny-wb production sources and the **85%** floor
unchanged. This corrects report scope, not test coverage. The subsequent supplied remained unchanged. This corrected report scope, not test coverage. The subsequent supplied
FreeBSD Jenkins build #7 confirmed `Final line coverage: 90.87%` and passed the FreeBSD Jenkins build #7 confirmed `Final line coverage: 90.87%` and passed the
coverage stage. That build then stopped at Clippy's `chunks_exact_to_as_chunks` coverage stage. That build then stopped at Clippy's `chunks_exact_to_as_chunks`
lint; the decoder now iterates fixed-size records with `as_chunks::<3>()`, lint; the decoder now iterates fixed-size records with `as_chunks::<3>()`,
compatible with the declared Rust 1.88 MSRV. Its exact frame-length validation compatible with the then-declared Rust 1.88 MSRV. Its exact frame-length validation
still rejects incomplete records before iteration. still rejects incomplete records before iteration.
FreeBSD Jenkins build #29 used Rust 1.100/LLVM 23 but downgraded the worker's
0.9.1 installation to the obsolete 0.6.16 pin. Although every test passed, that
tool reported 29.01%. The retained log does not include per-file totals, so it
cannot establish the exact files added to the report. Upstream
[0.9.0](https://github.com/taiki-e/cargo-llvm-cov/releases/tag/v0.9.0) fixed
build-script files appearing under Cargo's newer build-directory layout, and
the same CI environment and flags were reproduced locally with 0.9.1 at 91.49%.
This is a tooling correction, not an exclusion of production code or a
reduction of the coverage floor.
At checkout, CI recreates ignored `coverage/` to remove stale workspace state. At checkout, CI recreates ignored `coverage/` to remove stale workspace state.
In `post { cleanup { ... } }`, it uses only current-build markers to choose test In `post { cleanup { ... } }`, it uses only current-build markers to choose test
status and retain measured coverage, falling back to `failing` and neutral `-%` status and retain measured coverage, falling back to `failing` and neutral `-%`

View File

@ -15,9 +15,11 @@ cargo test --locked --doc
| Configuration | Embedded defaults, legacy flat keys, partial nested overrides, unknown/malformed values, numeric and path bounds, round trips, and failed replacement preservation. | | Configuration | Embedded defaults, legacy flat keys, partial nested overrides, unknown/malformed values, numeric and path bounds, round trips, and failed replacement preservation. |
| Protocol | Basic mode boundaries, point/repeat validation, truncated/extra records, alignment, closing brace, binary delimiter bytes, little-endian levels, Basic/Ultra raw offsets, both frequency-axis conventions, and firmware integer/single-precision frequency rounding. | | Protocol | Basic mode boundaries, point/repeat validation, truncated/extra records, alignment, closing brace, binary delimiter bytes, little-endian levels, Basic/Ultra raw offsets, both frequency-axis conventions, and firmware integer/single-precision frequency rounding. |
| Transport | One-byte/fragmented reads, multiple responses in one read, retained bytes after prompts, partial writes, invalid command lines, EOF, timeout, response size limits and raw-body framing. | | Transport | One-byte/fragmented reads, multiple responses in one read, retained bytes after prompts, partial writes, invalid command lines, EOF, timeout, response size limits and raw-body framing. |
| Acquisition | Exact command ordering, optional legacy pre-scan, progress completion, successful decoding, resume after malformed frames, and preservation of acquisition plus recovery errors. | | Acquisition | Exact command ordering, one retry after an unusable identity reply, repeated complete live snapshots, optional legacy pre-scan, progress completion, successful decoding, resume after malformed frames, and preservation of acquisition plus recovery errors. |
| UI/startup | Missing/stale ports, numeric overflow and clamping, configured baud rates, navigation, one-time result transfer, every screen on small/headless terminals, and invalid config before terminal startup. | | Connection worker | Healthy single/live scans open once; empty/unknown identity closes the first port and drops buffered bytes before reopening; fresh-session acquisition succeeds; repeated identity failure stops after one reconnect; conflicting identities, transport/configuration/frame errors and open failures are not replayed. |
| Export | Header/units, deterministic CSV values, propagated write failures and collision-safe output files. | | Live processing | Four/sixteen-sweep rolling windows, bounded history, min/max hold, one-dB decay, incompatible axes, non-finite input and mode-key mapping. |
| UI/startup | `--live` parsing, missing/stale ports, numeric overflow and clamping, typed frequency/point commit/cancel/bounds, configured baud rates, completed/live sample-resolution zoom, adaptive axis precision, pan/reset and clamping, viewport-aware peak selection and overlay, new-scan navigation, view-only CSV behavior, direct CSV startup failures, one-time result transfer, every screen on small/headless terminals, and invalid config before terminal startup. |
| Export | Header/units, header and headerless parsing, malformed/unordered input, deterministic CSV values, propagated write failures and collision-safe output files. |
`Shell<T>` accepts `T: Read + Write`. To add a regression, provide a transcript `Shell<T>` accepts `T: Read + Write`. To add a regression, provide a transcript
reader and capture its writes; vary read chunk size so a token may cross any reader and capture its writes; vary read chunk size so a token may cross any

View File

@ -14,8 +14,11 @@ can represent it in the UI.
| tinySA Basic crossing from 240–<350 MHz into 350–960 MHz | Implemented as high input | The whole scan is forced onto the high path; the low path is not stitched to it. | | tinySA Basic crossing from 240–<350 MHz into 350–960 MHz | Implemented as high input | The whole scan is forced onto the high path; the low path is not stitched to it. |
| Basic span starting below 240 MHz and ending at/above 350 MHz | Rejected | One physical path cannot cover it under the client's policy. Split it into scans. | | Basic span starting below 240 MHz and ending at/above 350 MHz | Rejected | One physical path cannot cover it under the client's policy. Split it into scans. |
| tinySA Ultra/Ultra+ 0.1–800 MHz | Implemented; awaiting hardware qualification | Family detection, `mode low input`, automatic `zero 174` and readback verification. | | tinySA Ultra/Ultra+ 0.1–800 MHz | Implemented; awaiting hardware qualification | Family detection, `mode low input`, automatic `zero 174` and readback verification. |
| Ultra above 800 MHz | Rejected | Revision-specific extended/normal ceilings and unlock state are not negotiated. | | Ultra+ ZS406 0.1–900 MHz | Hardware communications validated | Explicit ZS406/V0.4.6 identity permits the full normal-mode range; RF accuracy is not qualified. |
| Generator control, live streaming, capture, calibration, firmware update | Out of scope | No corresponding application workflow exists. | | Ultra+ ZS406 above 900 MHz through 5.4 GHz | Opt-in; hardware communications validated | Requires `scan.enable_ultra_mode = true`, sends `ultra on`, and verifies sweep readback. Expect slower scans, aliases/spurs and RF-port LO leakage. |
| ZS407 extended mode or any harmonic mode | Rejected | Their different ceilings and measurement behavior are not implemented. |
| Repeated-snapshot live display | Implemented; awaiting hardware qualification | `--live` retains a bounded 16-sweep history and one point buffer per derived hold/decay trace. It does not use native continuous framing. |
| Generator control, display capture, calibration, firmware update | Out of scope | No corresponding application workflow exists. |
At the exact 350 MHz boundary, the implementation's matching rules matter: At the exact 350 MHz boundary, the implementation's matching rules matter:
low accepts frequencies strictly below 350 MHz, while high accepts 350 MHz low accepts frequencies strictly below 350 MHz, while high accepts 350 MHz
@ -45,10 +48,30 @@ cargo build --release
./target/release/tiny-wb ./target/release/tiny-wb
``` ```
The program does not currently expose meaningful command-line options; it With no arguments the program starts the acquisition workflow. To inspect a
starts the interactive terminal immediately. Run it from the working directory for your settings and output, or set previous export without enumerating a serial device or starting acquisition,
open its renderer directly:
```console
./target/release/tiny-wb --view scan.csv
# A positional path is equivalent: ./target/release/tiny-wb scan.csv
```
Run it from the working directory for your settings and output, or set
`TINY_WB_CONFIG` to another configuration path. See [configuration](configuration.md). `TINY_WB_CONFIG` to another configuration path. See [configuration](configuration.md).
For live display, launch:
```console
./target/release/tiny-wb --live
```
Select the connection and scan parameters normally. The configured Points value
is the fixed size of every live sweep and visible/exported trace. tiny-wb opens
one connection, configures it once, and requests repeated complete `scanraw`
snapshots. This deliberately avoids firmware continuous framing until abort and
stream-resynchronization behavior is verified on supported hardware.
### Serial permissions ### Serial permissions
On Linux, identify the device after plugging it in: On Linux, identify the device after plugging it in:
@ -86,13 +109,40 @@ configurable; Basic frequency limits remain fixed protocol rules.
| Field | Unit | Default | Step | Bounds | | Field | Unit | Default | Step | Bounds |
| --- | --- | ---: | ---: | ---: | | --- | --- | ---: | ---: | ---: |
| Start frequency | MHz | 240 | 10 | 0–960 | | Start frequency | MHz | 240 | 10 | 0–5,400 (model checked after identity) |
| Stop frequency | MHz | 800 | 10 | 10–960 (Ultra acquisition capped at 800) | | Stop frequency | MHz | 800 | 10 | 10–5,400 (model checked after identity) |
| Points | samples | 10,001 | 100 | 101–1,000,001 | | Points | samples | 10,001 | 100 | 101–1,000,001 |
| Repeat | measurements/point | 1 | 1 | 1–1,000 | | Repeat | measurements/point | 1 | 1 | 1–1,000 |
Left/right or `h`/`l` changes the selected field. Up/down or `k`/`j` changes Left/right or `h`/`l` changes the selected field. Up/down or `k`/`j` changes
the selection/value. Enter advances to the next screen. `q` or Escape exits. the selection/value. On either frequency field or the Points field, typing a
digit opens an inline editor: digits append, Backspace removes a digit, Enter
applies a value within the displayed bounds, and Escape cancels the edit.
Frequencies are entered in MHz; points are entered as a sample count. Applying
a typed value does not advance, so press Enter again to start the scan. Outside
the editor, Enter advances to the next screen and `q` or Escape exits.
Instrument identification sends the read-only `version` and `info` queries. If
the first complete pair is empty or cannot identify a supported family, tiny-wb
repeats that pair once on the same connection. If both exchanges are empty or
unrecognized, the terminal application's single-scan and live workers close the
connection, discard their buffered replies, reopen once, and repeat identification
automatically. The UI briefly reports `Reconnecting after failed identification`.
A successful retry proceeds with the original settings; a second failed connection
reports its error. This recovery occurs before scan settings are changed or CSV
output is created.
Conflicting model identities, connection-opening failures, transport timeouts,
incomplete prompts, and failures during configuration/acquisition do not trigger
a reconnect. This avoids replaying a scan after a possible device mutation.
Library callers of `acquire`/`acquire_live` retain ownership of their connection
and only get the existing same-connection identity retry.
The reconnect addresses a user-reported Linux first-open failure where a manual
retry works. Stale serial input is a possible cause, not a verified diagnosis;
there is no new operating-system buffer purge or firmware-specific workaround.
Regression transcripts cover this recovery, but the intermittent first-open
hardware failure has not been reproduced locally.
Large point and repeat values can produce extremely long scans. Total time also Large point and repeat values can produce extremely long scans. Total time also
depends on RBW and instrument mode; the progress bar is based mainly on bytes depends on RBW and instrument mode; the progress bar is based mainly on bytes
@ -106,6 +156,46 @@ scatter trace. Its Y axis defaults to −128–0 dBm and uses the configured `ui
and `ui.chart_max_dbm` bounds. Values outside those bounds are clipped visually and `ui.chart_max_dbm` bounds. Values outside those bounds are clipped visually
even though CSV data may contain them. even though CSV data may contain them.
The frequency axis is labeled in MHz. In completed plots and live mode, `+` or
`=` zooms in, `-` zooms out, Left/Right or `h`/`l` pans by a quarter of the
visible span, and `0` or Home restores the full range. Zoom and pan stay within
the frequencies present in the plot. Maximum zoom follows the finest positive
sample spacing in the loaded data, and frequency labels add decimal places as
the visible range narrows. `m` toggles a top-right box containing the level and
frequency of the strongest sample in the visible range.
After an acquired scan, `r` reconnects and repeats the exact request and settings
without reopening the parameter screen; each successful repeat creates a new
collision-safe CSV. `n` returns to the scan screen with the previous parameters
prefilled so they can be edited before starting another scan. These restart keys
are not available when viewing a CSV directly. Plot bindings are configurable
under `[ui.bindings]`; on acquired results, `r` and `n` take precedence over any
matching plot binding. `q`, Escape, or Enter exits the renderer.
### Live display
Live mode updates the plot only after a complete, validated sweep. Its host-side
calculation keys are:
| Key | Visible buffer |
| --- | --- |
| `1` | Rolling arithmetic average of up to 4 sweeps |
| `2` | Rolling arithmetic average of up to 16 sweeps |
| `3` | Maximum held at each frequency since live capture began |
| `4` | Maximum with a 1 dB fall per completed sweep, limited by the new value |
| `5` | Minimum held at each frequency since live capture began |
| `6` | Minimum with a 1 dB rise per completed sweep, limited by the new value |
The history is bounded to 16 complete sweeps regardless of run duration. Hold
and decay calculations retain one value per configured point. `s` writes the
currently selected buffer to a new collision-safe CSV while capture continues.
`q`, Escape, or Enter requests a stop; the current sweep is allowed to finish,
the instrument receives `resume`, the selected buffer is saved, and the program
exits. A transport failure is reported rather than exporting a partial frame.
Subtraction/reference-buffer processing is not implemented yet. The live modes
are host calculations over repeated snapshots, not claims about the firmware's
front-panel detector or trace modes, and require physical-device qualification.
## Files ## Files
### `config.toml` ### `config.toml`
@ -142,6 +232,9 @@ resume response. Failed writes are reported and incomplete files are removed
when possible. Enable `output.include_header` for named columns. Choose the when possible. Enable `output.include_header` for named columns. Choose the
frequency-label convention explicitly after reviewing the frequency-label convention explicitly after reviewing the
[frequency assignment notes](usb-protocol.md#frequency-assignment). [frequency assignment notes](usb-protocol.md#frequency-assignment).
The direct renderer accepts this header or headerless files, ignores blank
lines, and reports malformed, non-finite, empty, or decreasing-frequency data
with its CSV line number before initializing logging or taking over the terminal.
### Logs ### Logs
@ -180,6 +273,13 @@ power-cycle/reload a preset after making the RF setup safe.
- Unplug/reconnect if the device was just in DFU mode; DFU and CDC serial are - Unplug/reconnect if the device was just in DFU mode; DFU and CDC serial are
different USB personalities. different USB personalities.
### Unsupported device identity on first connection
The application automatically reopens once after repeated empty or unknown
identity replies; see [identification recovery](#scan-screen). If it still
fails, confirm the port and instrument model. Do not assume that every unknown
device is a tinySA. Include the final error and firmware details in a bug report.
### “No version found” or a timeout ### “No version found” or a timeout
- Verify the selected port is the tinySA, not another CDC device. - Verify the selected port is the tinySA, not another CDC device.
@ -243,7 +343,7 @@ software bug; substitute a low-level known source or recorded serial fixture.
## Remaining engineering work ## Remaining engineering work
Revision-specific detection, Ultra ranges above 800 MHz, overall ZS407 extended detection, harmonic ranges above 5.4 GHz, overall
transaction deadlines, cancellation/abort, full instrument-state restoration, transaction deadlines, cancellation/abort, full instrument-state restoration,
and richer output metadata remain open. Buffered framing, strict record-count and richer output metadata remain open. Buffered framing, strict record-count
validation, reusable core interfaces and hardware-free regression tests are validation, reusable core interfaces and hardware-free regression tests are

View File

@ -304,8 +304,10 @@ version installed on the instrument.
## How this maps to tiny-wb ## How this maps to tiny-wb
tiny-wb detects Basic/Ultra families and applies model-specific input commands tiny-wb detects Basic/Ultra families and applies model-specific input commands
and native encoding offsets. Ultra support currently covers 0.1–800 MHz; and native encoding offsets. Generic Ultra support covers 0.1–800 MHz; a
extended ranges and hardware qualification remain pending. See detected ZS406 covers normal mode through 900 MHz and explicit opt-in Ultra mode
through 5.4 GHz. Harmonic reception, ZS407 extended mode and other extended
ranges remain unsupported; RF accuracy qualification remains pending. See
[support scope](ultra-support.md) and the [compatibility matrix](tiny-wb-operations.md#compatibility-matrix). [support scope](ultra-support.md) and the [compatibility matrix](tiny-wb-operations.md#compatibility-matrix).
For the wire format and exact command behavior, continue with For the wire format and exact command behavior, continue with

View File

@ -6,20 +6,25 @@ The acquisition path reads `version`, `info`, and `help` before changing scan
settings. Recognized Basic (`tinySA_v…`) and Ultra-family (`tinySA4_v…`) identities settings. Recognized Basic (`tinySA_v…`) and Ultra-family (`tinySA4_v…`) identities
select different plans. Unknown or conflicting identities fail. Explicit select different plans. Unknown or conflicting identities fail. Explicit
`scan.device_model = "basic"` or `"ultra"` requires a matching detected family; `scan.device_model = "basic"` or `"ultra"` requires a matching detected family;
the default is `"auto"`. Family detection does not identify a hardware revision the default is `"auto"`. Explicit identity text also distinguishes ZS405,
or certify that an arbitrary firmware build implements every command correctly. ZS406 and ZS407; an unrecognized revision retains the conservative family
fallback. Detection does not certify that arbitrary firmware implements every
command correctly.
| Family | Implemented acquisition range | Input command | Automatic raw bias | | Family | Implemented acquisition range | Input command | Automatic raw bias |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Basic | Existing low/high policy through 960 MHz | `mode low input` or `mode high input` | 128 dB | | Basic | Existing low/high policy through 960 MHz | `mode low input` or `mode high input` | 128 dB |
| Ultra/Ultra+ | Common normal range 0.1–800 MHz | `mode low input` | 174 dB | | Ultra family without identified revision | Common normal range 0.1–800 MHz | `mode low input` | 174 dB |
| Ultra+ ZS406 | Normal 0.1–900 MHz; opt-in Ultra through 5.4 GHz | `mode low input`; `ultra on` above 900 MHz | 174 dB |
The [official comparison](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Comparison) The [official comparison](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Comparison)
lists 800 MHz normal range for ZS405 and 900 MHz for Ultra+ revisions. This lists 800 MHz normal range for ZS405 and 900 MHz for Ultra+ revisions. ZS406 is
initial implementation deliberately uses their shared 800 MHz ceiling. recognized only from explicit `ZS406` or `HW Version:V0.4.6` evidence. Above
Extended/Ultra/harmonic ranges, revision detection, LNA control and mode-state 900 MHz, `scan.enable_ultra_mode = true` is required; acquisition sends
restoration are not implemented. Existing instrument processing settings and `ultra on` and verifies that `sweep` reads back the requested boundaries. The
Ultra-enable state are retained; no unlock or persistent-save command is sent. client stops at 5.4 GHz before harmonic mixing. It does not send `saveconfig`,
but firmware may retain Ultra mode as device state. ZS407 extended mode,
harmonic mode, LNA control and complete mode-state restoration are not implemented.
The [official Ultra console snapshot](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.ConsoleCommands) The [official Ultra console snapshot](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.ConsoleCommands)
documents the family version prefix and zero readback. The reviewed documents the family version prefix and zero readback. The reviewed
[mode handler](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c) [mode handler](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c)
@ -41,22 +46,26 @@ existing `zero_offset` value. Previously saved offsets remain parseable but
are ignored while automatic selection is enabled. No configuration is rewritten are ignored while automatic selection is enabled. No configuration is rewritten
until the normal save workflow runs. until the normal save workflow runs.
The terminal uses integer MHz inputs and a shared 960 MHz entry ceiling. The terminal uses integer MHz inputs and a shared 5,400 MHz entry ceiling.
Model-specific validation runs after identification in the acquisition worker; Model-specific validation runs after identification in the acquisition worker;
therefore out-of-profile input is rejected before mutation, but after the UI therefore out-of-profile input is rejected before mutation, but after the UI
saves the selection. Use the library for sub-MHz settings. Dynamic UI bounds saves the selection. Use the library for sub-MHz settings. Dynamic UI bounds
and detection before the selection screen remain future work. and detection before the selection screen remain future work. Existing partial
configuration files adopt `scan.enable_ultra_mode = false`, so this change does
not opt them into persistent instrument-state changes.
## Verification and qualification ## Verification and qualification
Regression tests cover model detection, conflicts, range/path selection, Regression tests cover model detection, conflicts, range/path selection,
automatic native offsets, command inventory, readback failures, partial I/O and automatic native offsets, command inventory, readback failures, partial I/O and
resume after scan failure. Run the [local gates](security-and-ci.md#local-verification) resume after scan failure. Run the [local gates](security-and-ci.md#local-verification)
and `cargo coverage`. The hardware validator now requires its selected family and `cargo coverage`. The hardware validator requires its selected family to
to match detection before changing settings and exercises Ultra below 800 MHz. match detection before changing settings. Its `zs406` profile separately checks
0.1–900 MHz normal reception and 900 MHz–5.4 GHz opt-in Ultra reception.
This is initial software support, not a claim of hardware-qualified first-tier The ZS406 normal and Ultra command paths were physically validated on 2026-10-07
support. Existing Basic evidence predates the new `help`/`zero` readback flow; with firmware `tinySA4_v1.4-197-gaa78ccc`; see
rerun [hardware validation](hardware-validation.md) on both instruments. Ultra [hardware validation](hardware-validation.md#recorded-zs406-evidence). This is
RF level/frequency accuracy, Windows/macOS, Jenkins and publication have not not RF accuracy qualification. Generic Ultra-family variants still need their
been verified by these synthetic tests. own hardware runs, and Ultra RF level/frequency accuracy, Windows/macOS, Jenkins
and publication have not been verified for this change.

View File

@ -82,9 +82,11 @@ Constraints visible in upstream firmware:
- waterfall is disabled before acquisition in current firmware; - waterfall is disabled before acquisition in current firmware;
- a continuous request must be explicitly aborted and needs a streaming parser. - a continuous request must be explicitly aborted and needs a streaming parser.
tiny-wb omits OPTIONS, so it requests one buffered acquisition. The firmware tiny-wb omits OPTIONS, so ordinary acquisition requests one buffered sweep and
buffers in small blocks internally; “buffered” does not mean the entire sweep `--live` repeats that complete request over one configured connection. The
is delivered in a single USB transfer. firmware buffers in small blocks internally; “buffered” does not mean the entire
sweep is delivered in a single USB transfer. Native option-2 continuous framing
remains unsupported until explicit abort and resynchronization are verified.
## Binary response framing ## Binary response framing
@ -257,7 +259,9 @@ or a later command fails. A failed recovery is included with the original error.
There is no cancellation protocol or full state restoration, and process exit There is no cancellation protocol or full state restoration, and process exit
can prevent recovery. The offset requires readback; other settings are checked can prevent recovery. The offset requires readback; other settings are checked
for recognizable command errors. Optional diagnostic queries require `help` for recognizable command errors. Optional diagnostic queries require `help`
advertisement. See [model-specific planning](ultra-support.md). advertisement. ZS406 Ultra acquisition additionally requires explicit opt-in,
an advertised `ultra` command and exact requested `sweep` boundary readback.
See [model-specific planning](ultra-support.md).
The `scan` outmask value `101` remains outside the documented three-bit mask and The `scan` outmask value `101` remains outside the documented three-bit mask and
its returned data is discarded. The legacy preparation is enabled by default its returned data is discarded. The legacy preparation is enabled by default

View File

@ -23,6 +23,7 @@ use tiny_wb::{
enum Model { enum Model {
Basic, Basic,
Ultra, Ultra,
Zs406,
} }
impl Model { impl Model {
@ -30,6 +31,7 @@ impl Model {
match value.to_ascii_lowercase().as_str() { match value.to_ascii_lowercase().as_str() {
"basic" => Some(Self::Basic), "basic" => Some(Self::Basic),
"ultra" => Some(Self::Ultra), "ultra" => Some(Self::Ultra),
"zs406" => Some(Self::Zs406),
_ => None, _ => None,
} }
} }
@ -38,17 +40,18 @@ impl Model {
match self { match self {
Self::Basic => "Basic", Self::Basic => "Basic",
Self::Ultra => "Ultra", Self::Ultra => "Ultra",
Self::Zs406 => "ZS406",
} }
} }
fn raw_level_offset_db(self) -> u16 { fn raw_level_offset_db(self) -> u16 {
match self { match self {
Self::Basic => BASIC_RAW_LEVEL_OFFSET_DB, Self::Basic => BASIC_RAW_LEVEL_OFFSET_DB,
Self::Ultra => ULTRA_RAW_LEVEL_OFFSET_DB, Self::Ultra | Self::Zs406 => ULTRA_RAW_LEVEL_OFFSET_DB,
} }
} }
fn scans(self) -> [(&'static str, ScanRequest, bool); 2] { fn scans(self) -> [(&'static str, ScanRequest, bool, bool); 2] {
let low = ScanRequest { let low = ScanRequest {
start_hz: 240_000_000, start_hz: 240_000_000,
stop_hz: 300_000_000, stop_hz: 300_000_000,
@ -61,11 +64,35 @@ impl Model {
stop_hz: 400_000_000, stop_hz: 400_000_000,
..low ..low
}, },
// Ultra support is experimental. Stay on the shared low-input // Generic Ultra validation stays on the shared low-input path.
// command path until model-aware extended ranges are implemented.
Self::Ultra => low, Self::Ultra => low,
Self::Zs406 => ScanRequest {
start_hz: 900_000_000,
stop_hz: 5_400_000_000,
points: 101,
repeat: 1,
},
}; };
[("legacy", low, true), ("direct", second, false)] match self {
Self::Zs406 => [
(
"normal",
ScanRequest {
start_hz: 100_000,
stop_hz: 900_000_000,
points: 101,
repeat: 1,
},
false,
false,
),
("ultra", second, false, true),
],
Self::Basic | Self::Ultra => [
("legacy", low, true, false),
("direct", second, false, false),
],
}
} }
} }
@ -76,7 +103,7 @@ struct Arguments {
} }
fn usage() -> &'static str { fn usage() -> &'static str {
"usage: validate-hardware <basic|ultra> [--port DEVICE] [--output DIRECTORY]" "usage: validate-hardware <basic|ultra|zs406> [--port DEVICE] [--output DIRECTORY]"
} }
fn parse_arguments(arguments: impl IntoIterator<Item = String>) -> Result<Arguments, String> { fn parse_arguments(arguments: impl IntoIterator<Item = String>) -> Result<Arguments, String> {
@ -199,7 +226,7 @@ fn run() -> Result<(), Box<dyn Error>> {
let session = arguments.output.join(format!( let session = arguments.output.join(format!(
"{}-{}", "{}-{}",
arguments.model.name().to_ascii_lowercase(), arguments.model.name().to_ascii_lowercase(),
chrono::Local::now().format("%Y%m%d-%H%M%S-%6f") jiff::ZonedDateTime::now().strftime("%Y%m%d-%H%M%S-%6f")
)); ));
fs::create_dir_all(&session)?; fs::create_dir_all(&session)?;
@ -209,7 +236,7 @@ fn run() -> Result<(), Box<dyn Error>> {
port port
); );
let mut identity = String::new(); let mut identity = String::new();
for (name, request, legacy_pre_scan) in arguments.model.scans() { for (name, request, legacy_pre_scan, enable_ultra_mode) in arguments.model.scans() {
println!( println!(
"Running {name} scan: {}–{} MHz, {} points...", "Running {name} scan: {}–{} MHz, {} points...",
request.start_hz / 1_000_000, request.start_hz / 1_000_000,
@ -224,8 +251,9 @@ fn run() -> Result<(), Box<dyn Error>> {
config.repeat = request.repeat; config.repeat = request.repeat;
config.scan.device_model = match arguments.model { config.scan.device_model = match arguments.model {
Model::Basic => ModelSelection::Basic, Model::Basic => ModelSelection::Basic,
Model::Ultra => ModelSelection::Ultra, Model::Ultra | Model::Zs406 => ModelSelection::Ultra,
}; };
config.scan.enable_ultra_mode = enable_ultra_mode;
config.scan.auto_zero_offset = true; config.scan.auto_zero_offset = true;
config.scan.zero_offset = arguments.model.raw_level_offset_db(); config.scan.zero_offset = arguments.model.raw_level_offset_db();
config.scan.frequency_axis = FrequencyAxis::Firmware; config.scan.frequency_axis = FrequencyAxis::Firmware;
@ -257,12 +285,13 @@ fn run() -> Result<(), Box<dyn Error>> {
path.display() path.display()
); );
report.push_str(&format!( report.push_str(&format!(
"scan={name},start_hz={},stop_hz={},points={},raw_level_offset_db={},legacy_pre_scan={},csv={}\n", "scan={name},start_hz={},stop_hz={},points={},raw_level_offset_db={},legacy_pre_scan={},enable_ultra_mode={},csv={}\n",
request.start_hz, request.start_hz,
request.stop_hz, request.stop_hz,
request.points, request.points,
config.scan.zero_offset, config.scan.zero_offset,
legacy_pre_scan, legacy_pre_scan,
enable_ultra_mode,
path.display() path.display()
)); ));
} }
@ -294,6 +323,8 @@ fn run() -> Result<(), Box<dyn Error>> {
); );
if arguments.model == Model::Ultra { if arguments.model == Model::Ultra {
println!("Ultra result covers only the shared 240–300 MHz low-input path; extended ranges remain unsupported."); println!("Ultra result covers only the shared 240–300 MHz low-input path; extended ranges remain unsupported.");
} else if arguments.model == Model::Zs406 {
println!("ZS406 result covers normal reception through 900 MHz and opt-in non-harmonic Ultra reception through 5.4 GHz; it does not establish RF accuracy.");
} }
Ok(()) Ok(())
} }
@ -324,12 +355,18 @@ mod tests {
"mode high input" "mode high input"
); );
let ultra = Model::Ultra.scans(); let ultra = Model::Ultra.scans();
assert!(ultra.iter().all(|(_, request, _)| { assert!(ultra.iter().all(|(_, request, _, enable_ultra_mode)| {
request.stop_hz < 350_000_000 request.stop_hz < 350_000_000
&& !enable_ultra_mode
&& DeviceModel::Ultra && DeviceModel::Ultra
.plan(request) .plan(request)
.is_ok_and(|plan| plan.input_command == "mode low input") .is_ok_and(|plan| plan.input_command == "mode low input")
})); }));
let zs406 = Model::Zs406.scans();
assert_eq!(zs406[0].1.stop_hz, 900_000_000);
assert!(!zs406[0].3);
assert_eq!(zs406[1].1.stop_hz, 5_400_000_000);
assert!(zs406[1].3);
assert!(ultra[0].2); assert!(ultra[0].2);
assert!(!ultra[1].2); assert!(!ultra[1].2);
} }

View File

@ -7,10 +7,21 @@ tag-prefix = ""
# Desktop targets. Linux uses glibc because serialport links system libudev. # Desktop targets. Linux uses glibc because serialport links system libudev.
# release/Cross.toml injects target libudev/pkg-config; the base images provide # release/Cross.toml injects target libudev/pkg-config; the base images provide
# the remaining target toolchains, including the Windows windres executable. # the remaining target toolchains, including the Windows windres executable.
targets = ["x86_64-unknown-linux-gnu", "x86_64-pc-windows-gnu"] targets = [
"x86_64-unknown-linux-gnu",
"x86_64-pc-windows-gnu",
"aarch64-apple-darwin",
"x86_64-apple-darwin",
]
profile = "release" profile = "release"
locked = true locked = true
# Apple targets use the publisher's direct cargo-zigbuild backend, not Cross.
[build.apple]
image = "ghcr.io/rust-cross/cargo-zigbuild@sha256:9b4f6b3eb9e8f9fefb3960fe288ddba576627d66d9eff851ce7f62d2455564a5"
deployment-target = "13.0"
sdk-root = "/opt/MacOSX11.3.sdk"
[gitea] [gitea]
token-env = "GITEA_TOKEN" token-env = "GITEA_TOKEN"

View File

@ -9,7 +9,7 @@ trap 'exit 1' HUP INT TERM
rm -f "$summary" rm -f "$summary"
coverage_status=0 coverage_status=0
cargo coverage >"$log" 2>&1 || coverage_status=$? cargo coverage >"$log" 2>&1 || coverage_status=$?
# cargo-llvm-cov 0.6.16 can fail the floor silently after writing its report. # Preserve the explicit status check even when Cargo writes a valid report.
# Print the measurement before cleanup, but never mask a failed Cargo run. # Print the measurement before cleanup, but never mask a failed Cargo run.
if [ ! -s "$summary" ]; then if [ ! -s "$summary" ]; then
echo "ERROR: cargo coverage produced no summary (exit $coverage_status); see coverage/coverage.log." >&2 echo "ERROR: cargo coverage produced no summary (exit $coverage_status); see coverage/coverage.log." >&2

View File

@ -172,7 +172,7 @@ exit "$FAKE_COVERAGE_STATUS"
''') ''')
cargo.chmod(0o755) cargo.chmod(0o755)
os.environ['PATH'] = str(tools) + ':' + old_path os.environ['PATH'] = str(tools) + ':' + old_path
for percentage, status in ((90.87, 0), (85, 0), (84.99, 1), (90.87, 7)): for percentage, status in ((91.49, 0), (85, 0), (84.99, 1), (91.49, 7)):
os.environ['FAKE_COVERAGE_REPORT'] = json.dumps({'data': [{ os.environ['FAKE_COVERAGE_REPORT'] = json.dumps({'data': [{
'totals': {'lines': {'percent': percentage}}, 'totals': {'lines': {'percent': percentage}},
'files': [{'filename': 'src/example.rs', 'summary': { 'files': [{'filename': 'src/example.rs', 'summary': {
@ -233,6 +233,7 @@ readme = (REPO/'README.md').read_text()
for name in ('version', 'test', 'coverage'): for name in ('version', 'test', 'coverage'):
assert readme.count(f'https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/{name}.svg') == 1 assert readme.count(f'https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/{name}.svg') == 1
pipeline = (REPO/'Jenkinsfile').read_text() pipeline = (REPO/'Jenkinsfile').read_text()
assert "CARGO_LLVM_COV_VERSION = '0.9.1'" in pipeline
assert "artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg'" in pipeline assert "artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg'" in pipeline
assert 'fingerprint: true, allowEmptyArchive: false' in pipeline assert 'fingerprint: true, allowEmptyArchive: false' in pipeline
print('Badge rendering, XML, validation, coverage diagnostics, publication, README and archive checks passed.') print('Badge rendering, XML, validation, coverage diagnostics, publication, README and archive checks passed.')

View File

@ -2,9 +2,9 @@
set -eu set -eu
case "${1:-}" in case "${1:-}" in
basic|ultra) ;; basic|ultra|zs406) ;;
*) *)
echo "usage: $0 <basic|ultra> [--port DEVICE] [--output DIRECTORY]" >&2 echo "usage: $0 <basic|ultra|zs406> [--port DEVICE] [--output DIRECTORY]" >&2
exit 2 exit 2
;; ;;
esac esac

View File

@ -168,12 +168,31 @@ sys.exit(int(os.environ.get("PUBLISHER_EXIT", "0")))
self.assertEqual(config['release']['tag-prefix'], '') self.assertEqual(config['release']['tag-prefix'], '')
self.assertEqual(config['build']['profile'], 'release') self.assertEqual(config['build']['profile'], 'release')
self.assertTrue(config['build']['locked']) self.assertTrue(config['build']['locked'])
self.assertEqual(config['build']['targets'], ['x86_64-unknown-linux-gnu', 'x86_64-pc-windows-gnu']) self.assertEqual(config['build']['targets'], [
'x86_64-unknown-linux-gnu', 'x86_64-pc-windows-gnu',
'aarch64-apple-darwin', 'x86_64-apple-darwin'])
self.assertEqual(config['build']['apple'], {
'image': 'ghcr.io/rust-cross/cargo-zigbuild@sha256:'
'9b4f6b3eb9e8f9fefb3960fe288ddba576627d66d9eff851ce7f62d2455564a5',
'deployment-target': '13.0',
'sdk-root': '/opt/MacOSX11.3.sdk'})
self.assertEqual(manifest['metadata']['binstall'], { self.assertEqual(manifest['metadata']['binstall'], {
'pkg-url': '{ repo }/releases/download/{ version }/{ name }-{ target }-v{ version }.tgz', 'pkg-url': '{ repo }/releases/download/{ version }/{ name }-{ target }-v{ version }.tgz',
'pkg-fmt': 'tgz', 'pkg-fmt': 'tgz',
'bin-dir': '{ name }-{ target }-v{ version }/{ bin }{ binary-ext }'}) 'bin-dir': '{ name }-{ target }-v{ version }/{ bin }{ binary-ext }'})
def test_apple_target_overrides_are_forwarded_without_a_token(self):
self.env['GITEA_TOKEN'] = 'inherited-token-must-not-reach-publisher'
targets = ['--target', 'aarch64-apple-darwin',
'--target', 'x86_64-apple-darwin']
self.run_wrapper(['--compile-only', *targets])
record = json.loads(self.capture.read_text())
self.assertEqual(record['args'][6:10], targets)
self.assertIsNone(record['token'])
config = tomllib.loads(record['fallback'])
self.assertEqual(config['build']['apple']['deployment-target'], '13.0')
self.assertEqual(Path(record['cross_config']), self.project / 'release' / 'Cross.toml')
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -73,6 +73,16 @@ pub enum AcquisitionError {
/// Offset reported by the device, in dB. /// Offset reported by the device, in dB.
actual: u16, actual: u16,
}, },
/// Extended-mode sweep readback did not confirm the requested boundaries.
#[error("ZS406 did not confirm the requested Ultra sweep {requested_start}–{requested_stop} Hz; readback was {response:?}")]
SweepReadbackMismatch {
/// Requested lower boundary, in Hz.
requested_start: u64,
/// Requested upper boundary, in Hz.
requested_stop: u64,
/// Bounded prompt-stripped firmware response.
response: String,
},
/// Both acquisition and the subsequent resume attempt failed. /// Both acquisition and the subsequent resume attempt failed.
#[error("{primary}; additionally, resume failed: {recovery}")] #[error("{primary}; additionally, resume failed: {recovery}")]
Recovery { Recovery {
@ -89,7 +99,8 @@ pub enum AcquisitionError {
/// Settings should come from a validated [`crate::config::Config`]. The request /// Settings should come from a validated [`crate::config::Config`]. The request
/// is structurally validated before I/O and checked against the detected model /// is structurally validated before I/O and checked against the detected model
/// before mutation. Basic supports its existing low/high paths through 960 MHz. /// before mutation. Basic supports its existing low/high paths through 960 MHz.
/// Ultra-family support is restricted to the common normal 0.1–800 MHz range. /// Ultra-family support defaults to the common normal 0.1–800 MHz range. A
/// detected ZS406 supports 900 MHz normally and opt-in Ultra mode to 5.4 GHz.
pub fn acquire<T: Read + Write>( pub fn acquire<T: Read + Write>(
shell: &mut Shell<T>, shell: &mut Shell<T>,
request: &ScanRequest, request: &ScanRequest,
@ -97,18 +108,85 @@ pub fn acquire<T: Read + Write>(
serial: &SerialConfig, serial: &SerialConfig,
mut report: impl FnMut(ScanEvent), mut report: impl FnMut(ScanEvent),
) -> Result<Vec<Sample>, AcquisitionError> { ) -> Result<Vec<Sample>, AcquisitionError> {
let prepared = prepare_acquisition(shell, request, scan, serial, &mut report)?;
// Pause may take effect even when its response times out, so recovery also
// covers failure receiving the pause response itself.
let result = (|| {
configure_paused(shell, request, scan, serial, prepared)?;
report(ScanEvent::Message("Acquiring samples"));
let frame = read_snapshot(shell, request, &mut report)?;
Ok(protocol::decode_frame(
&frame,
request,
prepared.zero_offset,
scan.frequency_axis,
)?)
})();
let samples = resume_after(shell, prepared, result)?;
report(ScanEvent::Message("Acquisition complete"));
report(ScanEvent::Progress(100));
Ok(samples)
}
/// Repeatedly acquire complete bounded snapshots on one configured connection.
///
/// This deliberately does not use firmware continuous framing. Cancellation is
/// checked before each snapshot, so an in-progress sweep completes before the
/// instrument is resumed. `on_sweep` receives only fully decoded frames.
///
/// # Errors
///
/// Returns an error when validation, device identification, configuration,
/// transport, frame decoding, or the final resume command fails. When both
/// acquisition and resume fail, both errors are retained.
pub fn acquire_live<T: Read + Write>(
shell: &mut Shell<T>,
request: &ScanRequest,
scan: &ScanConfig,
serial: &SerialConfig,
mut should_stop: impl FnMut() -> bool,
mut on_sweep: impl FnMut(Vec<Sample>),
mut report: impl FnMut(ScanEvent),
) -> Result<u64, AcquisitionError> {
let prepared = prepare_acquisition(shell, request, scan, serial, &mut report)?;
let result = (|| {
configure_paused(shell, request, scan, serial, prepared)?;
report(ScanEvent::Message("Live capture running"));
let mut sweeps = 0_u64;
while !should_stop() {
let frame = read_snapshot(shell, request, &mut report)?;
let samples =
protocol::decode_frame(&frame, request, prepared.zero_offset, scan.frequency_axis)?;
sweeps = sweeps.saturating_add(1);
on_sweep(samples);
}
Ok(sweeps)
})();
resume_after(shell, prepared, result)
}
#[derive(Clone, Copy)]
struct PreparedAcquisition {
delay: Duration,
settle: Duration,
plan: crate::device::AcquisitionPlan,
zero_offset: u16,
}
fn prepare_acquisition<T: Read + Write>(
shell: &mut Shell<T>,
request: &ScanRequest,
scan: &ScanConfig,
serial: &SerialConfig,
report: &mut impl FnMut(ScanEvent),
) -> Result<PreparedAcquisition, AcquisitionError> {
request.validate()?; request.validate()?;
let delay = Duration::from_millis(serial.command_delay_ms); let delay = Duration::from_millis(serial.command_delay_ms);
let settle = Duration::from_millis(serial.settle_delay_ms); let settle = Duration::from_millis(serial.settle_delay_ms);
report(ScanEvent::Message("Identifying instrument")); report(ScanEvent::Message("Identifying instrument"));
report(ScanEvent::Progress(5)); report(ScanEvent::Progress(5));
shell.synchronize()?; shell.synchronize()?;
let version = shell.command("version", delay, settle)?; let identity = identify_with_retry(shell, delay, settle, report)?;
let info = shell.command("info", delay, settle)?;
if version.trim().is_empty() || info.trim().is_empty() {
return Err(AcquisitionError::MissingIdentity);
}
let identity = DeviceIdentity::detect(version, info)?;
let expected = match scan.device_model { let expected = match scan.device_model {
ModelSelection::Auto => None, ModelSelection::Auto => None,
ModelSelection::Basic => Some(DeviceModel::Basic), ModelSelection::Basic => Some(DeviceModel::Basic),
@ -120,12 +198,13 @@ pub fn acquire<T: Read + Write>(
actual: identity.model, actual: identity.model,
}); });
} }
let plan = identity.model.plan(request)?; let plan = identity.plan(request, scan.enable_ultra_mode)?;
let help = shell.command("help", delay, settle)?; let help = shell.command("help", delay, settle)?;
for command in [ for command in [
"repeat", "zero", "pause", "mode", "sweep", "scanraw", "resume", "repeat", "zero", "pause", "mode", "sweep", "scanraw", "resume",
] ]
.into_iter() .into_iter()
.chain(plan.enable_ultra_mode.then_some("ultra"))
.chain(scan.legacy_pre_scan.then_some("scan")) .chain(scan.legacy_pre_scan.then_some("scan"))
{ {
if !advertises_command(&help, command) { if !advertises_command(&help, command) {
@ -135,9 +214,13 @@ pub fn acquire<T: Read + Write>(
}); });
} }
} }
let revision = identity
.ultra_revision
.map(|revision| format!(" {revision}"))
.unwrap_or_default();
report(ScanEvent::InstrumentInfo(format!( report(ScanEvent::InstrumentInfo(format!(
"Detected {} (native raw offset {} dB)\n{}{}", "Detected {}{} (native raw offset {} dB)\n{}{}",
identity.model, plan.native_zero_offset_db, identity.version, identity.info identity.model, revision, plan.native_zero_offset_db, identity.version, identity.info
))); )));
for command in ["leveloffset", "vbat", "usart_cfg", "threads", "marker"] { for command in ["leveloffset", "vbat", "usart_cfg", "threads", "marker"] {
if advertises_command(&help, command) { if advertises_command(&help, command) {
@ -165,47 +248,82 @@ pub fn acquire<T: Read + Write>(
None => { None => {
return Err(AcquisitionError::MissingZeroReadback { return Err(AcquisitionError::MissingZeroReadback {
requested: zero_offset, requested: zero_offset,
}); })
} }
} }
report(ScanEvent::Progress(20)); report(ScanEvent::Progress(20));
// Pause may take effect even when its response times out, so recovery also Ok(PreparedAcquisition {
// covers failure receiving the pause response itself. delay,
let result = (|| { settle,
shell.command_checked("pause", delay, settle)?; plan,
shell.command_checked(plan.input_command, delay, settle)?; zero_offset,
shell.command_checked(&format!("sweep start {}", request.start_hz), delay, settle)?; })
shell.command_checked(&format!("sweep stop {}", request.stop_hz), delay, settle)?; }
shell.command_checked("sweep", delay, settle)?;
if scan.legacy_pre_scan { fn configure_paused<T: Read + Write>(
shell.command_checked( shell: &mut Shell<T>,
&format!("scan {} {} 290 101", request.start_hz, request.stop_hz), request: &ScanRequest,
Duration::from_millis(serial.scan_delay_ms), scan: &ScanConfig,
settle, serial: &SerialConfig,
)?; prepared: PreparedAcquisition,
} ) -> Result<(), AcquisitionError> {
report(ScanEvent::Message("Acquiring samples")); shell.command_checked("pause", prepared.delay, prepared.settle)?;
shell.send(&format!( shell.command_checked(prepared.plan.input_command, prepared.delay, prepared.settle)?;
"scanraw {} {} {}", if prepared.plan.enable_ultra_mode {
request.start_hz, request.stop_hz, request.points shell.command_checked("ultra on", prepared.delay, prepared.settle)?;
))?; }
let frame = shell.read_frame(request, |received, expected| { shell.command_checked(
report(ScanEvent::Progress((20 + received * 75 / expected) as u8)) &format!("sweep start {}", request.start_hz),
})?; prepared.delay,
Ok(protocol::decode_frame( prepared.settle,
&frame, )?;
request, shell.command_checked(
zero_offset, &format!("sweep stop {}", request.stop_hz),
scan.frequency_axis, prepared.delay,
)?) prepared.settle,
})(); )?;
let recovery = shell.command_checked("resume", delay, settle); let sweep_response = shell.command_checked("sweep", prepared.delay, prepared.settle)?;
if prepared.plan.enable_ultra_mode
&& parse_sweep_bounds(&sweep_response) != Some((request.start_hz, request.stop_hz))
{
return Err(AcquisitionError::SweepReadbackMismatch {
requested_start: request.start_hz,
requested_stop: request.stop_hz,
response: sweep_response,
});
}
if scan.legacy_pre_scan {
shell.command_checked(
&format!("scan {} {} 290 101", request.start_hz, request.stop_hz),
Duration::from_millis(serial.scan_delay_ms),
prepared.settle,
)?;
}
Ok(())
}
fn read_snapshot<T: Read + Write>(
shell: &mut Shell<T>,
request: &ScanRequest,
report: &mut impl FnMut(ScanEvent),
) -> Result<Vec<u8>, AcquisitionError> {
shell.send(&format!(
"scanraw {} {} {}",
request.start_hz, request.stop_hz, request.points
))?;
Ok(shell.read_frame(request, |received, expected| {
report(ScanEvent::Progress((20 + received * 75 / expected) as u8))
})?)
}
fn resume_after<T: Read + Write, R>(
shell: &mut Shell<T>,
prepared: PreparedAcquisition,
result: Result<R, AcquisitionError>,
) -> Result<R, AcquisitionError> {
let recovery = shell.command_checked("resume", prepared.delay, prepared.settle);
match (result, recovery) { match (result, recovery) {
(Ok(samples), Ok(_)) => { (Ok(value), Ok(_)) => Ok(value),
report(ScanEvent::Message("Acquisition complete"));
report(ScanEvent::Progress(100));
Ok(samples)
}
(Err(primary), Err(recovery)) => Err(AcquisitionError::Recovery { (Err(primary), Err(recovery)) => Err(AcquisitionError::Recovery {
primary: Box::new(primary), primary: Box::new(primary),
recovery, recovery,
@ -215,6 +333,37 @@ pub fn acquire<T: Read + Write>(
} }
} }
/// Retry the read-only identity exchange once after a complete but unusable reply.
///
/// Transport failures are not retried because a timeout can leave an incomplete
/// prompt in the buffered stream. Replaying commands in that state would risk
/// assigning a late response to the wrong request.
fn identify_with_retry<T: Read + Write>(
shell: &mut Shell<T>,
delay: Duration,
settle: Duration,
report: &mut impl FnMut(ScanEvent),
) -> Result<DeviceIdentity, AcquisitionError> {
for attempt in 0..2 {
let version = shell.command("version", delay, settle)?;
let info = shell.command("info", delay, settle)?;
let identity = if version.trim().is_empty() || info.trim().is_empty() {
Err(AcquisitionError::MissingIdentity)
} else {
DeviceIdentity::detect(version, info).map_err(AcquisitionError::from)
};
match identity {
Ok(identity) => return Ok(identity),
Err(error) if attempt == 0 => {
log::warn!("instrument identification failed; retrying once: {error}");
report(ScanEvent::Message("Retrying instrument identification"));
}
Err(error) => return Err(error),
}
}
unreachable!("the bounded identity loop always returns")
}
fn advertises_command(help: &str, command: &str) -> bool { fn advertises_command(help: &str, command: &str) -> bool {
help.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_')) help.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
.any(|word| word.eq_ignore_ascii_case(command)) .any(|word| word.eq_ignore_ascii_case(command))
@ -229,11 +378,22 @@ fn parse_zero_offset(response: &str) -> Option<u16> {
}) })
} }
fn parse_sweep_bounds(response: &str) -> Option<(u64, u64)> {
response.lines().find_map(|line| {
let values: Vec<_> = line
.split_whitespace()
.filter_map(|word| word.parse::<u64>().ok())
.collect();
(values.len() >= 2).then(|| (values[0], values[1]))
})
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::config::Config; use crate::config::Config;
use std::{ use std::{
cell::Cell,
io::{self, Cursor}, io::{self, Cursor},
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
@ -324,6 +484,100 @@ mod tests {
assert!(!commands.contains("\rscan ")); assert!(!commands.contains("\rscan "));
} }
#[test]
fn identification_retries_once_after_an_unusable_version() {
let mut config = Config::default();
config.scan.legacy_pre_scan = false;
config.serial.command_delay_ms = 0;
config.serial.settle_delay_ms = 0;
let request = ScanRequest {
start_hz: 240_000_000,
stop_hz: 960_000_000,
points: 2,
repeat: 1,
};
let mut input = b"ch>\r\nch>unknown\r\nch>tinySA_v1.4-test\r\nch>tinySA\r\nch>Commands: repeat zero pause mode sweep scanraw resume\r\nch>"
.to_vec();
input.extend_from_slice(b"okch>".repeat(2).as_slice());
input.extend_from_slice(b"128dBm\r\nch>");
input.extend_from_slice(b"okch>".repeat(5).as_slice());
input.extend_from_slice(b"{x\0\x08x\0\x10}ch>okch>");
let commands = Arc::new(Mutex::new(Vec::new()));
let mut shell = Shell::new(
Transcript {
input: Cursor::new(input),
commands: commands.clone(),
},
1024,
);
let mut events = Vec::new();
let result = acquire(
&mut shell,
&request,
&config.scan,
&config.serial,
|event| events.push(event),
);
assert!(result.is_ok(), "{result:?}");
let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap();
assert!(written.starts_with("version\rinfo\rversion\rinfo\rhelp\r"));
assert_eq!(written.matches("version\r").count(), 2);
assert!(events.contains(&ScanEvent::Message("Retrying instrument identification")));
}
#[test]
fn live_acquisition_repeats_complete_snapshots_then_resumes() {
let config = Config::from_toml(
"[scan]\nlegacy_pre_scan=false\n[serial]\ncommand_delay_ms=0\nsettle_delay_ms=0",
)
.unwrap();
let request = ScanRequest {
start_hz: 240_000_000,
stop_hz: 960_000_000,
points: 2,
repeat: 1,
};
let mut input = b"ch>tinySA_v1.4-test\r\nch>tinySA\r\nch>Commands: repeat zero pause mode sweep scanraw resume\r\nch>"
.to_vec();
input.extend_from_slice(b"okch>".repeat(2).as_slice());
input.extend_from_slice(b"128dBm\r\nch>");
input.extend_from_slice(b"okch>".repeat(5).as_slice());
input.extend_from_slice(b"{x\0\x08x\0\x10}ch>");
input.extend_from_slice(b"{x\0\x10x\0\x18}ch>okch>");
let commands = Arc::new(Mutex::new(Vec::new()));
let mut shell = Shell::new(
Transcript {
input: Cursor::new(input),
commands: commands.clone(),
},
1024,
);
let received = Cell::new(0_u64);
let mut levels = Vec::new();
let sweeps = acquire_live(
&mut shell,
&request,
&config.scan,
&config.serial,
|| received.get() == 2,
|samples| {
received.set(received.get() + 1);
levels.push(samples[0].level_dbm);
},
|_| {},
)
.unwrap();
assert_eq!(sweeps, 2);
assert_eq!(levels, vec![-64.0, 0.0]);
let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap();
assert_eq!(written.matches("scanraw ").count(), 2);
assert!(written.ends_with("resume\r"));
}
#[test] #[test]
fn malformed_frames_still_resume_and_preserve_original_error() { fn malformed_frames_still_resume_and_preserve_original_error() {
let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", true, true); let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", true, true);
@ -349,6 +603,11 @@ mod tests {
Some(174) Some(174)
); );
assert_eq!(parse_zero_offset("174 dBm"), None); assert_eq!(parse_zero_offset("174 dBm"), None);
assert_eq!(
parse_sweep_bounds("sweep\r\n900000000 5400000000 450\r\n"),
Some((900_000_000, 5_400_000_000))
);
assert_eq!(parse_sweep_bounds("ok"), None);
} }
#[test] #[test]
@ -383,7 +642,14 @@ mod tests {
) )
.unwrap(); .unwrap();
let commands = Arc::new(Mutex::new(Vec::new())); let commands = Arc::new(Mutex::new(Vec::new()));
let input = format!("ch>{version}\r\nch>{info}\r\nch>{help}\r\nch>ch>ch>{zero}\r\nch>"); let retry_identity = if matches!(expected, "unsupported device" | "conflicting") {
format!("{version}\r\nch>{info}\r\nch>")
} else {
String::new()
};
let input = format!(
"ch>{version}\r\nch>{info}\r\nch>{retry_identity}{help}\r\nch>ch>ch>{zero}\r\nch>"
);
let mut shell = Shell::new( let mut shell = Shell::new(
Transcript { Transcript {
input: Cursor::new(input.into_bytes()), input: Cursor::new(input.into_bytes()),
@ -405,4 +671,55 @@ mod tests {
assert!(!written.contains("scanraw ")); assert!(!written.contains("scanraw "));
} }
} }
#[test]
fn zs406_extended_scan_is_opt_in_and_verifies_sweep_readback() {
let request = ScanRequest {
start_hz: 900_000_000,
stop_hz: 5_400_000_000,
points: 2,
repeat: 1,
};
let run = |enable_ultra_mode: bool, sweep: &str| {
let mut config = Config::default();
config.scan.enable_ultra_mode = enable_ultra_mode;
config.scan.legacy_pre_scan = false;
config.serial.command_delay_ms = 0;
config.serial.settle_delay_ms = 0;
let input = format!(
"ch>tinySA4_v1.4-test\r\nHW Version:V0.4.6\r\nch>tinySA Ultra+ ZS406\r\nch>Commands: repeat zero pause mode ultra sweep scanraw resume\r\nch>ch>ch>174dBm\r\nch>ch>ch>ch>ch>ch>{sweep}\r\nch>{{x\0\x08x\0\x10}}ch>ch>"
);
let commands = Arc::new(Mutex::new(Vec::new()));
let mut shell = Shell::new(
Transcript {
input: Cursor::new(input.into_bytes()),
commands: commands.clone(),
},
1024,
);
let result = acquire(&mut shell, &request, &config.scan, &config.serial, |_| {});
let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap();
(result, written)
};
let (result, commands) = run(false, "900000000 5400000000 450");
assert!(result
.unwrap_err()
.to_string()
.contains("enable_ultra_mode"));
assert!(!commands.contains("pause\r"));
let (result, commands) = run(true, "900000000 5400000000 450");
assert!(result.is_ok(), "{result:?}");
assert!(commands.contains("mode low input\rultra on\r"));
assert!(commands.contains("scanraw 900000000 5400000000 2\r"));
let (result, commands) = run(true, "900000000 900000000 450");
assert!(matches!(
result,
Err(AcquisitionError::SweepReadbackMismatch { .. })
));
assert!(!commands.contains("scanraw "));
assert!(commands.ends_with("resume\r"));
}
} }

View File

@ -38,7 +38,7 @@ pub struct Config {
pub port: String, pub port: String,
/// Selected baud rate, which must occur in `serial.baudrates`. /// Selected baud rate, which must occur in `serial.baudrates`.
pub baudrate: u32, pub baudrate: u32,
/// Scan start in MHz, within the Basic 0–960 MHz envelope. /// Scan start in MHz, within the application's 0–5,400 MHz envelope.
pub start_frequency: usize, pub start_frequency: usize,
/// Scan stop in MHz, no lower than the start. /// Scan stop in MHz, no lower than the start.
pub stop_frequency: usize, pub stop_frequency: usize,
@ -130,6 +130,8 @@ pub enum ModelSelection {
pub struct ScanConfig { pub struct ScanConfig {
/// Expected device family; `auto` still rejects unknown or conflicting identity. /// Expected device family; `auto` still rejects unknown or conflicting identity.
pub device_model: ModelSelection, pub device_model: ModelSelection,
/// Explicitly permit ZS406 Ultra mode for analyzer scans above 900 MHz.
pub enable_ultra_mode: bool,
/// Select the detected model's native raw-level offset. /// Select the detected model's native raw-level offset.
pub auto_zero_offset: bool, pub auto_zero_offset: bool,
/// Offset sent with `zero` and subtracted from raw levels, in dB. /// Offset sent with `zero` and subtracted from raw levels, in dB.
@ -161,6 +163,27 @@ pub struct UiConfig {
pub chart_min_dbm: f64, pub chart_min_dbm: f64,
/// Chart upper bound, in dBm. /// Chart upper bound, in dBm.
pub chart_max_dbm: f64, pub chart_max_dbm: f64,
/// Configurable keyboard shortcuts used by completed, CSV, and live plots.
pub bindings: PlotBindings,
}
/// Keyboard bindings for navigating a rendered frequency plot.
///
/// Each entry is either one Unicode character or one of `left`, `right`, and
/// `home`. Bindings are case-sensitive for characters and must not overlap.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct PlotBindings {
/// Keys that halve the visible frequency span.
pub zoom_in: Vec<String>,
/// Keys that double the visible frequency span.
pub zoom_out: Vec<String>,
/// Keys that move the viewport toward lower frequencies.
pub pan_left: Vec<String>,
/// Keys that move the viewport toward higher frequencies.
pub pan_right: Vec<String>,
/// Keys that restore the complete frequency range.
pub reset_view: Vec<String>,
} }
/// CSV settings; paths are relative to the working directory unless absolute. /// CSV settings; paths are relative to the working directory unless absolute.
@ -249,9 +272,9 @@ impl Config {
)?; )?;
require( require(
self.start_frequency <= self.stop_frequency self.start_frequency <= self.stop_frequency
&& self.stop_frequency <= 960 && self.stop_frequency <= 5_400
&& self.stop_frequency >= 10, && self.stop_frequency >= 10,
"frequencies must be ordered in 0–960 MHz, with stop at least 10 MHz", "frequencies must be ordered in 0–5400 MHz, with stop at least 10 MHz",
)?; )?;
require( require(
self.scan.min_points >= 2 self.scan.min_points >= 2
@ -269,7 +292,7 @@ impl Config {
"repeat must be within 1..=scan.max_repeat, which cannot exceed 1000", "repeat must be within 1..=scan.max_repeat, which cannot exceed 1000",
)?; )?;
require( require(
(1..=960).contains(&self.scan.frequency_step_mhz) (1..=5_400).contains(&self.scan.frequency_step_mhz)
&& (1..=self.scan.max_points).contains(&self.scan.points_step), && (1..=self.scan.max_points).contains(&self.scan.points_step),
"scan keyboard steps must be positive and within their bounds", "scan keyboard steps must be positive and within their bounds",
)?; )?;
@ -316,6 +339,31 @@ impl Config {
&& self.ui.chart_min_dbm < self.ui.chart_max_dbm, && self.ui.chart_min_dbm < self.ui.chart_max_dbm,
"UI chart bounds must be finite and increasing", "UI chart bounds must be finite and increasing",
)?; )?;
let binding_groups = [
&self.ui.bindings.zoom_in,
&self.ui.bindings.zoom_out,
&self.ui.bindings.pan_left,
&self.ui.bindings.pan_right,
&self.ui.bindings.reset_view,
];
require(
binding_groups.iter().all(|group| !group.is_empty()),
"each UI plot action must have at least one binding",
)?;
let mut bindings: Vec<&str> = Vec::new();
for binding in binding_groups.into_iter().flatten() {
let valid = matches!(binding.as_str(), "left" | "right" | "home")
|| (binding.chars().count() == 1 && !binding.chars().any(char::is_control));
require(
valid && binding != "q",
"UI plot bindings must be one printable character or left/right/home; q is reserved",
)?;
require(
!bindings.contains(&binding.as_str()),
"UI plot bindings must not overlap",
)?;
bindings.push(binding);
}
require(!self.output.filename_prefix.is_empty() && self.output.filename_prefix.len() <= 64 && self.output.filename_prefix.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-'), "output.filename_prefix must contain 1–64 ASCII letters, digits, underscores or hyphens")?; require(!self.output.filename_prefix.is_empty() && self.output.filename_prefix.len() <= 64 && self.output.filename_prefix.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_' || c == b'-'), "output.filename_prefix must contain 1–64 ASCII letters, digits, underscores or hyphens")?;
require( require(
!self.output.directory.as_os_str().is_empty() !self.output.directory.as_os_str().is_empty()
@ -359,6 +407,7 @@ mod tests {
let config = Config::from_toml("port = 'COM3'\nbaudrate = 57600\nstart_frequency = 20\nstop_frequency = 100\npoints = 101\nrepeat = 2").unwrap(); let config = Config::from_toml("port = 'COM3'\nbaudrate = 57600\nstart_frequency = 20\nstop_frequency = 100\npoints = 101\nrepeat = 2").unwrap();
assert_eq!(config.port, "COM3"); assert_eq!(config.port, "COM3");
assert_eq!(config.points, 101); assert_eq!(config.points, 101);
assert!(!config.scan.enable_ultra_mode);
assert_eq!(config.serial, Config::default().serial); assert_eq!(config.serial, Config::default().serial);
assert_eq!( assert_eq!(
Config::from_toml("[scan]\nfrequency_axis = 'inclusive'") Config::from_toml("[scan]\nfrequency_axis = 'inclusive'")
@ -367,6 +416,12 @@ mod tests {
.frequency_axis, .frequency_axis,
FrequencyAxis::Inclusive FrequencyAxis::Inclusive
); );
let zs406 = Config::from_toml(
"start_frequency = 900\nstop_frequency = 5400\n[scan]\nenable_ultra_mode = true",
)
.unwrap();
assert!(zs406.scan.enable_ultra_mode);
assert_eq!(zs406.stop_frequency, 5_400);
} }
#[test] #[test]
@ -389,7 +444,7 @@ mod tests {
"broken", "broken",
"pointz = 100", "pointz = 100",
"points = 1", "points = 1",
"start_frequency = 961", "start_frequency = 5401",
"start_frequency = 900\nstop_frequency = 100", "start_frequency = 900\nstop_frequency = 100",
"repeat = 0", "repeat = 0",
"[serial]\nbaudrates = []", "[serial]\nbaudrates = []",
@ -403,6 +458,9 @@ mod tests {
"[scan]\nfrequency_axis = 'unknown'", "[scan]\nfrequency_axis = 'unknown'",
"[ui]\nchart_min_dbm = nan", "[ui]\nchart_min_dbm = nan",
"[ui]\nchart_min_dbm = 1.0", "[ui]\nchart_min_dbm = 1.0",
"[ui.bindings]\nzoom_in = []",
"[ui.bindings]\nzoom_in = ['q']",
"[ui.bindings]\nzoom_in = ['left']",
"[output]\nfilename_prefix = '../scan'", "[output]\nfilename_prefix = '../scan'",
"[logging]\nfilter = ''", "[logging]\nfilter = ''",
"[serial]\ntimeuot_ms = 5", "[serial]\ntimeuot_ms = 5",

View File

@ -1,8 +1,8 @@
//! Device identity parsing and model-specific acquisition policy. //! Device identity parsing and model-specific acquisition policy.
//! //!
//! Identification consumes explicit `version`/`info` evidence. This module //! Identification consumes explicit `version`/`info` evidence. This module
//! selects only acquisition behavior shared by the detected family; it does not //! selects acquisition behavior only from explicit family and hardware-revision
//! infer an Ultra hardware revision or unlock extended/harmonic modes. //! evidence. ZS406 Ultra mode is opt-in; harmonic mode remains unsupported.
use crate::protocol::{ use crate::protocol::{
ProtocolError, ScanRequest, BASIC_MAX_HZ, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB, ProtocolError, ScanRequest, BASIC_MAX_HZ, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB,
@ -13,6 +13,10 @@ use std::fmt;
pub const ULTRA_MIN_HZ: u64 = 100_000; pub const ULTRA_MIN_HZ: u64 = 100_000;
/// Common normal-mode ceiling across supported Ultra family revisions, in Hz. /// Common normal-mode ceiling across supported Ultra family revisions, in Hz.
pub const ULTRA_NORMAL_MAX_HZ: u64 = 800_000_000; pub const ULTRA_NORMAL_MAX_HZ: u64 = 800_000_000;
/// ZS406 normal-mode ceiling, in Hz.
pub const ZS406_NORMAL_MAX_HZ: u64 = 900_000_000;
/// Highest ZS406 frequency supported without harmonic mixing, in Hz.
pub const ZS406_ULTRA_MAX_HZ: u64 = 5_400_000_000;
/// Device family established from console identity replies. /// Device family established from console identity replies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -23,6 +27,27 @@ pub enum DeviceModel {
Ultra, Ultra,
} }
/// Hardware revision established from the firmware's `version`/`info` text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UltraRevision {
/// Original tinySA Ultra hardware.
Zs405,
/// First tinySA Ultra+ hardware, version V0.4.6.
Zs406,
/// Later tinySA Ultra+ hardware; retained on the conservative family range.
Zs407,
}
impl fmt::Display for UltraRevision {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Zs405 => "ZS405",
Self::Zs406 => "ZS406",
Self::Zs407 => "ZS407",
})
}
}
impl fmt::Display for DeviceModel { impl fmt::Display for DeviceModel {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self { formatter.write_str(match self {
@ -37,6 +62,8 @@ impl fmt::Display for DeviceModel {
pub struct DeviceIdentity { pub struct DeviceIdentity {
/// Detected device family. /// Detected device family.
pub model: DeviceModel, pub model: DeviceModel,
/// Ultra-family hardware revision, when the replies contain explicit evidence.
pub ultra_revision: Option<UltraRevision>,
/// Verbatim prompt-stripped `version` response. /// Verbatim prompt-stripped `version` response.
pub version: String, pub version: String,
/// Verbatim prompt-stripped `info` response. /// Verbatim prompt-stripped `info` response.
@ -52,6 +79,8 @@ pub struct AcquisitionPlan {
pub input_command: &'static str, pub input_command: &'static str,
/// Native raw-level encoding offset, in dB. /// Native raw-level encoding offset, in dB.
pub native_zero_offset_db: u16, pub native_zero_offset_db: u16,
/// Whether the acquisition must explicitly enable firmware Ultra mode.
pub enable_ultra_mode: bool,
} }
/// Device identification failures occur before acquisition settings are changed. /// Device identification failures occur before acquisition settings are changed.
@ -63,6 +92,9 @@ pub enum DeviceError {
/// Basic and Ultra signatures occurred in the same identity exchange. /// Basic and Ultra signatures occurred in the same identity exchange.
#[error("conflicting device identity: replies identify both tinySA Basic and Ultra")] #[error("conflicting device identity: replies identify both tinySA Basic and Ultra")]
Conflicting, Conflicting,
/// More than one Ultra revision signature occurred in the identity exchange.
#[error("conflicting device identity: replies identify multiple tinySA Ultra revisions")]
ConflictingRevision,
} }
impl DeviceIdentity { impl DeviceIdentity {
@ -89,12 +121,85 @@ impl DeviceIdentity {
(true, true) => return Err(DeviceError::Conflicting), (true, true) => return Err(DeviceError::Conflicting),
(false, false) => return Err(DeviceError::Unknown), (false, false) => return Err(DeviceError::Unknown),
}; };
let identity_lower = format!("{version_lower}\n{info_lower}");
let revision_matches = [
(
UltraRevision::Zs405,
identity_lower.contains("zs405") || identity_lower.contains("hw version:v0.4.5.1"),
),
(
UltraRevision::Zs406,
identity_lower.contains("zs406") || identity_lower.contains("hw version:v0.4.6"),
),
(
UltraRevision::Zs407,
identity_lower.contains("zs407")
|| identity_lower.contains("hw version:v0.5.3")
|| identity_lower.contains("hw version:v0.5.4"),
),
];
let mut revisions = revision_matches
.into_iter()
.filter_map(|(revision, matches)| matches.then_some(revision));
let ultra_revision = revisions.next();
if revisions.next().is_some() {
return Err(DeviceError::ConflictingRevision);
}
let ultra_revision = (model == DeviceModel::Ultra)
.then_some(ultra_revision)
.flatten();
Ok(Self { Ok(Self {
model, model,
ultra_revision,
version, version,
info, info,
}) })
} }
/// Validate a request using detected revision evidence and explicit Ultra opt-in.
pub fn plan(
&self,
request: &ScanRequest,
allow_ultra_mode: bool,
) -> Result<AcquisitionPlan, ProtocolError> {
if self.model == DeviceModel::Basic {
return self.model.plan(request);
}
request.validate()?;
if request.start_hz < ULTRA_MIN_HZ {
return Err(ProtocolError::InvalidRequest(
"tinySA Ultra frequencies must start at or above 0.1 MHz".into(),
));
}
let normal_max_hz = match self.ultra_revision {
Some(UltraRevision::Zs406) => ZS406_NORMAL_MAX_HZ,
Some(UltraRevision::Zs405 | UltraRevision::Zs407) | None => ULTRA_NORMAL_MAX_HZ,
};
let enable_ultra_mode = request.stop_hz > normal_max_hz;
if enable_ultra_mode {
if self.ultra_revision != Some(UltraRevision::Zs406) {
return Err(ProtocolError::InvalidRequest(
"extended acquisition currently requires an explicitly detected ZS406".into(),
));
}
if !allow_ultra_mode {
return Err(ProtocolError::InvalidRequest(
"ZS406 scans above 900 MHz require scan.enable_ultra_mode = true".into(),
));
}
if request.stop_hz > ZS406_ULTRA_MAX_HZ {
return Err(ProtocolError::InvalidRequest(
"ZS406 support stops at 5.4 GHz; harmonic mode is not supported".into(),
));
}
}
Ok(AcquisitionPlan {
model: self.model,
input_command: "mode low input",
native_zero_offset_db: ULTRA_RAW_LEVEL_OFFSET_DB,
enable_ultra_mode,
})
}
} }
impl DeviceModel { impl DeviceModel {
@ -133,6 +238,7 @@ impl DeviceModel {
model: self, model: self,
input_command, input_command,
native_zero_offset_db, native_zero_offset_db,
enable_ultra_mode: false,
}) })
} }
} }
@ -159,11 +265,23 @@ mod tests {
DeviceModel::Basic DeviceModel::Basic
); );
assert_eq!( assert_eq!(
DeviceIdentity::detect("tinySA4_v1.4-200-gabc".into(), "tinySA Ultra+".into()) DeviceIdentity::detect(
.unwrap() "tinySA4_v1.4-200-gabc\r\nHW Version:V0.4.6".into(),
.model, "tinySA Ultra+ ZS406".into()
)
.unwrap()
.model,
DeviceModel::Ultra DeviceModel::Ultra
); );
assert_eq!(
DeviceIdentity::detect(
"tinySA4_v1.4-200-gabc\r\nHW Version:V0.4.6".into(),
"tinySA Ultra+ ZS406".into()
)
.unwrap()
.ultra_revision,
Some(UltraRevision::Zs406)
);
assert_eq!( assert_eq!(
DeviceIdentity::detect("version unknown".into(), "instrument".into()), DeviceIdentity::detect("version unknown".into(), "instrument".into()),
Err(DeviceError::Unknown) Err(DeviceError::Unknown)
@ -195,4 +313,39 @@ mod tests {
.plan(&request(100_000, 800_000_001)) .plan(&request(100_000, 800_000_001))
.is_err()); .is_err());
} }
#[test]
fn zs406_plan_separates_normal_ultra_and_harmonic_ranges() {
let identity = DeviceIdentity::detect(
"tinySA4_v1.4-test\r\nHW Version:V0.4.6".into(),
"tinySA Ultra+ ZS406".into(),
)
.unwrap();
let normal = identity
.plan(&request(ULTRA_MIN_HZ, ZS406_NORMAL_MAX_HZ), false)
.unwrap();
assert!(!normal.enable_ultra_mode);
assert!(identity
.plan(&request(900_000_000, ZS406_ULTRA_MAX_HZ), false)
.is_err());
let ultra = identity
.plan(&request(900_000_000, ZS406_ULTRA_MAX_HZ), true)
.unwrap();
assert!(ultra.enable_ultra_mode);
assert!(identity
.plan(&request(900_000_000, ZS406_ULTRA_MAX_HZ + 1), true)
.is_err());
let zs407 = DeviceIdentity::detect(
"tinySA4_v1.4-test\r\nHW Version:V0.5.4".into(),
"tinySA Ultra+ ZS407".into(),
)
.unwrap();
assert!(zs407
.plan(&request(ULTRA_MIN_HZ, ULTRA_NORMAL_MAX_HZ), false)
.is_ok());
assert!(zs407
.plan(&request(ULTRA_MIN_HZ, ULTRA_NORMAL_MAX_HZ + 1), true)
.is_err());
}
} }

View File

@ -3,6 +3,9 @@
/// Errors surfaced during startup or acquisition. /// Errors surfaced during startup or acquisition.
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub(crate) enum AppError { pub(crate) enum AppError {
/// Command-line arguments do not select a supported startup mode.
#[error("{0}")]
Usage(String),
/// Configuration read, validation or persistence failed. /// Configuration read, validation or persistence failed.
#[error(transparent)] #[error(transparent)]
Config(#[from] tiny_wb::config::ConfigError), Config(#[from] tiny_wb::config::ConfigError),
@ -15,9 +18,20 @@ pub(crate) enum AppError {
/// Filesystem or terminal I/O failed. /// Filesystem or terminal I/O failed.
#[error("I/O: {0}")] #[error("I/O: {0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
/// A requested scan CSV could not be opened or decoded.
#[error("cannot load CSV {}: {source}", path.display())]
Csv {
/// Requested input path.
path: std::path::PathBuf,
/// File or data error.
source: std::io::Error,
},
/// Acquisition failed, potentially including a failed resume attempt. /// Acquisition failed, potentially including a failed resume attempt.
#[error(transparent)] #[error(transparent)]
Acquisition(#[from] tiny_wb::acquisition::AcquisitionError), Acquisition(#[from] tiny_wb::acquisition::AcquisitionError),
/// Host-side live trace processing failed.
#[error("live capture: {0}")]
Live(String),
/// The file logger could not be initialized. /// The file logger could not be initialized.
#[error("logging: {0}")] #[error("logging: {0}")]
Logger(#[from] flexi_logger::FlexiLoggerError), Logger(#[from] flexi_logger::FlexiLoggerError),

View File

@ -1,13 +1,88 @@
//! CSV serialization and collision-safe file creation, separate from decoding. //! CSV serialization and collision-safe file creation, separate from decoding.
use crate::{config::OutputConfig, protocol::Sample}; use crate::{config::OutputConfig, protocol::Sample};
use chrono::Local; use jiff::ZonedDateTime;
use std::{ use std::{
fs::{self, OpenOptions}, fs::{self, OpenOptions},
io::{self, BufWriter, Write}, io::{self, BufRead, BufWriter, Write},
path::PathBuf, path::PathBuf,
}; };
/// Read samples from tiny-wb's two-column CSV representation.
///
/// Both headerless exports and files beginning with
/// `frequency_MHz,level_dBm` are accepted. Blank lines are ignored. Every data
/// row must contain exactly two finite numbers and frequencies must be in
/// nondecreasing order. An empty file is rejected.
///
/// # Errors
/// Returns [`io::ErrorKind::InvalidData`] with a line number for malformed CSV.
pub fn read_csv(reader: impl BufRead) -> io::Result<Vec<Sample>> {
let mut samples = Vec::new();
let mut saw_header = false;
for (index, line) in reader.lines().enumerate() {
let line_number = index + 1;
let line = line?;
let line = line.trim();
if line.is_empty() {
continue;
}
if samples.is_empty() && !saw_header && line == "frequency_MHz,level_dBm" {
saw_header = true;
continue;
}
let mut columns = line.split(',');
let frequency = columns.next();
let level = columns.next();
if frequency.is_none() || level.is_none() || columns.next().is_some() {
return Err(invalid_csv(line_number, "expected exactly two columns"));
}
let parse = |value: &str, name: &str| {
value.trim().parse::<f64>().map_err(|_| {
invalid_csv(
line_number,
&format!("invalid {name} number `{}`", value.trim()),
)
})
};
let frequency_mhz = parse(frequency.unwrap_or_default(), "frequency")?;
let level_dbm = parse(level.unwrap_or_default(), "level")?;
if !frequency_mhz.is_finite() || !level_dbm.is_finite() {
return Err(invalid_csv(line_number, "values must be finite"));
}
if samples
.last()
.is_some_and(|sample: &Sample| sample.frequency_mhz > frequency_mhz)
{
return Err(invalid_csv(
line_number,
"frequencies must be in nondecreasing order",
));
}
samples.push(Sample {
frequency_mhz,
level_dbm,
});
}
if samples.is_empty() {
return Err(invalid_csv(0, "file contains no samples"));
}
Ok(samples)
}
/// Build a bounded, contextual malformed-CSV error.
fn invalid_csv(line: usize, message: &str) -> io::Error {
let location = if line == 0 {
String::new()
} else {
format!(" at line {line}")
};
io::Error::new(
io::ErrorKind::InvalidData,
format!("invalid scan CSV{location}: {message}"),
)
}
/// Write sample values to any writer, optionally with an explicit units header. /// Write sample values to any writer, optionally with an explicit units header.
/// ///
/// The caller decides when/how to open and flush a file. Every write error is /// The caller decides when/how to open and flush a file. Every write error is
@ -33,7 +108,7 @@ pub fn write_csv(
/// Readers may see the in-progress file, so only the returned path means complete. /// Readers may see the in-progress file, so only the returned path means complete.
pub fn save_csv(samples: &[Sample], settings: &OutputConfig) -> io::Result<PathBuf> { pub fn save_csv(samples: &[Sample], settings: &OutputConfig) -> io::Result<PathBuf> {
fs::create_dir_all(&settings.directory)?; fs::create_dir_all(&settings.directory)?;
let stamp = Local::now().format("%Y%m%d %H_%M_%S_%6f").to_string(); let stamp = filename_stamp(&ZonedDateTime::now());
for suffix in 0..100 { for suffix in 0..100 {
let path = settings let path = settings
.directory .directory
@ -60,10 +135,33 @@ pub fn save_csv(samples: &[Sample], settings: &OutputConfig) -> io::Result<PathB
)) ))
} }
/// Preserve the local calendar fields and six fractional digits in export names.
fn filename_stamp(now: &ZonedDateTime) -> String {
now.strftime("%Y%m%d %H_%M_%S_%6f").to_string()
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn filename_timestamp_preserves_local_time_and_microseconds() {
for (input, expected) in [
(
"2024-02-29T23:59:58.123456789+05:30[+05:30]",
"20240229 23_59_58_123456",
),
(
"2026-01-01T00:00:00.000001-04:00[-04:00]",
"20260101 00_00_00_000001",
),
("2026-01-01T00:00:00Z[UTC]", "20260101 00_00_00_000000"),
] {
let now: ZonedDateTime = input.parse().unwrap();
assert_eq!(filename_stamp(&now), expected);
}
}
#[test] #[test]
fn csv_has_explicit_units_only_when_requested() { fn csv_has_explicit_units_only_when_requested() {
let samples = [Sample { let samples = [Sample {
@ -95,6 +193,34 @@ mod tests {
); );
} }
#[test]
fn csv_reader_accepts_header_and_headerless_data() {
let expected = vec![Sample {
frequency_mhz: 240.5,
level_dbm: -64.25,
}];
assert_eq!(
read_csv(&b"frequency_MHz,level_dBm\n240.5,-64.25\n"[..]).unwrap(),
expected
);
assert_eq!(read_csv(&b"\n240.5, -64.25\n"[..]).unwrap(), expected);
}
#[test]
fn csv_reader_rejects_empty_malformed_and_unordered_data() {
for input in [
"",
"frequency_MHz,level_dBm\n",
"240\n",
"MHz,dBm\n",
"240,NaN\n",
"241,-1\n240,-2\n",
] {
let error = read_csv(input.as_bytes()).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{input:?}");
}
}
#[test] #[test]
fn scans_do_not_overwrite_each_other() { fn scans_do_not_overwrite_each_other() {
let directory = std::env::temp_dir().join(format!("tiny-wb-export-{}", std::process::id())); let directory = std::env::temp_dir().join(format!("tiny-wb-export-{}", std::process::id()));

View File

@ -27,6 +27,7 @@ pub mod config;
pub mod connection; pub mod connection;
pub mod device; pub mod device;
pub mod export; pub mod export;
pub mod live;
/// Opt-in deterministic simulator and TCP server support. /// Opt-in deterministic simulator and TCP server support.
#[cfg(feature = "mock")] #[cfg(feature = "mock")]
pub mod mock; pub mod mock;

283
src/live.rs Normal file
View File

@ -0,0 +1,283 @@
//! Bounded host-side processing for repeated live scan snapshots.
//!
//! This module owns no device, terminal or file. It retains at most sixteen
//! complete sweeps and one value per point for each hold/decay trace.
use crate::protocol::Sample;
use std::{collections::VecDeque, fmt};
/// Host-side trace calculation shown and exported by live mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TraceMode {
/// Rolling arithmetic mean of up to four completed sweeps.
Average4,
/// Rolling arithmetic mean of up to sixteen completed sweeps.
Average16,
/// Highest value observed at every frequency since capture began.
MaxHold,
/// Maximum trace that falls by 1 dB per completed sweep.
MaxDecay,
/// Lowest value observed at every frequency since capture began.
MinHold,
/// Minimum trace that rises by 1 dB per completed sweep.
MinDecay,
}
impl TraceMode {
/// Resolve the live-mode number-key binding.
pub fn from_key(key: char) -> Option<Self> {
match key {
'1' => Some(Self::Average4),
'2' => Some(Self::Average16),
'3' => Some(Self::MaxHold),
'4' => Some(Self::MaxDecay),
'5' => Some(Self::MinHold),
'6' => Some(Self::MinDecay),
_ => None,
}
}
}
impl fmt::Display for TraceMode {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Average4 => "average 4",
Self::Average16 => "average 16",
Self::MaxHold => "max hold",
Self::MaxDecay => "max decay",
Self::MinHold => "min hold",
Self::MinDecay => "min decay",
})
}
}
/// A malformed or incompatible sweep supplied to [`TraceBuffer`].
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum LiveTraceError {
/// Live traces require at least one point.
#[error("a live sweep cannot be empty")]
Empty,
/// Every sweep must retain the configured point count.
#[error("live sweep has {actual} points; expected {expected}")]
PointCount {
/// Point count established by the first sweep.
expected: usize,
/// Point count in the rejected sweep.
actual: usize,
},
/// A point's frequency changed between repeated snapshots.
#[error(
"live sweep frequency changed at point {index}: expected {expected} MHz, got {actual} MHz"
)]
Frequency {
/// Zero-based point index.
index: usize,
/// Frequency established by the first sweep, in MHz.
expected: f64,
/// Frequency in the rejected sweep, in MHz.
actual: f64,
},
/// Input values must remain finite before processing.
#[error("live sweep contains a non-finite value at point {index}")]
NonFinite {
/// Zero-based point index.
index: usize,
},
}
/// Bounded rolling history and derived hold/decay traces.
#[derive(Debug, Default)]
pub struct TraceBuffer {
history: VecDeque<Vec<Sample>>,
max_hold: Vec<f64>,
max_decay: Vec<f64>,
min_hold: Vec<f64>,
min_decay: Vec<f64>,
sweeps: u64,
}
impl TraceBuffer {
/// Add one complete sweep, rejecting axis or point-count changes.
///
/// # Errors
///
/// Returns [`LiveTraceError`] for an empty sweep, non-finite values, or a
/// point count or frequency axis that differs from the retained history.
/// Rejected input does not change the buffer.
pub fn push(&mut self, samples: Vec<Sample>) -> Result<(), LiveTraceError> {
if samples.is_empty() {
return Err(LiveTraceError::Empty);
}
for (index, sample) in samples.iter().enumerate() {
if !sample.frequency_mhz.is_finite() || !sample.level_dbm.is_finite() {
return Err(LiveTraceError::NonFinite { index });
}
}
if let Some(previous) = self.history.back() {
if previous.len() != samples.len() {
return Err(LiveTraceError::PointCount {
expected: previous.len(),
actual: samples.len(),
});
}
for (index, (expected, actual)) in previous.iter().zip(&samples).enumerate() {
if expected.frequency_mhz != actual.frequency_mhz {
return Err(LiveTraceError::Frequency {
index,
expected: expected.frequency_mhz,
actual: actual.frequency_mhz,
});
}
}
}
if self.history.is_empty() {
let levels: Vec<_> = samples.iter().map(|sample| sample.level_dbm).collect();
self.max_hold = levels.clone();
self.max_decay = levels.clone();
self.min_hold = levels.clone();
self.min_decay = levels;
} else {
for (index, sample) in samples.iter().enumerate() {
self.max_hold[index] = self.max_hold[index].max(sample.level_dbm);
self.min_hold[index] = self.min_hold[index].min(sample.level_dbm);
self.max_decay[index] = (self.max_decay[index] - 1.0).max(sample.level_dbm);
self.min_decay[index] = (self.min_decay[index] + 1.0).min(sample.level_dbm);
}
}
self.history.push_back(samples);
if self.history.len() > 16 {
self.history.pop_front();
}
self.sweeps = self.sweeps.saturating_add(1);
Ok(())
}
/// Number of complete sweeps incorporated since the last reset.
pub fn sweeps(&self) -> u64 {
self.sweeps
}
/// Produce the selected trace with the original frequency axis.
pub fn trace(&self, mode: TraceMode) -> Option<Vec<Sample>> {
let latest = self.history.back()?;
let levels = match mode {
TraceMode::Average4 => return Some(self.average(4)),
TraceMode::Average16 => return Some(self.average(16)),
TraceMode::MaxHold => &self.max_hold,
TraceMode::MaxDecay => &self.max_decay,
TraceMode::MinHold => &self.min_hold,
TraceMode::MinDecay => &self.min_decay,
};
Some(
latest
.iter()
.zip(levels)
.map(|(sample, level)| Sample {
frequency_mhz: sample.frequency_mhz,
level_dbm: *level,
})
.collect(),
)
}
fn average(&self, count: usize) -> Vec<Sample> {
let used = self.history.len().min(count);
let start = self.history.len() - used;
let latest = self.history.back().expect("average requires one sweep");
latest
.iter()
.enumerate()
.map(|(index, sample)| Sample {
frequency_mhz: sample.frequency_mhz,
level_dbm: self
.history
.iter()
.skip(start)
.map(|sweep| sweep[index].level_dbm)
.sum::<f64>()
/ used as f64,
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sweep(levels: &[f64]) -> Vec<Sample> {
levels
.iter()
.enumerate()
.map(|(index, level)| Sample {
frequency_mhz: 100.0 + index as f64,
level_dbm: *level,
})
.collect()
}
fn levels(buffer: &TraceBuffer, mode: TraceMode) -> Vec<f64> {
buffer
.trace(mode)
.unwrap()
.into_iter()
.map(|sample| sample.level_dbm)
.collect()
}
#[test]
fn rolling_averages_are_bounded_to_four_and_sixteen_sweeps() {
let mut buffer = TraceBuffer::default();
for level in 1..=20 {
buffer.push(sweep(&[f64::from(level)])).unwrap();
}
assert_eq!(buffer.history.len(), 16);
assert_eq!(levels(&buffer, TraceMode::Average4), vec![18.5]);
assert_eq!(levels(&buffer, TraceMode::Average16), vec![12.5]);
assert_eq!(buffer.sweeps(), 20);
}
#[test]
fn holds_and_one_db_decay_follow_deterministic_sequences() {
let mut buffer = TraceBuffer::default();
buffer.push(sweep(&[-10.0, -30.0])).unwrap();
buffer.push(sweep(&[-20.0, -20.0])).unwrap();
assert_eq!(levels(&buffer, TraceMode::MaxHold), vec![-10.0, -20.0]);
assert_eq!(levels(&buffer, TraceMode::MinHold), vec![-20.0, -30.0]);
assert_eq!(levels(&buffer, TraceMode::MaxDecay), vec![-11.0, -20.0]);
assert_eq!(levels(&buffer, TraceMode::MinDecay), vec![-20.0, -29.0]);
}
#[test]
fn incompatible_or_non_finite_sweeps_are_rejected_without_mutation() {
let mut buffer = TraceBuffer::default();
assert_eq!(buffer.push(Vec::new()), Err(LiveTraceError::Empty));
buffer.push(sweep(&[-10.0, -20.0])).unwrap();
assert!(matches!(
buffer.push(sweep(&[-10.0])),
Err(LiveTraceError::PointCount { .. })
));
let mut changed = sweep(&[-10.0, -20.0]);
changed[1].frequency_mhz = 999.0;
assert!(matches!(
buffer.push(changed),
Err(LiveTraceError::Frequency { .. })
));
assert!(matches!(
buffer.push(sweep(&[f64::NAN, -20.0])),
Err(LiveTraceError::NonFinite { .. })
));
assert_eq!(buffer.sweeps(), 1);
}
#[test]
fn number_keys_select_every_supported_mode() {
assert_eq!(TraceMode::from_key('1'), Some(TraceMode::Average4));
assert_eq!(TraceMode::from_key('2'), Some(TraceMode::Average16));
assert_eq!(TraceMode::from_key('3'), Some(TraceMode::MaxHold));
assert_eq!(TraceMode::from_key('4'), Some(TraceMode::MaxDecay));
assert_eq!(TraceMode::from_key('5'), Some(TraceMode::MinHold));
assert_eq!(TraceMode::from_key('6'), Some(TraceMode::MinDecay));
assert_eq!(TraceMode::from_key('7'), None);
}
}

View File

@ -7,9 +7,39 @@ mod ui;
use error::AppError; use error::AppError;
use flexi_logger::{FileSpec, Logger, WriteMode}; use flexi_logger::{FileSpec, Logger, WriteMode};
use std::path::PathBuf; use std::{ffi::OsString, fs::File, io::BufReader, path::PathBuf};
use tiny_wb::config::{Backend, Config}; use tiny_wb::config::{Backend, Config};
/// Startup route selected by the small command-line surface.
#[derive(Debug, PartialEq, Eq)]
enum StartMode {
/// Configure and acquire a new scan.
Acquire,
/// Configure and run repeated snapshots until the user stops them.
Live,
/// Open an existing CSV directly in the renderer.
View(PathBuf),
/// Print command help without loading configuration.
Help,
}
/// Interpret zero arguments as acquisition and one CSV path as direct viewing.
fn parse_start_mode(args: impl IntoIterator<Item = OsString>) -> Result<StartMode, AppError> {
let args: Vec<OsString> = args.into_iter().collect();
match args.as_slice() {
[] => Ok(StartMode::Acquire),
[flag] if flag == "--live" => Ok(StartMode::Live),
[flag] if flag == "-h" || flag == "--help" => Ok(StartMode::Help),
[flag, path] if flag == "--view" => Ok(StartMode::View(PathBuf::from(path))),
[path] if !path.to_string_lossy().starts_with('-') => {
Ok(StartMode::View(PathBuf::from(path)))
}
_ => Err(AppError::Usage(
"usage: tiny-wb [--live | --view SCAN.csv | SCAN.csv]".into(),
)),
}
}
/// Restore the terminal on ordinary errors and unwinding after initialization. /// Restore the terminal on ordinary errors and unwinding after initialization.
struct TerminalSession; struct TerminalSession;
@ -22,6 +52,11 @@ impl Drop for TerminalSession {
/// Load and validate settings before taking ownership of the user's terminal. /// Load and validate settings before taking ownership of the user's terminal.
fn main() -> Result<(), AppError> { fn main() -> Result<(), AppError> {
color_eyre::install()?; color_eyre::install()?;
let mode = parse_start_mode(std::env::args_os().skip(1))?;
if mode == StartMode::Help {
println!("tiny-wb [--live | --view SCAN.csv | SCAN.csv]\n\nWith no option, acquire one scan. --live repeats complete snapshots until stopped. With a CSV path, open the plot renderer directly.");
return Ok(());
}
let config_path = std::env::var_os("TINY_WB_CONFIG") let config_path = std::env::var_os("TINY_WB_CONFIG")
.map(PathBuf::from) .map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("config.toml")); .unwrap_or_else(|| PathBuf::from("config.toml"));
@ -29,19 +64,81 @@ fn main() -> Result<(), AppError> {
eprintln!("Cannot load {}: {error}", config_path.display()); eprintln!("Cannot load {}: {error}", config_path.display());
error error
})?; })?;
let loaded_plot = if let StartMode::View(path) = &mode {
let file = File::open(path).map_err(|source| AppError::Csv {
path: path.clone(),
source,
})?;
let samples =
tiny_wb::export::read_csv(BufReader::new(file)).map_err(|source| AppError::Csv {
path: path.clone(),
source,
})?;
Some(
samples
.into_iter()
.map(|sample| (sample.frequency_mhz, sample.level_dbm))
.collect(),
)
} else {
None
};
let _logger = Logger::try_with_str(&config.logging.filter)? let _logger = Logger::try_with_str(&config.logging.filter)?
.log_to_file(FileSpec::default().directory(&config.logging.directory)) .log_to_file(FileSpec::default().directory(&config.logging.directory))
.write_mode(WriteMode::BufferAndFlush) .write_mode(WriteMode::BufferAndFlush)
.start()?; .start()?;
let ports = match config.connection.backend { let live_mode = mode == StartMode::Live;
Backend::Serial => serialport::available_ports()?, let mut app = match mode {
Backend::Tcp => vec![serialport::SerialPortInfo { StartMode::Acquire | StartMode::Live => {
port_name: format!("tcp://{}", config.connection.tcp_address), let ports = match config.connection.backend {
port_type: serialport::SerialPortType::Unknown, Backend::Serial => serialport::available_ports()?,
}], Backend::Tcp => vec![serialport::SerialPortInfo {
port_name: format!("tcp://{}", config.connection.tcp_address),
port_type: serialport::SerialPortType::Unknown,
}],
};
if live_mode {
ui::App::live(ports, config, config_path)
} else {
ui::App::new(ports, config, config_path)
}
}
StartMode::View(path) => ui::App::viewer(
config,
path,
loaded_plot.expect("viewer data was loaded for view mode"),
),
StartMode::Help => unreachable!("help returned before configuration loading"),
}; };
let _session = TerminalSession; let _session = TerminalSession;
let terminal = ratatui::try_init()?; let terminal = ratatui::try_init()?;
ui::App::new(ports, config, config_path).run(terminal)?; app.run(terminal)?;
Ok(()) Ok(())
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn command_line_selects_acquisition_help_and_csv_viewer() {
assert_eq!(parse_start_mode([]).unwrap(), StartMode::Acquire);
assert_eq!(
parse_start_mode([OsString::from("--live")]).unwrap(),
StartMode::Live
);
assert_eq!(
parse_start_mode([OsString::from("--help")]).unwrap(),
StartMode::Help
);
assert_eq!(
parse_start_mode([OsString::from("scan.csv")]).unwrap(),
StartMode::View(PathBuf::from("scan.csv"))
);
assert_eq!(
parse_start_mode([OsString::from("--view"), OsString::from("scan.csv")]).unwrap(),
StartMode::View(PathBuf::from("scan.csv"))
);
assert!(parse_start_mode([OsString::from("--unknown")]).is_err());
}
}

View File

@ -1,18 +1,23 @@
//! Serial worker adapter and shared progress state for the terminal application. //! Serial worker adapter and shared progress state for the terminal application.
//! //!
//! The worker opens the device and exports completed samples. Protocol parsing //! The worker opens the device, retries an unusable identity on one fresh
//! connection, and exports completed samples. Protocol parsing
//! and orchestration stay in the library; no core type knows about UI widgets. //! and orchestration stay in the library; no core type knows about UI widgets.
use crate::error::{AppError, UiError}; use crate::error::{AppError, UiError};
use std::{ use std::{
io::{Read, Write},
path::PathBuf, path::PathBuf,
sync::{Arc, Mutex, MutexGuard}, sync::{Arc, Mutex, MutexGuard},
}; };
use tiny_wb::{ use tiny_wb::{
acquisition::{acquire, ScanEvent}, acquisition::{acquire, acquire_live, AcquisitionError, ScanEvent},
config::Config, config::Config,
connection::open_connection, connection::{open_connection, ConnectionError},
device::DeviceError,
export::save_csv, export::save_csv,
live::{TraceBuffer, TraceMode},
protocol::Sample,
protocol::ScanRequest, protocol::ScanRequest,
transport::Shell, transport::Shell,
}; };
@ -54,6 +59,64 @@ struct Progress {
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub(crate) struct ScanState(Arc<Mutex<Progress>>); pub(crate) struct ScanState(Arc<Mutex<Progress>>);
/// Shared repeated-snapshot state for the live terminal screen.
#[derive(Debug, Clone)]
pub(crate) struct LiveState(Arc<Mutex<LiveProgress>>);
/// One coherent live snapshot and its control flags.
#[derive(Debug)]
struct LiveProgress {
/// Worker lifecycle.
status: ScanStatus,
/// Current operation or save result.
message: String,
/// Verbatim device identity.
info: String,
/// Failure retained for the error screen.
error: Option<String>,
/// Bounded raw history and derived traces.
trace: TraceBuffer,
/// Calculation selected by the terminal.
mode: TraceMode,
/// Monotonic renderer invalidation counter.
generation: u64,
/// Graceful cancellation requested by the terminal.
stop_requested: bool,
/// Visible trace captured for the next worker-side intermediate export.
pending_save: Option<Vec<Sample>>,
/// Save requested before the first complete sweep became available.
save_after_first: bool,
}
/// Renderer-owned copy of one derived live trace.
pub(crate) struct LiveSnapshot {
/// Monotonic state generation.
pub(crate) generation: u64,
/// Selected host-side calculation.
pub(crate) mode: TraceMode,
/// Complete sweeps incorporated in the calculation.
pub(crate) sweeps: u64,
/// Plot-ready `(MHz, dBm)` points.
pub(crate) data: Vec<(f64, f64)>,
}
impl Default for LiveState {
fn default() -> Self {
Self(Arc::new(Mutex::new(LiveProgress {
status: ScanStatus::Ready,
message: String::new(),
info: String::new(),
error: None,
trace: TraceBuffer::default(),
mode: TraceMode::Average4,
generation: 0,
stop_requested: false,
pending_save: None,
save_after_first: false,
})))
}
}
impl ScanState { impl ScanState {
/// Recover telemetry after a poisoned lock rather than panic in error rendering. /// Recover telemetry after a poisoned lock rather than panic in error rendering.
fn lock(&self) -> MutexGuard<'_, Progress> { fn lock(&self) -> MutexGuard<'_, Progress> {
@ -72,6 +135,16 @@ impl ScanState {
} }
} }
/// Clear results and errors before launching another worker.
pub(crate) fn begin(&self) {
let mut progress = self.lock();
*progress = Progress {
status: ScanStatus::Running,
message: "Opening connection".into(),
..Progress::default()
};
}
/// Current completion estimate; 100 means acquisition and export succeeded. /// Current completion estimate; 100 means acquisition and export succeeded.
pub(crate) fn progress(&self) -> usize { pub(crate) fn progress(&self) -> usize {
self.lock().percent self.lock().percent
@ -115,29 +188,222 @@ impl ScanState {
} }
} }
/// Open one port, acquire through the reusable core, then export valid samples. impl LiveState {
/// Recover shared live state after a poisoned worker lock.
fn lock(&self) -> MutexGuard<'_, LiveProgress> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Reset all bounded history and control flags for a new live run.
pub(crate) fn begin(&self) {
let mut state = self.lock();
*state = LiveProgress {
status: ScanStatus::Running,
message: "Opening live connection".into(),
info: String::new(),
error: None,
trace: TraceBuffer::default(),
mode: TraceMode::Average4,
generation: state.generation.saturating_add(1),
stop_requested: false,
pending_save: None,
save_after_first: false,
};
}
/// Adapt core acquisition events without exposing the terminal to the core.
fn report(&self, event: ScanEvent) {
let mut state = self.lock();
match event {
ScanEvent::Message(message) => state.message = message.into(),
ScanEvent::InstrumentInfo(info) => state.info = info,
ScanEvent::Progress(_) => {}
}
}
/// Incorporate one decoded complete sweep.
fn publish(&self, samples: Vec<Sample>) -> Result<(), tiny_wb::live::LiveTraceError> {
let mut state = self.lock();
state.trace.push(samples)?;
state.generation = state.generation.saturating_add(1);
state.message = format!("Live capture — {} sweeps", state.trace.sweeps());
Ok(())
}
/// Return a rendered trace only when samples or the selected mode changed.
pub(crate) fn snapshot_after(&self, generation: u64) -> Option<LiveSnapshot> {
let state = self.lock();
if state.generation == generation {
return None;
}
state.trace.trace(state.mode).map(|samples| LiveSnapshot {
generation: state.generation,
mode: state.mode,
sweeps: state.trace.sweeps(),
data: samples
.into_iter()
.map(|sample| (sample.frequency_mhz, sample.level_dbm))
.collect(),
})
}
/// Copy the selected calculation for worker-side CSV export.
fn samples(&self) -> Option<Vec<Sample>> {
let state = self.lock();
state.trace.trace(state.mode)
}
/// Select a host-side calculation without discarding its retained history.
pub(crate) fn set_mode(&self, mode: TraceMode) {
let mut state = self.lock();
if state.mode != mode {
state.mode = mode;
state.generation = state.generation.saturating_add(1);
}
}
/// Current host-side calculation.
pub(crate) fn mode(&self) -> TraceMode {
self.lock().mode
}
/// Capture the visible trace for worker-side export after the current sweep.
pub(crate) fn request_save(&self) {
let mut state = self.lock();
if let Some(samples) = state.trace.trace(state.mode) {
state.pending_save = Some(samples);
state.message = "Save requested for the visible buffer".into();
} else {
state.save_after_first = true;
state.message = "Save requested; waiting for the first complete sweep".into();
}
}
/// Consume one captured intermediate export, deferring an early request.
fn take_save_request(&self) -> Option<Vec<Sample>> {
let mut state = self.lock();
if let Some(samples) = state.pending_save.take() {
return Some(samples);
}
if state.save_after_first {
if let Some(samples) = state.trace.trace(state.mode) {
state.save_after_first = false;
return Some(samples);
}
}
None
}
/// Request cancellation after the current sweep completes.
pub(crate) fn request_stop(&self) {
let mut state = self.lock();
state.stop_requested = true;
state.message = "Stopping after the current sweep".into();
}
/// Whether the worker should refrain from starting another snapshot.
fn should_stop(&self) -> bool {
self.lock().stop_requested
}
/// Report a successful intermediate export without stopping capture.
fn saved(&self, path: &std::path::Path) {
self.lock().message = format!("Saved {}; live capture continues", path.display());
}
/// Publish final export and recovery completion together.
fn complete(&self, path: Option<&std::path::Path>) {
let mut state = self.lock();
state.status = ScanStatus::Complete;
state.message = path.map_or_else(
|| "Live capture stopped before the first complete sweep".into(),
|path| format!("Saved {} and stopped live capture", path.display()),
);
}
/// Record a worker failure for the terminal error screen.
pub(crate) fn fail(&self, error: impl std::fmt::Display) {
let mut state = self.lock();
state.error = Some(error.to_string());
state.status = ScanStatus::Failed;
}
/// Current live worker lifecycle.
pub(crate) fn status(&self) -> ScanStatus {
self.lock().status
}
/// Current live operation or save result.
pub(crate) fn message(&self) -> String {
self.lock().message.clone()
}
/// Device identification text received by the live worker.
pub(crate) fn info(&self) -> String {
self.lock().info.clone()
}
/// Live worker failure, when present.
pub(crate) fn error(&self) -> Option<String> {
self.lock().error.clone()
}
}
/// Reopen once when complete identity replies remain empty or unrecognized.
///
/// Dropping the entire shell before opening again releases the port and its
/// buffered replies. These errors occur before any acquisition settings change;
/// transport errors and failures after configuration must never replay a scan.
fn with_identity_reconnect<T: Read + Write, R>(
max_response_bytes: usize,
mut open: impl FnMut() -> Result<T, ConnectionError>,
mut operation: impl FnMut(&mut Shell<T>) -> Result<R, AcquisitionError>,
mut on_retry: impl FnMut(),
) -> Result<R, AppError> {
let first = {
let mut shell = Shell::new(open()?, max_response_bytes);
operation(&mut shell)
};
match first {
Err(
error @ (AcquisitionError::MissingIdentity
| AcquisitionError::Device(DeviceError::Unknown)),
) => {
log::warn!("instrument identification failed; reopening connection once: {error}");
on_retry();
let mut shell = Shell::new(open()?, max_response_bytes);
Ok(operation(&mut shell)?)
}
result => Ok(result?),
}
}
/// Acquire with one identity-only reconnect, then export valid samples.
pub(crate) fn run_scan( pub(crate) fn run_scan(
state: ScanState, state: ScanState,
request: ScanRequest, request: ScanRequest,
config: Config, config: Config,
) -> Result<(), AppError> { ) -> Result<(), AppError> {
{ state.begin();
let mut progress = state.lock();
progress.status = ScanStatus::Running;
progress.message = "Opening connection".into();
}
config.validate()?; config.validate()?;
request request
.validate() .validate()
.map_err(tiny_wb::acquisition::AcquisitionError::from)?; .map_err(tiny_wb::acquisition::AcquisitionError::from)?;
let port = open_connection(&config)?; let samples = with_identity_reconnect(
let mut shell = Shell::new(port, config.serial.max_response_bytes); config.serial.max_response_bytes,
let samples = acquire( || open_connection(&config),
&mut shell, |shell| {
&request, acquire(shell, &request, &config.scan, &config.serial, |event| {
&config.scan, state.report(event)
&config.serial, })
|event| state.report(event), },
|| {
state.report(ScanEvent::Message(
"Reconnecting after failed identification",
))
},
)?; )?;
state.report(ScanEvent::Message("Writing CSV")); state.report(ScanEvent::Message("Writing CSV"));
let filename = save_csv(&samples, &config.output)?; let filename = save_csv(&samples, &config.output)?;
@ -151,10 +417,263 @@ pub(crate) fn run_scan(
Ok(()) Ok(())
} }
/// Keep one connection configured while acquiring repeated complete snapshots.
pub(crate) fn run_live(
state: LiveState,
request: ScanRequest,
config: Config,
) -> Result<(), AppError> {
if state.status() == ScanStatus::Ready {
state.begin();
}
config.validate()?;
request
.validate()
.map_err(tiny_wb::acquisition::AcquisitionError::from)?;
with_identity_reconnect(
config.serial.max_response_bytes,
|| open_connection(&config),
|shell| {
acquire_live(
shell,
&request,
&config.scan,
&config.serial,
|| state.should_stop(),
|samples| {
if let Err(error) = state.publish(samples) {
state.fail(error);
state.request_stop();
return;
}
if let Some(samples) = state.take_save_request() {
match save_csv(&samples, &config.output) {
Ok(path) => state.saved(&path),
Err(error) => {
state.fail(error);
state.request_stop();
}
}
}
},
|event| state.report(event),
)
},
|| {
state.report(ScanEvent::Message(
"Reconnecting after failed identification",
))
},
)?;
if let Some(error) = state.error() {
return Err(AppError::Live(error));
}
let saved = match state.samples() {
Some(samples) => Some(save_csv(&samples, &config.output)?),
None => None,
};
state.complete(saved.as_deref());
Ok(())
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::{
cell::{Cell, RefCell},
io::{self, Cursor},
net::TcpListener,
rc::Rc,
thread,
time::{Duration, Instant},
};
use tiny_wb::{
config::Backend,
mock::{serve_connection, MockConfig},
};
struct IdentitySession {
input: Cursor<Vec<u8>>,
commands: Rc<RefCell<Vec<u8>>>,
closed: Rc<Cell<bool>>,
}
impl Read for IdentitySession {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
self.input.read(buffer)
}
}
impl Write for IdentitySession {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.commands.borrow_mut().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Drop for IdentitySession {
fn drop(&mut self) {
self.closed.set(true);
}
}
#[test]
fn single_and_live_scans_reconnect_only_after_unusable_identity() {
for live in [false, true] {
// None also checks that a healthy first connection is never replayed.
for failed_reply in [None, Some(""), Some("stale startup text")] {
let config = Config::from_toml(
"[scan]\nlegacy_pre_scan=false\n[serial]\ncommand_delay_ms=0\nsettle_delay_ms=0",
).unwrap();
let request = ScanRequest {
start_hz: 280_000_000,
stop_hz: 320_000_000,
points: 2,
repeat: 1,
};
let closed = Rc::new(Cell::new(true));
let commands = [
Rc::new(RefCell::new(Vec::new())),
Rc::new(RefCell::new(Vec::new())),
];
let mut opened = 0;
let mut retries = 0;
let mut open = || {
assert!(
closed.replace(false),
"old port must close before reopening"
);
let input = if let Some(reply) = failed_reply.filter(|_| opened == 0) {
// Extra bytes are prefetched into the first shell's buffer.
// They must not leak into the fresh identity exchange.
format!("ch>{reply}ch>{reply}ch>{reply}ch>{reply}ch>leftover stale bytes")
.into_bytes()
} else {
b"ch>tinySA_v1.4-test\r\nch>tinySA\r\nch>repeat zero pause mode sweep scanraw resume\r\nch>ch>ch>128dBm\r\nch>ch>ch>ch>ch>ch>{x\0\x08x\0\x10}ch>ch>".to_vec()
};
let session = IdentitySession {
input: Cursor::new(input),
commands: commands[opened].clone(),
closed: closed.clone(),
};
opened += 1;
Ok(session)
};
let sweeps = Cell::new(0);
let result = with_identity_reconnect(
1024,
&mut open,
|shell| {
if live {
acquire_live(
shell,
&request,
&config.scan,
&config.serial,
|| sweeps.get() == 1,
|samples| {
assert_eq!(samples.len(), 2);
sweeps.set(sweeps.get() + 1);
},
|_| {},
)
.map(|_| ())
} else {
acquire(shell, &request, &config.scan, &config.serial, |_| {})
.map(|samples| assert_eq!(samples.len(), 2))
}
},
|| retries += 1,
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(opened, 1 + usize::from(failed_reply.is_some()));
assert_eq!(retries, usize::from(failed_reply.is_some()));
assert!(closed.get());
if failed_reply.is_some() {
assert_eq!(&*commands[0].borrow(), b"version\rinfo\rversion\rinfo\r");
}
let successful = String::from_utf8(commands[opened - 1].borrow().clone()).unwrap();
assert_eq!(successful.matches("scanraw ").count(), 1);
assert!(successful.ends_with("resume\r"));
}
}
}
#[test]
fn reconnect_is_bounded_and_other_acquisition_errors_are_not_retried() {
for (error, expected_opens) in [
(AcquisitionError::MissingIdentity, 2),
(AcquisitionError::Device(DeviceError::Unknown), 2),
(AcquisitionError::Device(DeviceError::Conflicting), 1),
(
AcquisitionError::Device(DeviceError::ConflictingRevision),
1,
),
(
AcquisitionError::Transport(io::Error::from(io::ErrorKind::TimedOut).into()),
1,
),
(AcquisitionError::MissingZeroReadback { requested: 128 }, 1),
(
AcquisitionError::Protocol(tiny_wb::protocol::ProtocolError::MissingEnd),
1,
),
] {
let mut opened = 0;
let mut error = Some(error);
let result = with_identity_reconnect(
256,
|| {
opened += 1;
Ok(Cursor::new(Vec::<u8>::new()))
},
|_| {
Err::<(), _>(
error
.take()
.unwrap_or(AcquisitionError::Device(DeviceError::Unknown)),
)
},
|| {},
);
assert!(matches!(result, Err(AppError::Acquisition(_))));
assert_eq!(opened, expected_opens);
}
}
#[test]
fn connection_open_errors_are_propagated_without_another_attempt() {
for fail_on in [1, 2] {
let mut opened = 0;
let mut operations = 0;
let result = with_identity_reconnect(
256,
|| {
opened += 1;
if opened == fail_on {
Err(ConnectionError::Tcp(io::ErrorKind::PermissionDenied.into()))
} else {
Ok(Cursor::new(Vec::<u8>::new()))
}
},
|_| {
operations += 1;
Err::<(), _>(AcquisitionError::MissingIdentity)
},
|| {},
);
assert!(matches!(result, Err(AppError::Connection(_))));
assert_eq!(opened, fail_on);
assert_eq!(operations, fail_on - 1);
}
}
#[test] #[test]
fn shared_progress_and_errors_are_visible_across_clones() { fn shared_progress_and_errors_are_visible_across_clones() {
let state = ScanState::default(); let state = ScanState::default();
@ -175,4 +694,135 @@ mod tests {
assert_eq!(state.take_samples().unwrap(), vec![(240.0, -64.0)]); assert_eq!(state.take_samples().unwrap(), vec![(240.0, -64.0)]);
assert!(state.take_samples().is_err()); assert!(state.take_samples().is_err());
} }
#[test]
fn beginning_another_scan_clears_previous_results_and_errors() {
let state = ScanState::default();
state.complete(PathBuf::from("old.csv"), vec![(240.0, -64.0)]);
state.fail("old failure");
state.begin();
assert_eq!(state.status(), ScanStatus::Running);
assert_eq!(state.progress(), 0);
assert_eq!(state.message(), "Opening connection");
assert!(state.info().is_empty());
assert!(state.error().is_none());
assert!(state.take_samples().is_err());
}
#[test]
fn live_state_publishes_modes_and_control_requests_coherently() {
let state = LiveState::default();
state.begin();
state
.publish(vec![Sample {
frequency_mhz: 240.0,
level_dbm: -64.0,
}])
.unwrap();
let snapshot = state.snapshot_after(0).unwrap();
assert_eq!(snapshot.mode, TraceMode::Average4);
assert_eq!(snapshot.sweeps, 1);
assert_eq!(snapshot.data, vec![(240.0, -64.0)]);
assert!(state.snapshot_after(snapshot.generation).is_none());
state.set_mode(TraceMode::MaxHold);
assert_eq!(state.mode(), TraceMode::MaxHold);
assert!(state.snapshot_after(snapshot.generation).is_some());
state.request_save();
state
.publish(vec![Sample {
frequency_mhz: 240.0,
level_dbm: -20.0,
}])
.unwrap();
assert_eq!(state.take_save_request().unwrap()[0].level_dbm, -64.0);
assert!(state.take_save_request().is_none());
state.request_stop();
assert!(state.should_stop());
}
fn mock_tcp_config(output_name: &str) -> (Config, thread::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let mut config = Config::default();
config.connection.backend = Backend::Tcp;
config.connection.tcp_address = listener.local_addr().unwrap().to_string();
config.serial.command_delay_ms = 0;
config.serial.settle_delay_ms = 0;
config.serial.scan_delay_ms = 0;
config.scan.legacy_pre_scan = false;
config.output.directory =
std::env::temp_dir().join(format!("tiny-wb-{output_name}-{}", std::process::id()));
let server = thread::spawn(move || {
let (socket, _) = listener.accept().unwrap();
socket
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
socket
.set_write_timeout(Some(Duration::from_secs(5)))
.unwrap();
serve_connection(socket, MockConfig::default()).unwrap();
});
(config, server)
}
fn mock_request() -> ScanRequest {
ScanRequest {
start_hz: 240_000_000,
stop_hz: 360_000_000,
points: 4,
repeat: 1,
}
}
#[test]
fn scan_worker_acquires_exports_and_publishes_completion() {
let (config, server) = mock_tcp_config("scan-worker");
let output = config.output.directory.clone();
let state = ScanState::default();
run_scan(state.clone(), mock_request(), config).unwrap();
assert_eq!(state.status(), ScanStatus::Complete);
assert_eq!(state.progress(), 100);
assert_eq!(state.take_samples().unwrap().len(), 4);
assert!(state.message().starts_with("Saved "));
server.join().unwrap();
std::fs::remove_dir_all(output).unwrap();
}
#[test]
fn live_worker_honors_deferred_save_and_graceful_stop() {
let (config, server) = mock_tcp_config("live-worker");
let output = config.output.directory.clone();
let state = LiveState::default();
state.begin();
state.report(ScanEvent::InstrumentInfo("mock identity".into()));
assert_eq!(state.info(), "mock identity");
state.request_save();
let controller = state.clone();
let stop = thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(5);
while controller.snapshot_after(0).is_none() {
assert!(
Instant::now() < deadline,
"live worker produced no snapshot"
);
thread::yield_now();
}
controller.request_stop();
});
run_live(state.clone(), mock_request(), config).unwrap();
stop.join().unwrap();
server.join().unwrap();
assert_eq!(state.status(), ScanStatus::Complete);
assert!(state.error().is_none());
assert!(state.message().contains("stopped live capture"));
assert!(std::fs::read_dir(&output).unwrap().count() >= 2);
std::fs::remove_dir_all(output).unwrap();
}
} }

View File

@ -16,12 +16,12 @@ use ratatui::{
use serialport::SerialPortInfo; use serialport::SerialPortInfo;
pub(crate) use state::App; pub(crate) use state::App;
use state::{ use state::{
AppState, BaudRateList, InputDirection, MenuItems, NumericInput, PortList, SelectedConnection, AppState, BaudRateList, InputDirection, MenuItems, NumericInput, Plot, PortList,
SelectedScan, SelectedConnection, SelectedScan,
}; };
use std::{path::PathBuf, thread, time::Duration}; use std::{path::PathBuf, thread, time::Duration};
use strum::EnumCount; use strum::EnumCount;
use tiny_wb::{config::Config, protocol::ScanRequest}; use tiny_wb::{config::Config, live::TraceMode, protocol::ScanRequest};
impl App { impl App {
/// Construct UI state from already validated settings; no file I/O here. /// Construct UI state from already validated settings; no file I/O here.
@ -37,13 +37,13 @@ impl App {
config.start_frequency, config.start_frequency,
config.scan.frequency_step_mhz, config.scan.frequency_step_mhz,
0, 0,
960, 5_400,
), ),
stop_frequency: NumericInput::new( stop_frequency: NumericInput::new(
config.stop_frequency, config.stop_frequency,
config.scan.frequency_step_mhz, config.scan.frequency_step_mhz,
10, 10,
960, 5_400,
), ),
points: NumericInput::new( points: NumericInput::new(
config.points, config.points,
@ -53,12 +53,35 @@ impl App {
), ),
repeat: NumericInput::new(config.repeat, 1, 1, config.scan.max_repeat), repeat: NumericInput::new(config.repeat, 1, 1, config.scan.max_repeat),
scan_state: ScanState::default(), scan_state: ScanState::default(),
return_data: Vec::new(), live_state: scan::LiveState::default(),
live_enabled: false,
live_generation: 0,
live_exit_requested: false,
show_peak_info: false,
plot: None,
last_scan: None,
can_acquire: true,
config, config,
config_path, config_path,
} }
} }
/// Construct an acquisition UI whose confirmed settings launch live mode.
pub(crate) fn live(info: Vec<SerialPortInfo>, config: Config, config_path: PathBuf) -> Self {
let mut app = Self::new(info, config, config_path);
app.live_enabled = true;
app
}
/// Construct the renderer directly from an already parsed CSV plot.
pub(crate) fn viewer(config: Config, source: PathBuf, data: Vec<(f64, f64)>) -> Self {
let mut app = Self::new(Vec::new(), config, PathBuf::new());
app.flow_state = AppState::Complete;
app.plot = Some(Plot::new(source.display().to_string(), data));
app.can_acquire = false;
app
}
/// Drive events and rendering; worker state is reconciled before each frame. /// Drive events and rendering; worker state is reconciled before each frame.
pub(crate) fn run( pub(crate) fn run(
&mut self, &mut self,
@ -70,6 +93,7 @@ impl App {
self.scan_state.fail(error); self.scan_state.fail(error);
self.flow_state = AppState::Error; self.flow_state = AppState::Error;
} }
self.refresh_live();
let mut draw_error = None; let mut draw_error = None;
terminal.draw(|frame| { terminal.draw(|frame| {
draw_error = self.draw(frame).err(); draw_error = self.draw(frame).err();
@ -77,6 +101,9 @@ impl App {
if let Some(error) = draw_error { if let Some(error) = draw_error {
return Err(error.into()); return Err(error.into());
} }
if self.should_quit {
break;
}
let timeout = Duration::from_millis(self.config.ui.poll_interval_ms); let timeout = Duration::from_millis(self.config.ui.poll_interval_ms);
if event::poll(timeout)? { if event::poll(timeout)? {
if let Event::Key(key) = event::read()? { if let Event::Key(key) = event::read()? {
@ -85,9 +112,6 @@ impl App {
self.flow_state = AppState::Error; self.flow_state = AppState::Error;
}; };
}; };
if self.should_quit {
break;
}
} }
} }
Ok(()) Ok(())
@ -139,6 +163,15 @@ impl App {
if key.kind != KeyEventKind::Press { if key.kind != KeyEventKind::Press {
return Ok(()); return Ok(());
} }
if matches!(self.flow_state, AppState::Complete) {
return self.handle_plot_key(key.code);
}
if matches!(self.flow_state, AppState::Live) {
return self.handle_live_key(key.code);
}
if self.handle_numeric_editor_key(key.code) {
return Ok(());
}
match key.code { match key.code {
KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down), KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down),
@ -154,6 +187,113 @@ impl App {
Ok(()) Ok(())
} }
/// Apply live processing, save and graceful-stop controls.
fn handle_live_key(&mut self, code: KeyCode) -> Result<(), UiError> {
match code {
KeyCode::Char('q') | KeyCode::Esc | KeyCode::Enter => {
self.live_exit_requested = true;
self.live_state.request_stop();
}
KeyCode::Char('s') => self.live_state.request_save(),
KeyCode::Char(key) => {
if let Some(mode) = TraceMode::from_key(key) {
self.live_state.set_mode(mode);
} else if !self.apply_plot_navigation(&code) && key == 'm' {
self.show_peak_info = !self.show_peak_info;
}
}
_ => {
self.apply_plot_navigation(&code);
}
}
Ok(())
}
/// Give an active direct-entry editor exclusive use of keys and start one on a digit.
fn handle_numeric_editor_key(&mut self, code: KeyCode) -> bool {
let input = match self.flow_state {
AppState::SelectingScan(SelectedScan::StartFreq) => &mut self.start_frequency,
AppState::SelectingScan(SelectedScan::FinalFreq) => &mut self.stop_frequency,
AppState::SelectingScan(SelectedScan::Points) => &mut self.points,
_ => return false,
};
if input.is_editing() {
match code {
KeyCode::Char(digit) if digit.is_ascii_digit() => input.push_digit(digit),
KeyCode::Backspace => input.backspace(),
KeyCode::Enter => {
input.commit_edit();
}
KeyCode::Esc => input.cancel_edit(),
_ => {}
}
true
} else {
match code {
KeyCode::Char(digit) if digit.is_ascii_digit() => {
input.push_digit(digit);
true
}
_ => false,
}
}
}
/// Apply configured navigation keys on the plot screen.
fn handle_plot_key(&mut self, code: KeyCode) -> Result<(), UiError> {
match code {
KeyCode::Char('q') | KeyCode::Esc | KeyCode::Enter => {
self.should_quit = true;
return Ok(());
}
KeyCode::Char('r') if self.can_acquire => {
self.repeat_last_scan()?;
return Ok(());
}
KeyCode::Char('n') if self.can_acquire => {
self.plot = None;
self.flow_state = AppState::SelectingScan(SelectedScan::default());
return Ok(());
}
_ => {}
}
if !self.apply_plot_navigation(&code) && code == KeyCode::Char('m') {
self.show_peak_info = !self.show_peak_info;
}
Ok(())
}
/// Apply configured zoom, pan, or reset navigation to the current plot.
fn apply_plot_navigation(&mut self, code: &KeyCode) -> bool {
let bindings = &self.config.ui.bindings;
let action = if binding_matches(code, &bindings.zoom_in) {
Some(PlotAction::ZoomIn)
} else if binding_matches(code, &bindings.zoom_out) {
Some(PlotAction::ZoomOut)
} else if binding_matches(code, &bindings.pan_left) {
Some(PlotAction::PanLeft)
} else if binding_matches(code, &bindings.pan_right) {
Some(PlotAction::PanRight)
} else if binding_matches(code, &bindings.reset_view) {
Some(PlotAction::Reset)
} else {
None
};
let Some(action) = action else {
return false;
};
if let Some(plot) = self.plot.as_mut() {
match action {
PlotAction::ZoomIn => plot.viewport.zoom_in(),
PlotAction::ZoomOut => plot.viewport.zoom_out(),
PlotAction::PanLeft => plot.viewport.pan(InputDirection::Left),
PlotAction::PanRight => plot.viewport.pan(InputDirection::Right),
PlotAction::Reset => plot.viewport.reset(),
}
}
true
}
/// Apply vertical input to the selected field. /// Apply vertical input to the selected field.
fn change_cursor_position(&mut self, direction: InputDirection) { fn change_cursor_position(&mut self, direction: InputDirection) {
match self.flow_state { match self.flow_state {
@ -169,6 +309,7 @@ impl App {
}, },
AppState::Complete => (), AppState::Complete => (),
AppState::Scanning => (), AppState::Scanning => (),
AppState::Live => (),
AppState::Error => (), AppState::Error => (),
} }
} }
@ -208,6 +349,7 @@ impl App {
} }
AppState::Complete => None, AppState::Complete => None,
AppState::Scanning => None, AppState::Scanning => None,
AppState::Live => None,
AppState::Error => None, AppState::Error => None,
} { } {
self.flow_state = s; self.flow_state = s;
@ -225,43 +367,87 @@ impl App {
self.flow_state = AppState::SelectingScan(SelectedScan::default()); self.flow_state = AppState::SelectingScan(SelectedScan::default());
} }
AppState::SelectingScan(_) => { AppState::SelectingScan(_) => {
let config = self.selected_config()?; self.start_selected_scan()?;
let request = ScanRequest {
start_hz: config.start_frequency as u64 * 1_000_000,
stop_hz: config.stop_frequency as u64 * 1_000_000,
points: config.points,
repeat: config.repeat,
};
request
.validate()
.map_err(tiny_wb::acquisition::AcquisitionError::from)
.map_err(AppError::from)?;
config.save(&self.config_path).map_err(AppError::from)?;
self.flow_state = AppState::Scanning;
self.init_progress()?;
let connection = self.scan_state.clone();
thread::spawn(move || {
if let Err(error) = scan::run_scan(connection.clone(), request, config) {
connection.fail(error);
}
});
} }
AppState::Complete => { AppState::Complete => {
self.should_quit = true; self.should_quit = true;
} }
AppState::Scanning => {} AppState::Scanning => {}
AppState::Live => {}
AppState::Error => { AppState::Error => {
self.should_quit = true; self.should_quit = true;
} }
} }
Ok(()) Ok(())
} }
/// Validate and persist the edited fields, then launch their scan.
fn start_selected_scan(&mut self) -> Result<(), UiError> {
let config = self.selected_config()?;
let request = ScanRequest {
start_hz: config.start_frequency as u64 * 1_000_000,
stop_hz: config.stop_frequency as u64 * 1_000_000,
points: config.points,
repeat: config.repeat,
};
request
.validate()
.map_err(tiny_wb::acquisition::AcquisitionError::from)
.map_err(AppError::from)?;
config.save(&self.config_path).map_err(AppError::from)?;
if self.live_enabled {
self.launch_live(request, config)
} else {
self.launch_scan(request, config)
}
}
/// Relaunch the exact request and settings used by the previous scan.
fn repeat_last_scan(&mut self) -> Result<(), UiError> {
let Some((request, config)) = self.last_scan.clone() else {
return Ok(());
};
self.launch_scan(request, config)
}
/// Reset progress synchronously and start one acquisition worker.
fn launch_scan(&mut self, request: ScanRequest, config: Config) -> Result<(), UiError> {
self.init_progress()?;
self.scan_state.begin();
self.flow_state = AppState::Scanning;
self.plot = None;
self.last_scan = Some((request, config.clone()));
let connection = self.scan_state.clone();
thread::spawn(move || {
if let Err(error) = scan::run_scan(connection.clone(), request, config) {
connection.fail(error);
}
});
Ok(())
}
/// Reset live history and start one persistent repeated-snapshot worker.
fn launch_live(&mut self, request: ScanRequest, config: Config) -> Result<(), UiError> {
self.live_state.begin();
self.live_generation = 0;
self.live_exit_requested = false;
self.flow_state = AppState::Live;
self.plot = None;
let live = self.live_state.clone();
thread::spawn(move || {
if let Err(error) = scan::run_live(live.clone(), request, config) {
live.fail(error);
}
});
Ok(())
}
/// Transfer completed samples once and keep rendering free of transitions. /// Transfer completed samples once and keep rendering free of transitions.
fn refresh_scan(&mut self) -> Result<(), UiError> { fn refresh_scan(&mut self) -> Result<(), UiError> {
if matches!(self.flow_state, AppState::Scanning) { if matches!(self.flow_state, AppState::Scanning) {
match self.scan_state.status() { match self.scan_state.status() {
ScanStatus::Complete => { ScanStatus::Complete => {
self.return_data = self.scan_state.take_samples()?; let data = self.scan_state.take_samples()?;
self.plot = Some(Plot::new(self.scan_state.message(), data));
self.flow_state = AppState::Complete; self.flow_state = AppState::Complete;
} }
ScanStatus::Failed => self.flow_state = AppState::Error, ScanStatus::Failed => self.flow_state = AppState::Error,
@ -270,6 +456,63 @@ impl App {
} }
Ok(()) Ok(())
} }
/// Copy at most one newly completed live trace into renderer-owned storage.
fn refresh_live(&mut self) {
if !matches!(self.flow_state, AppState::Live) {
return;
}
if let Some(snapshot) = self.live_state.snapshot_after(self.live_generation) {
self.live_generation = snapshot.generation;
let label = format!("Live {} — {} sweeps", snapshot.mode, snapshot.sweeps);
if let Some(plot) = self.plot.as_mut() {
plot.replace_data(label, snapshot.data);
} else {
self.plot = Some(Plot::new(label, snapshot.data));
}
}
match self.live_state.status() {
ScanStatus::Failed => {
self.scan_state.fail(
self.live_state
.error()
.unwrap_or_else(|| "live capture failed".into()),
);
self.flow_state = AppState::Error;
}
ScanStatus::Complete if self.live_exit_requested => self.should_quit = true,
ScanStatus::Ready | ScanStatus::Running | ScanStatus::Complete => {}
}
}
}
/// Renderer action resolved from configured key names.
#[derive(Clone, Copy)]
enum PlotAction {
/// Decrease the visible span.
ZoomIn,
/// Increase the visible span.
ZoomOut,
/// Shift toward lower frequencies.
PanLeft,
/// Shift toward higher frequencies.
PanRight,
/// Restore the full span.
Reset,
}
/// Match a terminal key against validated character/special-key names.
fn binding_matches(code: &KeyCode, bindings: &[String]) -> bool {
bindings
.iter()
.any(|binding| match (binding.as_str(), code) {
("left", KeyCode::Left) | ("right", KeyCode::Right) | ("home", KeyCode::Home) => true,
(value, KeyCode::Char(character)) => {
let mut chars = value.chars();
chars.next() == Some(*character) && chars.next().is_none()
}
_ => false,
})
} }
#[cfg(test)] #[cfg(test)]
@ -317,6 +560,69 @@ mod tests {
assert!(app.should_quit); assert!(app.should_quit);
} }
#[test]
fn frequency_digits_open_an_editor_before_enter_advances() {
let mut app = app();
app.init_config().unwrap();
app.next_step().unwrap();
for digit in "315".chars() {
app.handle_start_keys(KeyEvent::new(KeyCode::Char(digit), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(app.start_frequency.to_string(), "315_");
app.handle_start_keys(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE))
.unwrap();
assert!(matches!(
app.flow_state,
AppState::SelectingScan(SelectedScan::StartFreq)
));
app.handle_start_keys(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.start_frequency.value(), 315);
assert!(matches!(
app.flow_state,
AppState::SelectingScan(SelectedScan::StartFreq)
));
app.handle_start_keys(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert!(matches!(
app.flow_state,
AppState::SelectingScan(SelectedScan::FinalFreq)
));
app.handle_start_keys(KeyEvent::new(KeyCode::Char('9'), KeyModifiers::NONE))
.unwrap();
app.handle_start_keys(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.stop_frequency.value(), 800);
assert!(!app.should_quit);
}
#[test]
fn point_digits_use_the_same_bounded_editor() {
let mut app = app();
app.init_config().unwrap();
app.next_step().unwrap();
app.next_menu(InputDirection::Right).unwrap();
app.next_menu(InputDirection::Right).unwrap();
assert!(matches!(
app.flow_state,
AppState::SelectingScan(SelectedScan::Points)
));
for digit in "2048".chars() {
app.handle_start_keys(KeyEvent::new(KeyCode::Char(digit), KeyModifiers::NONE))
.unwrap();
}
assert_eq!(app.points.to_string(), "2048_");
app.handle_start_keys(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.points.value(), 2048);
assert!(matches!(
app.flow_state,
AppState::SelectingScan(SelectedScan::Points)
));
}
#[test] #[test]
fn missing_ports_and_invalid_spans_fail_before_saving_or_scanning() { fn missing_ports_and_invalid_spans_fail_before_saving_or_scanning() {
let mut app = App::new( let mut app = App::new(
@ -327,7 +633,7 @@ mod tests {
assert!(matches!(app.next_step(), Err(UiError::NoPortSelected))); assert!(matches!(app.next_step(), Err(UiError::NoPortSelected)));
let mut app = self::app(); let mut app = self::app();
app.next_step().unwrap(); app.next_step().unwrap();
app.start_frequency = NumericInput::new(900, 10, 0, 960); app.start_frequency = NumericInput::new(900, 10, 0, 5_400);
assert!(app.next_step().is_err()); assert!(app.next_step().is_err());
assert_eq!(app.scan_state.status(), ScanStatus::Ready); assert_eq!(app.scan_state.status(), ScanStatus::Ready);
} }
@ -340,7 +646,7 @@ mod tests {
.complete(PathBuf::from("scan.csv"), vec![(240.0, -64.0)]); .complete(PathBuf::from("scan.csv"), vec![(240.0, -64.0)]);
app.refresh_scan().unwrap(); app.refresh_scan().unwrap();
assert!(matches!(app.flow_state, AppState::Complete)); assert!(matches!(app.flow_state, AppState::Complete));
assert_eq!(app.return_data, vec![(240.0, -64.0)]); assert_eq!(app.plot.as_ref().unwrap().data, vec![(240.0, -64.0)]);
app.refresh_scan().unwrap(); app.refresh_scan().unwrap();
app.flow_state = AppState::Scanning; app.flow_state = AppState::Scanning;
app.scan_state.fail("disconnected"); app.scan_state.fail("disconnected");
@ -348,12 +654,96 @@ mod tests {
assert!(matches!(app.flow_state, AppState::Error)); assert!(matches!(app.flow_state, AppState::Error));
} }
#[test]
fn configured_plot_keys_zoom_pan_and_reset() {
let mut config = Config::default();
config.ui.bindings.zoom_in = vec!["z".into()];
let mut app = App::viewer(
config,
PathBuf::from("scan.csv"),
vec![
(100.0, -1.0),
(125.0, -1.5),
(150.0, -2.0),
(175.0, -1.5),
(200.0, -1.0),
],
);
app.handle_start_keys(KeyEvent::new(KeyCode::Char('+'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [100.0, 200.0]);
app.handle_start_keys(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [125.0, 175.0]);
app.handle_start_keys(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [137.5, 187.5]);
app.handle_start_keys(KeyEvent::new(KeyCode::Home, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [100.0, 200.0]);
}
#[test]
fn new_scan_key_returns_to_prefilled_parameters_only_for_acquisition() {
let mut app = app();
app.flow_state = AppState::Complete;
app.plot = Some(Plot::new("scan.csv", vec![(240.0, -64.0)]));
app.handle_start_keys(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE))
.unwrap();
assert!(matches!(
app.flow_state,
AppState::SelectingScan(SelectedScan::StartFreq)
));
assert_eq!(app.start_frequency.value(), 240);
assert!(app.plot.is_none());
let mut viewer = App::viewer(
Config::default(),
PathBuf::from("scan.csv"),
vec![(240.0, -64.0)],
);
viewer
.handle_start_keys(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE))
.unwrap();
assert!(matches!(viewer.flow_state, AppState::Complete));
}
#[test]
fn live_keys_switch_mode_and_request_a_graceful_exit() {
let mut app = app();
app.flow_state = AppState::Live;
app.plot = Some(Plot::new(
"live",
vec![(100.0, -30.0), (150.0, -10.0), (200.0, -20.0)],
));
app.live_state.begin();
app.handle_start_keys(KeyEvent::new(KeyCode::Char('+'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.plot.as_ref().unwrap().viewport.bounds(), [125.0, 175.0]);
app.handle_start_keys(KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE))
.unwrap();
assert!(app.show_peak_info);
app.handle_start_keys(KeyEvent::new(KeyCode::Char('6'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.live_state.mode(), TraceMode::MinDecay);
app.handle_start_keys(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE))
.unwrap();
assert!(app.live_exit_requested);
assert!(
!app.should_quit,
"worker recovery and final save must finish first"
);
assert_eq!(app.live_state.message(), "Stopping after the current sweep");
}
#[test] #[test]
fn every_screen_renders_without_a_physical_terminal() { fn every_screen_renders_without_a_physical_terminal() {
for (width, height) in [(120, 40), (40, 10), (1, 1)] { for (width, height) in [(120, 40), (40, 10), (1, 1)] {
let mut app = app(); let mut app = app();
app.init_config().unwrap(); app.init_config().unwrap();
app.init_progress().unwrap(); app.init_progress().unwrap();
app.plot = Some(Plot::new("test.csv", vec![(240.0, -64.0)]));
app.show_peak_info = true;
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
for screen in [ for screen in [
AppState::default(), AppState::default(),
@ -362,6 +752,7 @@ mod tests {
AppState::SelectingScan(SelectedScan::Points), AppState::SelectingScan(SelectedScan::Points),
AppState::SelectingScan(SelectedScan::Repeat), AppState::SelectingScan(SelectedScan::Repeat),
AppState::Scanning, AppState::Scanning,
AppState::Live,
AppState::Complete, AppState::Complete,
AppState::Error, AppState::Error,
] { ] {
@ -370,4 +761,26 @@ mod tests {
} }
} }
} }
#[test]
fn peak_toggle_renders_the_strongest_visible_sample() {
let mut app = App::viewer(
Config::default(),
PathBuf::from("scan.csv"),
vec![(100.0, -30.0), (150.0, -10.0), (200.0, -20.0)],
);
app.show_peak_info = true;
let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap();
terminal.draw(|frame| app.draw(frame).unwrap()).unwrap();
let rendered: String = terminal
.backend()
.buffer()
.content
.iter()
.map(|cell| cell.symbol())
.collect();
assert!(rendered.contains("Visible peak"));
assert!(rendered.contains("-10.00 dBm"));
assert!(rendered.contains("150.00 MHz"));
}
} }

View File

@ -11,9 +11,9 @@ use strum::FromRepr;
use crate::{ use crate::{
error::{AppError, UiError}, error::{AppError, UiError},
scan::ScanState, scan::{LiveState, ScanState},
}; };
use tiny_wb::config::Config; use tiny_wb::{config::Config, protocol::ScanRequest};
/// Color of a selected border /// Color of a selected border
pub(crate) const SELECTED_COLOR: Color = Color::White; pub(crate) const SELECTED_COLOR: Color = Color::White;
@ -45,12 +45,163 @@ pub(crate) struct App {
pub(crate) repeat: NumericInput, pub(crate) repeat: NumericInput,
/// Shared acquisition telemetry; request settings are passed separately. /// Shared acquisition telemetry; request settings are passed separately.
pub(crate) scan_state: ScanState, pub(crate) scan_state: ScanState,
/// Shared repeated-snapshot state used only by `--live` sessions.
pub(crate) live_state: LiveState,
/// Whether scans launched from the settings screen should run continuously.
pub(crate) live_enabled: bool,
/// Last live generation copied into the plot.
pub(crate) live_generation: u64,
/// Whether the UI should exit after live recovery and final export.
pub(crate) live_exit_requested: bool,
/// Whether the plot overlays the strongest sample in the visible frequency range.
pub(crate) show_peak_info: bool,
/// Validated settings retained when the selection is saved. /// Validated settings retained when the selection is saved.
pub(crate) config: Config, pub(crate) config: Config,
/// Explicit settings path selected at startup. /// Explicit settings path selected at startup.
pub(crate) config_path: PathBuf, pub(crate) config_path: PathBuf,
/// Completed samples owned by the UI, in MHz and dBm. /// Last launched request and settings, retained for one-key repetition.
pub(crate) return_data: Vec<(f64, f64)>, pub(crate) last_scan: Option<(ScanRequest, Config)>,
/// Whether this session may acquire, as opposed to viewing a standalone CSV.
pub(crate) can_acquire: bool,
/// Plot currently shown by the renderer; a collection boundary for future tabs.
pub(crate) plot: Option<Plot>,
}
/// One named plot and its independently navigable frequency viewport.
#[derive(Debug)]
pub(crate) struct Plot {
/// User-facing source name.
pub(crate) label: String,
/// Samples in MHz and dBm, ordered by frequency.
pub(crate) data: Vec<(f64, f64)>,
/// Current and complete horizontal bounds.
pub(crate) viewport: FrequencyViewport,
}
impl Plot {
/// Construct a plot whose initial viewport contains all samples.
pub(crate) fn new(label: impl Into<String>, data: Vec<(f64, f64)>) -> Self {
let viewport = FrequencyViewport::from_samples(&data);
Self {
label: label.into(),
data,
viewport,
}
}
/// Replace samples without resetting a compatible live viewport.
pub(crate) fn replace_data(&mut self, label: impl Into<String>, data: Vec<(f64, f64)>) {
let replacement = FrequencyViewport::from_samples(&data);
if self.viewport.full_min != replacement.full_min
|| self.viewport.full_max != replacement.full_max
{
self.viewport = replacement;
}
self.label = label.into();
self.data = data;
}
/// Return the strongest sample inside the current horizontal viewport.
pub(crate) fn visible_peak(&self) -> Option<(f64, f64)> {
let [minimum, maximum] = self.viewport.bounds();
self.data
.iter()
.copied()
.filter(|(frequency, _)| (minimum..=maximum).contains(frequency))
.reduce(|peak, sample| if sample.1 > peak.1 { sample } else { peak })
}
}
/// Horizontal chart bounds with zoom and pan clamped to the source data.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct FrequencyViewport {
/// Complete lower bound, in MHz.
full_min: f64,
/// Complete upper bound, in MHz.
full_max: f64,
/// Visible lower bound, in MHz.
visible_min: f64,
/// Visible upper bound, in MHz.
visible_max: f64,
/// Smallest permitted visible span.
min_span: f64,
}
impl FrequencyViewport {
/// Derive safe increasing chart bounds from an ordered sample set.
fn from_samples(samples: &[(f64, f64)]) -> Self {
let first = samples.first().map_or(0.0, |sample| sample.0);
let last = samples.last().map_or(first, |sample| sample.0);
let (full_min, full_max) = if first < last {
(first, last)
} else {
let padding = (first.abs() * 1e-6).max(0.001);
(first - padding, first + padding)
};
let span = full_max - full_min;
let sample_spacing = samples
.windows(2)
.filter_map(|pair| {
let spacing = pair[1].0 - pair[0].0;
(spacing > 0.0).then_some(spacing)
})
.min_by(f64::total_cmp);
Self {
full_min,
full_max,
visible_min: full_min,
visible_max: full_max,
min_span: sample_spacing.unwrap_or(span).min(span).max(f64::EPSILON),
}
}
/// Current `[minimum, maximum]` bounds in MHz.
pub(crate) fn bounds(self) -> [f64; 2] {
[self.visible_min, self.visible_max]
}
/// Halve the visible span around its center, down to the resolution floor.
pub(crate) fn zoom_in(&mut self) {
self.set_span(((self.visible_max - self.visible_min) / 2.0).max(self.min_span));
}
/// Double the visible span around its center, up to the complete range.
pub(crate) fn zoom_out(&mut self) {
self.set_span(((self.visible_max - self.visible_min) * 2.0).min(self.full_span()));
}
/// Move by one quarter of the visible span and clamp at the data edge.
pub(crate) fn pan(&mut self, direction: InputDirection) {
let span = self.visible_max - self.visible_min;
let shift = match direction {
InputDirection::Left => -span / 4.0,
InputDirection::Right => span / 4.0,
_ => return,
};
let new_min = (self.visible_min + shift).clamp(self.full_min, self.full_max - span);
self.visible_min = new_min;
self.visible_max = new_min + span;
}
/// Restore the complete source range.
pub(crate) fn reset(&mut self) {
self.visible_min = self.full_min;
self.visible_max = self.full_max;
}
/// Update the visible span while retaining the current center when possible.
fn set_span(&mut self, span: f64) {
let span = span.clamp(self.min_span, self.full_span());
let center = (self.visible_min + self.visible_max) / 2.0;
let new_min = (center - span / 2.0).clamp(self.full_min, self.full_max - span);
self.visible_min = new_min;
self.visible_max = new_min + span;
}
/// Width of the complete frequency range.
fn full_span(self) -> f64 {
self.full_max - self.full_min
}
} }
#[derive(Debug)] #[derive(Debug)]
@ -64,6 +215,10 @@ pub(crate) struct NumericInput {
min_clamp: usize, min_clamp: usize,
/// Inclusive upper bound. /// Inclusive upper bound.
max_clamp: usize, max_clamp: usize,
/// Digits being entered directly; `None` retains step-based behavior.
edit_buffer: Option<String>,
/// Whether the current buffer failed bounds or integer validation.
invalid_edit: bool,
} }
impl NumericInput { impl NumericInput {
@ -93,6 +248,8 @@ impl NumericInput {
increment, increment,
max_clamp, max_clamp,
min_clamp, min_clamp,
edit_buffer: None,
invalid_edit: false,
} }
} }
@ -100,6 +257,57 @@ impl NumericInput {
pub(crate) fn value(&self) -> usize { pub(crate) fn value(&self) -> usize {
self.value self.value
} }
/// Start or extend direct decimal entry without changing the committed value.
pub(crate) fn push_digit(&mut self, digit: char) {
if !digit.is_ascii_digit() {
return;
}
let buffer = self.edit_buffer.get_or_insert_with(String::new);
if buffer.len() < 20 {
buffer.push(digit);
}
self.invalid_edit = false;
}
/// Remove the last typed digit while retaining edit mode.
pub(crate) fn backspace(&mut self) {
if let Some(buffer) = self.edit_buffer.as_mut() {
buffer.pop();
self.invalid_edit = false;
}
}
/// Commit direct entry when it is an integer inside the field's bounds.
pub(crate) fn commit_edit(&mut self) -> bool {
let parsed = self
.edit_buffer
.as_deref()
.filter(|buffer| !buffer.is_empty())
.and_then(|buffer| buffer.parse::<usize>().ok());
if let Some(value) =
parsed.filter(|value| (self.min_clamp..=self.max_clamp).contains(value))
{
self.value = value;
self.edit_buffer = None;
self.invalid_edit = false;
true
} else {
self.invalid_edit = true;
false
}
}
/// Abandon direct entry and restore the previously committed value.
pub(crate) fn cancel_edit(&mut self) {
self.edit_buffer = None;
self.invalid_edit = false;
}
/// Whether keystrokes currently belong to the inline editor.
pub(crate) fn is_editing(&self) -> bool {
self.edit_buffer.is_some()
}
} }
#[derive(Debug)] #[derive(Debug)]
@ -113,6 +321,8 @@ pub(crate) enum AppState {
Complete, Complete,
/// Acquisition and export progress. /// Acquisition and export progress.
Scanning, Scanning,
/// Repeated complete snapshots displayed while acquisition continues.
Live,
/// Error window /// Error window
Error, Error,
} }
@ -293,7 +503,21 @@ pub(crate) enum InputDirection {
impl std::fmt::Display for NumericInput { impl std::fmt::Display for NumericInput {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.value.fmt(formatter) if let Some(buffer) = &self.edit_buffer {
if self.invalid_edit {
write!(
formatter,
"{}_ (enter {}–{})",
buffer, self.min_clamp, self.max_clamp
)
} else if buffer.is_empty() {
formatter.write_str("_")
} else {
write!(formatter, "{buffer}_")
}
} else {
self.value.fmt(formatter)
}
} }
} }
@ -317,6 +541,93 @@ mod tests {
assert_eq!(field.value(), 0); assert_eq!(field.value(), 0);
} }
#[test]
fn numeric_input_edits_commits_and_cancels_typed_values() {
let mut field = NumericInput::new(240, 10, 0, 5_400);
for digit in "1234".chars() {
field.push_digit(digit);
}
assert!(field.is_editing());
assert_eq!(field.to_string(), "1234_");
assert!(field.commit_edit());
assert_eq!(field.value(), 1234);
for digit in "9999".chars() {
field.push_digit(digit);
}
assert!(!field.commit_edit());
assert_eq!(field.value(), 1234);
assert!(field.to_string().contains("enter 0–5400"));
field.backspace();
field.cancel_edit();
assert_eq!(field.to_string(), "1234");
}
#[test]
fn viewport_zooms_pans_clamps_and_resets() {
let mut viewport = FrequencyViewport::from_samples(&[
(100.0, -1.0),
(125.0, -1.5),
(150.0, -2.0),
(175.0, -1.5),
(200.0, -1.0),
]);
assert_eq!(viewport.bounds(), [100.0, 200.0]);
viewport.zoom_in();
assert_eq!(viewport.bounds(), [125.0, 175.0]);
viewport.pan(InputDirection::Right);
assert_eq!(viewport.bounds(), [137.5, 187.5]);
for _ in 0..20 {
viewport.pan(InputDirection::Right);
}
assert_eq!(viewport.bounds(), [150.0, 200.0]);
viewport.zoom_out();
assert_eq!(viewport.bounds(), [100.0, 200.0]);
viewport.reset();
assert_eq!(viewport.bounds(), [100.0, 200.0]);
}
#[test]
fn maximum_zoom_uses_the_finest_positive_sample_spacing() {
let mut viewport = FrequencyViewport::from_samples(&[
(100.0, -1.0),
(100.0, -2.0),
(100.01, -3.0),
(100.02, -4.0),
(200.0, -5.0),
]);
for _ in 0..32 {
viewport.zoom_in();
}
let [minimum, maximum] = viewport.bounds();
assert!(((maximum - minimum) - 0.01).abs() < 1e-12);
}
#[test]
fn viewport_for_one_sample_still_has_increasing_bounds() {
let viewport = FrequencyViewport::from_samples(&[(240.0, -64.0)]);
let [minimum, maximum] = viewport.bounds();
assert!(minimum < 240.0 && maximum > 240.0);
}
#[test]
fn visible_peak_tracks_the_zoomed_and_panned_viewport() {
let mut plot = Plot::new(
"test",
vec![
(100.0, -30.0),
(125.0, -10.0),
(150.0, -20.0),
(200.0, -5.0),
],
);
assert_eq!(plot.visible_peak(), Some((200.0, -5.0)));
plot.viewport.zoom_in();
assert_eq!(plot.visible_peak(), Some((125.0, -10.0)));
plot.viewport.pan(InputDirection::Right);
assert_eq!(plot.visible_peak(), Some((150.0, -20.0)));
}
#[test] #[test]
fn empty_and_stale_port_selections_return_errors() { fn empty_and_stale_port_selections_return_errors() {
let mut list = PortList::from_serial(Vec::new(), &Config::default()); let mut list = PortList::from_serial(Vec::new(), &Config::default());

View File

@ -1,14 +1,14 @@
//! Ratatui rendering; acquisition results arrive through shared scan state. //! Ratatui rendering; acquisition results arrive through shared scan state.
use super::state::{ use super::state::{
App, AppState, SelectedConnection, SelectedScan, SELECTED_COLOR, UNSELECTED_COLOR, App, AppState, Plot, SelectedConnection, SelectedScan, SELECTED_COLOR, UNSELECTED_COLOR,
}; };
use crate::error::UiError; use crate::error::UiError;
use ratatui::{ use ratatui::{
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
style::{Color, Style}, style::{Color, Style},
symbols::Marker, symbols::Marker,
widgets::{Axis, Block, Chart, Dataset, GraphType, List, Paragraph, Wrap}, widgets::{Axis, Block, Chart, Clear, Dataset, GraphType, List, Paragraph, Wrap},
Frame, Frame,
}; };
@ -19,11 +19,85 @@ impl App {
AppState::SelectingConnection(_) => self.draw_config(frame), AppState::SelectingConnection(_) => self.draw_config(frame),
AppState::SelectingScan(_) => self.draw_final_config(frame), AppState::SelectingScan(_) => self.draw_final_config(frame),
AppState::Scanning => self.draw_progress(frame), AppState::Scanning => self.draw_progress(frame),
AppState::Live => self.draw_live(frame),
AppState::Complete => self.draw_end_window(frame), AppState::Complete => self.draw_end_window(frame),
AppState::Error => self.draw_error(frame), AppState::Error => self.draw_error(frame),
} }
} }
/// Render the newest complete live snapshot while the worker continues.
fn draw_live(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> {
let [_, main, _] = Layout::horizontal([
Constraint::Min(2),
Constraint::Percentage(96),
Constraint::Min(2),
])
.areas(frame.area());
let [status_area, graph_area, footer_area] = Layout::vertical([
Constraint::Length(4),
Constraint::Min(4),
Constraint::Length(2),
])
.areas(main);
let status = format!(
"{} — {}\n{}",
self.live_state.mode(),
self.live_state.message(),
self.live_state.info()
);
frame.render_widget(
Paragraph::new(status)
.wrap(Wrap { trim: true })
.block(Block::bordered().title("Live capture")),
status_area,
);
if let Some(plot) = self.plot.as_ref() {
let bounds = plot.viewport.bounds();
let span = bounds[1] - bounds[0];
let midpoint = (bounds[0] + bounds[1]) / 2.0;
let chart = Chart::new(vec![Dataset::default()
.marker(Marker::Dot)
.graph_type(GraphType::Scatter)
.style(Style::new().yellow())
.data(&plot.data)])
.x_axis(
Axis::default()
.title("Frequency (MHz)")
.bounds(bounds)
.labels([
format_frequency(bounds[0], span),
format_frequency(midpoint, span),
format_frequency(bounds[1], span),
]),
)
.y_axis(
Axis::default()
.title("Level (dBm)")
.bounds([self.config.ui.chart_min_dbm, self.config.ui.chart_max_dbm]),
);
frame.render_widget(chart, graph_area);
if self.show_peak_info {
render_peak_info(frame, graph_area, plot);
}
} else {
frame.render_widget(
Paragraph::new("Waiting for the first complete sweep…")
.centered()
.block(Block::bordered()),
graph_area,
);
}
frame.render_widget(
Paragraph::new(
"1–6 trace · zoom +/= / - · pan ←/→ · 0 reset · m peak · s save · q stop+save",
)
.centered()
.wrap(Wrap { trim: true }),
footer_area,
);
Ok(())
}
/// Render scan settings with the focused field highlighted. /// Render scan settings with the focused field highlighted.
fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> { fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> {
let [_, spaced, _] = Layout::horizontal([ let [_, spaced, _] = Layout::horizontal([
@ -113,13 +187,21 @@ impl App {
} }
/// Show keyboard guidance below editable settings. /// Show keyboard guidance below editable settings.
fn render_footer(&self, frame: &mut Frame, area: Rect) { fn render_footer(&self, frame: &mut Frame, area: Rect) {
frame.render_widget( let guidance = match self.flow_state {
Paragraph::new( AppState::SelectingScan(SelectedScan::StartFreq | SelectedScan::FinalFreq)
"Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.", if self.start_frequency.is_editing() || self.stop_frequency.is_editing() =>
) {
.centered(), "Type MHz; Backspace deletes, ↲ applies, and Esc cancels."
area, }
); AppState::SelectingScan(SelectedScan::Points) if self.points.is_editing() => {
"Type the point count; Backspace deletes, ↲ applies, and Esc cancels."
}
AppState::SelectingScan(_) => {
"Use ↓↑ to change, ←→ to select, digits to type MHz/points, and ↲ to continue."
}
_ => "Use ↓↑ to move, ←→ to select, and ↲ to continue.",
};
frame.render_widget(Paragraph::new(guidance).centered(), area);
} }
/// Render the available ports and configured baud choices. /// Render the available ports and configured baud choices.
@ -272,11 +354,15 @@ impl App {
]) ])
.areas(main_s); .areas(main_s);
let plot = self.plot.as_ref().ok_or(UiError::NoReturnData)?;
let bounds = plot.viewport.bounds();
let span = bounds[1] - bounds[0];
let status = Paragraph::new(format!( let status = Paragraph::new(format!(
"The scan of {} points in the range ({}MHz - {}MHz) finished successfully", "{} — {} points — visible {} to {} MHz",
self.points.value(), plot.label,
self.start_frequency.value(), plot.data.len(),
self.stop_frequency.value(), format_frequency(bounds[0], span),
format_frequency(bounds[1], span),
)) ))
.block(Block::bordered().title("Status")) .block(Block::bordered().title("Status"))
.style(SELECTED_COLOR); .style(SELECTED_COLOR);
@ -285,28 +371,20 @@ impl App {
.marker(Marker::Dot) .marker(Marker::Dot)
.graph_type(GraphType::Scatter) .graph_type(GraphType::Scatter)
.style(Style::new().yellow()) .style(Style::new().yellow())
.data(&self.return_data)]; .data(&plot.data)];
let midpoint = (bounds[0] + bounds[1]) / 2.0;
let chart = Chart::new(datasets) let chart = Chart::new(datasets)
.x_axis( .x_axis(
Axis::default() Axis::default()
.bounds([ .title("Frequency (MHz)")
self.start_frequency.value() as f64, .bounds(bounds)
self.stop_frequency.value() as f64,
])
.style(Style::default().fg(Color::Gray)) .style(Style::default().fg(Color::Gray))
.labels([ .labels([
format!("{}MHz", self.start_frequency), format_frequency(bounds[0], span),
format!( format_frequency(midpoint, span),
"{}MHz", format_frequency(bounds[1], span),
self.start_frequency.value()
+ (self
.stop_frequency
.value()
.saturating_sub(self.start_frequency.value()))
/ 2
),
format!("{}MHz", self.stop_frequency),
]), ]),
) )
.y_axis( .y_axis(
@ -323,9 +401,23 @@ impl App {
]), ]),
); );
frame.render_widget(chart, graph_area); frame.render_widget(chart, graph_area);
if self.show_peak_info {
render_peak_info(frame, graph_area, plot);
}
let keys = &self.config.ui.bindings;
let restart = if self.can_acquire {
"; r repeats; n edits a new scan"
} else {
""
};
let footer = Paragraph::new(format!( let footer = Paragraph::new(format!(
"{}, press ↲ or q to exit", "zoom {} / {}; pan {} / {}; reset {}; m peak{}; q exits",
self.scan_state.message(), keys.zoom_in.join("|"),
keys.zoom_out.join("|"),
keys.pan_left.join("|"),
keys.pan_right.join("|"),
keys.reset_view.join("|"),
restart,
)) ))
.centered(); .centered();
frame.render_widget(status, title_area); frame.render_widget(status, title_area);
@ -334,6 +426,42 @@ impl App {
} }
} }
/// Overlay the maximum visible sample without changing the chart's data bounds.
fn render_peak_info(frame: &mut Frame<'_>, graph_area: Rect, plot: &Plot) {
let Some((frequency, level)) = plot.visible_peak() else {
return;
};
let width = graph_area.width.min(26);
let height = graph_area.height.min(4);
if width == 0 || height == 0 {
return;
}
let area = Rect::new(
graph_area.right().saturating_sub(width),
graph_area.y,
width,
height,
);
let span = plot.viewport.bounds()[1] - plot.viewport.bounds()[0];
let text = format!("{level:.2} dBm\n{} MHz", format_frequency(frequency, span));
frame.render_widget(Clear, area);
frame.render_widget(
Paragraph::new(text).block(Block::bordered().title("Visible peak")),
area,
);
}
/// Keep axis labels compact while retaining useful precision after zooming.
fn format_frequency(value: f64, visible_span: f64) -> String {
let tick_spacing = visible_span / 2.0;
let precision = if tick_spacing >= 1.0 {
2
} else {
((-tick_spacing.log10()).ceil() as usize).clamp(2, 6)
};
format!("{value:.precision$}")
}
impl App { impl App {
/// Apply the active/inactive style to a cached list widget. /// Apply the active/inactive style to a cached list widget.
pub(crate) fn change_color( pub(crate) fn change_color(
@ -348,6 +476,7 @@ impl App {
) )
} }
} }
impl App { impl App {
/// Update connection selection styling after navigation. /// Update connection selection styling after navigation.
pub(crate) fn update_color(&mut self) -> Result<(), UiError> { pub(crate) fn update_color(&mut self) -> Result<(), UiError> {
@ -384,3 +513,15 @@ impl App {
Ok(()) Ok(())
} }
} }
#[cfg(test)]
mod tests {
use super::format_frequency;
#[test]
fn frequency_labels_gain_precision_as_the_view_narrows() {
assert_eq!(format_frequency(240.123_456, 100.0), "240.12");
assert_eq!(format_frequency(240.123_456, 0.001), "240.1235");
assert_eq!(format_frequency(240.123_456, 0.000_001), "240.123456");
}
}

13
task.md
View File

@ -41,7 +41,7 @@ model-detection entry. Hardware and extended-range gates remain open.
| Basic | Low/high selection, one-shot raw sweep, repeat, configurable zero offset, resume attempt | Hardware qualification, processing/input controls, generator and complete workflows | | Basic | Low/high selection, one-shot raw sweep, repeat, configurable zero offset, resume attempt | Hardware qualification, processing/input controls, generator and complete workflows |
| Ultra | Synthetic profile; experimental physical validator at 240–300 MHz | Model detection, normal/extended range planning, Ultra-specific controls and qualification | | Ultra | Synthetic profile; experimental physical validator at 240–300 MHz | Model detection, normal/extended range planning, Ultra-specific controls and qualification |
| Transport | Buffered mixed text/binary I/O, complete writes, bounded responses, serial/TCP adapters | Overall deadlines, abort, reconnect, typed replies and full recovery | | Transport | Buffered mixed text/binary I/O, complete writes, bounded responses, serial/TCP adapters | Overall deadlines, abort, reconnect, typed replies and full recovery |
| Interface | One scan per TUI launch, plot and CSV | Headless commands, repeat/live operation, capability-aware controls | | Interface | Rescan/settings return, repeated-snapshot live plot, bounded host trace calculations, plot and CSV | Headless commands, native continuous framing, subtraction/reference buffers and capability-aware controls |
| Verification | Regression/mock tests, CI gates, guided hardware validator | Captured real-device fixtures, RF reference measurements and platform matrix | | Verification | Regression/mock tests, CI gates, guided hardware validator | Captured real-device fixtures, RF reference measurements and platform matrix |
- [x] F01–F04: reusable library, injected I/O, bounded mock profiles and loopback tests. - [x] F01–F04: reusable library, injected I/O, bounded mock profiles and loopback tests.
@ -320,8 +320,10 @@ reference measurements verify exported amplitude and visible correction state.
only for advertised forms. Verify frequency/value lengths and record counts. only for advertised forms. Verify frequency/value lengths and record counts.
- [ ] Introduce trace metadata: device/build/profile, requested and actual range, - [ ] Introduce trace metadata: device/build/profile, requested and actual range,
axis policy, offset, RF path, processing, timestamps and completion status. axis policy, offset, RF path, processing, timestamps and completion status.
- [ ] Support repeated snapshots before native continuous frames; both need - [x] Support repeated complete snapshots with bounded sixteen-sweep history,
bounded queues, cancellation, backpressure and explicit dropped-frame counts. frame-boundary cancellation and no partial-frame publication.
- [ ] Add native continuous frames with bounded queues, backpressure, verified
abort/resynchronization and explicit dropped-frame counts.
- [ ] Preserve current two-column CSV compatibility. Add opt-in metadata sidecars - [ ] Preserve current two-column CSV compatibility. Add opt-in metadata sidecars
or a documented versioned format; keep serialization independent of paths. or a documented versioned format; keep serialization independent of paths.
- [ ] Define atomic completion for trace plus metadata and a clearly labeled - [ ] Define atomic completion for trace plus metadata and a clearly labeled
@ -465,8 +467,9 @@ Depends incrementally on P01/P02 and each exposed feature.
- [ ] Display model/build/connection state and derive field limits/choices from - [ ] Display model/build/connection state and derive field limits/choices from
capabilities. Explain unavailable features rather than offering illegal values. capabilities. Explain unavailable features rather than offering illegal values.
- [ ] Add rescan and return-to-settings without restarting, live plots, marker - [x] Add rescan, return-to-settings and a repeated-snapshot live plot without
controls and appropriate analyzer/generator/preset screens. restarting the process.
- [ ] Add marker controls and appropriate analyzer/generator/preset screens.
- [ ] Keep worker events/state updates outside rendering; add cancel, recovery, - [ ] Keep worker events/state updates outside rendering; add cancel, recovery,
trigger-wait and reconnect states without blocking the event loop. trigger-wait and reconnect states without blocking the event loop.
- [ ] Label MHz/dBm/time axes, selected path, corrections, output state and dropped - [ ] Label MHz/dBm/time axes, selected path, corrections, output state and dropped

View File

@ -21,3 +21,28 @@ fn invalid_override_exits_without_entering_the_terminal() {
assert_eq!(fs::read_dir(&directory).unwrap().count(), 1); assert_eq!(fs::read_dir(&directory).unwrap().count(), 1);
fs::remove_dir_all(directory).unwrap(); fs::remove_dir_all(directory).unwrap();
} }
#[test]
fn malformed_csv_exits_without_entering_the_terminal_or_enumerating_ports() {
let directory =
std::env::temp_dir().join(format!("tiny-wb-csv-startup-{}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
let path = directory.join("broken.csv");
fs::write(&path, "frequency_MHz,level_dBm\n240,not-a-level\n").unwrap();
let config_path = directory.join("viewer.toml");
fs::write(&config_path, "[logging]\ndirectory = 'not-a-directory'\n").unwrap();
fs::write(directory.join("not-a-directory"), "ordinary file").unwrap();
let result = Command::new(env!("CARGO_BIN_EXE_tiny-wb"))
.current_dir(&directory)
.env("TINY_WB_CONFIG", config_path)
.arg("--view")
.arg(&path)
.output()
.unwrap();
assert!(!result.status.success());
let error = String::from_utf8_lossy(&result.stderr);
assert!(error.contains("broken.csv"), "unexpected stderr: {error}");
assert!(error.contains("line 2"), "unexpected stderr: {error}");
assert!(!result.stdout.windows(2).any(|bytes| bytes == b"\x1b["));
fs::remove_dir_all(directory).unwrap();
}