Compare commits

..

47 Commits
0.1.1 ... main

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
Dandaedre 7fc9ed3f71 release: bump 0.1.3-rc.2
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-05 12:49:45 +02:00
Dandaedre 6fe4286e38 fix: configure Cross release dependencies
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-05 12:16:22 +02:00
Dandaedre 2def6e61e0 feat: prepare 0.1.3-rc.1 release candidate
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-05 10:10:15 +02:00
Dandaedre 1bc67400f6 docs: streamline project readme 2026-10-05 10:04:24 +02:00
Dandaedre 7558a24374 feat: detect tinySA Ultra and apply model-aware scan decoding
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-05 09:45:56 +02:00
Dandaedre 95e61dc5c3 docs: document Linux serial permissions
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-05 08:44:48 +02:00
Dandaedre b7ede664fa docs: detail Basic and Ultra completion tasks
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-05 02:06:03 +02:00
Dandaedre b4d14628bc test: add guided hardware validation 2026-10-05 01:53:10 +02:00
Dandaedre a7890c1712 fix: use array chunks for protocol records
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-05 01:40:31 +02:00
Dandaedre 820742048a ci: exclude dependency sources and summarize coverage output
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-10-05 01:02:50 +02:00
Dandaedre fe5933e9fd ci: expose silent coverage gate failures
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-10-05 00:46:57 +02:00
Dandaedre e47feea703 ci: verify core library builds and mock server integration
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-10-04 23:00:58 +02:00
Dandaedre 6893bf890a docs: plan complete Basic and Ultra feature coverage 2026-10-04 23:00:44 +02:00
Dandaedre b0be23639f feat: expose portable library connections and mock tinySA devices 2026-10-04 23:00:25 +02:00
Dandaedre 8f9059aeff feat: add project-local rust_realease wrapper and release policy 2026-10-04 22:40:49 +02:00
Dandaedre 9d917f9fc5 ci: enforce measured coverage floor and documentation gates 2026-10-04 22:33:05 +02:00
Dandaedre b5da980b6f refactor: wire configured acquisition into separated terminal UI 2026-10-04 22:31:05 +02:00
Dandaedre 25dd1f1712 refactor: extract testable acquisition protocol transport and export layers 2026-10-04 22:19:11 +02:00
Dandaedre b117029c76 feat: add validated typed configuration and atomic persistence 2026-10-04 22:13:29 +02:00
Dandaedre 77559e5b47 docs: define code structure documentation and verification standards 2026-10-04 22:10:14 +02:00
Dandaedre 0db65eb3af ci: generate and publish version test and coverage badges 2026-10-04 22:09:24 +02:00
Dandaedre 595aaf7b0c
ci: document project and harden Rust checks
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-10-04 17:17:56 +02:00
Dandaedre 960c3d6c59 Update Jenkinsfile
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details
2026-09-13 21:26:40 +02:00
Dandaedre eaad8c79cc Update Jenkinsfile
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-09-13 21:22:37 +02:00
Dandaedre 9625aaa784 Add Jenkinsfile
Dandaedre/tiny-wb/pipeline/head There was a failure building this commit Details
Rust CI tiny-wb failed CI.
Gitea/tiny-wb/pipeline/head There was a failure building this commit Details
2026-09-13 21:15:28 +02:00
Dandaedre 39e09e4363 Adds some Icons, an .ignore file and wrap for paragraphs 2024-09-27 08:30:40 -05:00
Dandaedre eccca9eb1c Adds icon, build script and shows build version 2024-09-27 03:05:46 -05:00
77 changed files with 14886 additions and 1814 deletions

View File

@ -1,2 +1,10 @@
[build]
rustflags = ["-Clink-arg=-fuse-ld=lld"]
[resolver]
incompatible-rust-versions = "fallback"
[alias]
# Registry source paths can differ from the inferred Cargo home on CI workers.
# Measured across library and application code; do not exclude production sources.
coverage = "llvm-cov --locked --all-targets --all-features --ignore-filename-regex /registry/src/ --json --summary-only --fail-under-lines 85 --output-path coverage/summary.json"

11
.gitignore vendored
View File

@ -4,10 +4,6 @@
debug/
target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
@ -22,3 +18,10 @@ Cargo.lock
*.csv
*.log
config.toml
/coverage/
/target-ci/
/hardware-validation/
# rust_realease artifacts and build cache
/dist/

1
.ignore Normal file
View File

@ -0,0 +1 @@
assets/

66
AGENTS.md Normal file
View File

@ -0,0 +1,66 @@
# Working on tiny-wb
## Structure and dependencies
- Keep the binary entry point small: configuration, diagnostics, terminal lifetime,
and application startup belong there.
- Separate configuration/persistence, protocol decoding, transport, acquisition,
CSV export, shared scan state, and terminal presentation by responsibility.
Do not recreate a miscellaneous `structs` module.
- Protocol and export code must be usable without a terminal or physical device.
Accept `Read`/`Write` implementations or explicit data instead of opening files
or serial ports inside parsers. Keep model rules separate from transport rules.
- Pass typed settings explicitly. Put user-adjustable defaults in
`config/default.toml`; keep wire-format invariants in the protocol module.
Validate settings before connecting or creating output, including units,
bounds, empty collections, and non-finite numbers.
- Preserve existing configuration compatibility or document a tested migration.
Unknown keys and invalid supplied values must produce actionable errors.
- Prefer small concrete types and functions over speculative abstraction.
Introduce a trait only when multiple implementations or an actual test seam
justify it. Avoid adding dependencies for small standard-library operations.
- Propagate I/O errors, use complete writes, bound receive buffers, and never
interpret binary payload as text. Do not use `unsafe` for protocol ordering.
## Documentation and comments
- Update user-visible behavior, configuration examples, architecture/source maps,
protocol notes, and verification instructions in the same task as code changes.
Link to the authoritative document instead of duplicating detailed guidance.
- Add module documentation explaining its responsibility and boundaries. Public
APIs need Rustdoc covering units, invariants, errors, and meaningful examples.
Private comments should explain intent, non-obvious constraints, or tradeoffs;
do not narrate straightforward statements or retain commented-out code.
- Keep names and terminology consistent: MHz in user settings/CSV, Hz on the
wire, dBm for levels, milliseconds for configurable delays and timeouts.
- Separate observed behavior, upstream protocol evidence, and unverified hardware
assumptions. Preserve source links and verification dates for device facts.
Never claim a simulated transcript is a hardware integration test.
- Document limitations candidly. Avoid vague TODOs; explain the missing behavior,
its consequence, and what evidence would justify the next change.
- Keep README concise; use `docs/` for operational and architectural details.
Generated reports and badge SVGs stay ignored.
## Verification
- Add focused regression tests for changed behavior, especially malformed input,
boundary values, partial reads/writes, timeouts, absent ports, persistence, and
failure cleanup. Use in-memory transcripts and isolated temporary directories.
- Run formatting, locked checks/tests, Clippy with warnings denied, documentation,
the release build, and the declared MSRV check. Use the exact commands in
`docs/security-and-ci.md`; run security gates when changing dependencies.
- Run `cargo coverage` after changing Rust behavior. Raise the documented floor
only from measured results; never exclude production code to satisfy a target.
- Run `python3 scripts/test-badges.py` after CI/badge changes. Verify documentation
links and configuration examples after moving files or changing settings.
- Report unavailable hardware, Jenkins, platform, or publication checks explicitly.
Do not start Jenkins or publish shared assets as part of local verification.
## Commits
- Preserve unrelated work. Make one commit per coherent task with a concise
imperative subject (`refactor:`, `feat:`, `fix:`, `test:`, `docs:`, or `ci:`).
- Include tests and directly related documentation with their implementation.
Keep an independent CI change or contributor policy in its own commit.
- Inspect each staged diff; never commit generated files, local configuration,
logs, credentials, or build products. Do not push unless requested.

2237
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +1,64 @@
[package]
name = "tiny-wb"
version = "0.1.1"
version = "0.1.5"
edition = "2021"
rust-version = "1.91.0"
license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/idle-org/tiny-wb"
# Release tags are unprefixed; publisher archive names retain their -v prefix.
[package.metadata.binstall]
pkg-url = "{ repo }/releases/download/{ version }/{ name }-{ target }-v{ version }.tgz"
pkg-fmt = "tgz"
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
[features]
default = ["tui", "serial"]
# Core integrations can disable defaults to avoid terminal/native serial dependencies.
tui = ["dep:color-eyre", "dep:flexi_logger", "dep:ratatui", "dep:strum", "dep:winresource"]
serial = ["dep:serialport"]
mock = []
[lib]
name = "tiny_wb"
path = "src/lib.rs"
[[bin]]
name = "tiny-wb"
path = "src/main.rs"
required-features = ["tui", "serial"]
[[test]]
name = "startup"
path = "tests/startup.rs"
required-features = ["tui", "serial"]
[[example]]
name = "mock-tinysa-server"
path = "examples/mock-tinysa-server.rs"
required-features = ["mock"]
[[example]]
name = "validate-hardware"
path = "examples/validate-hardware.rs"
required-features = ["serial"]
[[test]]
name = "mock_device"
path = "tests/mock_device.rs"
required-features = ["mock"]
[dependencies]
chrono = "0.4.38"
clap = { version = "4.5.17", features = ["derive"] }
color-eyre = "0.6.3"
flexi_logger = "0.29.0"
# human-panic = "2.0.1"
log = { version = "0.4.22", features = ["release_max_level_error"] }
# log = { version = "0.4.22"}
memchr = "2.7.4"
once_cell = "1.19.0"
packed_struct = "0.10.1"
ratatui = "0.28.1"
color-eyre = { version = "0.6.3", optional = true }
flexi_logger = { version = "0.32.0", optional = true }
jiff = "1.0.1"
log = "0.4.22"
ratatui = { version = "=0.30.2", optional = true }
serde = { version = "1.0.210", features = ["derive"] }
serialport = "4.5.0"
strum = { version = "0.26.3", features = ["derive"] }
thiserror = "1.0.63"
serialport = { version = "4.5.0", optional = true }
strum = { version = "0.28.0", features = ["derive"], optional = true }
thiserror = "2.0.21"
toml = "0.8.19"
tui-textarea = "0.6.1"
[profile.release]
opt-level = "z"
@ -50,3 +88,6 @@ lto = true
codegen-units = 1
incremental = false
panic = "abort"
[build-dependencies]
winresource = { version = "=0.1.17", optional = true }

443
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,443 @@
// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post
pipeline {
agent { label 'rust_nodocker' }
options {
disableConcurrentBuilds()
skipDefaultCheckout(true)
}
environment {
// Jenkins does not render Cargo ANSI sequences cleanly.
CARGO_TERM_COLOR = 'never'
RUST_BACKTRACE = '1'
// LTS-like compatibility floor verified by the dedicated MSRV stage.
MSRV = '1.91.0'
// Supply-chain tools are pinned for reproducible policy behavior.
CARGO_AUDIT_VERSION = '0.22.2'
CARGO_DENY_VERSION = '0.20.2'
CARGO_LLVM_COV_VERSION = '0.9.1'
BADGE_ROOT = '/mnt/assets/coverage'
BADGE_OWNER = 'idle-org'
BADGE_PROJECT = 'tiny-wb'
BADGE_BRANCH = 'main'
// Keep CI build products separate.
CARGO_TARGET_DIR = "${WORKSPACE}/target-ci"
// Force a portable x86-64 baseline.
//
// The repository already wants lld; specifying it here makes
// the CI configuration explicit as well.
RUSTFLAGS = '-Ctarget-cpu=x86-64 -Clink-arg=-fuse-ld=lld'
}
stages {
stage('Checkout') {
steps {
sh 'rm -rf coverage && mkdir coverage'
checkout scm
sh '''
set -eu
git submodule sync --recursive
git submodule update --init --recursive
'''
}
}
stage('Setup Rust') {
steps {
sh '''
set -eu
if ! command -v rustup >/dev/null 2>&1; then
echo "ERROR: rustup is not installed on this worker." >&2
exit 1
fi
echo "Ensuring stable Rust is available..."
rustup toolchain install stable \
--profile minimal \
--component rustfmt \
--component clippy \
--component llvm-tools-preview
rustup toolchain install "${MSRV}" \
--profile minimal
rustup default stable
INSTALLED_AUDIT_VERSION="$(cargo audit --version 2>/dev/null | awk '{print $NF}' || true)"
if [ "${INSTALLED_AUDIT_VERSION}" != "${CARGO_AUDIT_VERSION}" ]; then
cargo install --locked \
--version "${CARGO_AUDIT_VERSION}" \
cargo-audit
fi
INSTALLED_DENY_VERSION="$(cargo deny --version 2>/dev/null | awk '{print $NF}' || true)"
if [ "${INSTALLED_DENY_VERSION}" != "${CARGO_DENY_VERSION}" ]; then
cargo install --locked \
--version "${CARGO_DENY_VERSION}" \
cargo-deny
fi
command -v jq >/dev/null 2>&1 || {
echo 'ERROR: jq must be installed on this worker.' >&2
exit 1
}
INSTALLED_COVERAGE_VERSION="$(cargo llvm-cov --version 2>/dev/null | awk '{print $NF}' || true)"
if [ "${INSTALLED_COVERAGE_VERSION}" != "${CARGO_LLVM_COV_VERSION}" ]; then
cargo install --locked --version "${CARGO_LLVM_COV_VERSION}" cargo-llvm-cov
fi
# ---------------------------------------------------------
# LLD
# ---------------------------------------------------------
if ! command -v ld.lld >/dev/null 2>&1; then
echo "lld not found — installing it..."
pkg install -y lld
else
echo "lld already installed."
fi
# ---------------------------------------------------------
# Clean build
# ---------------------------------------------------------
rm -rf "${CARGO_TARGET_DIR}"
mkdir -p "${CARGO_TARGET_DIR}"
# ---------------------------------------------------------
# Diagnostics
# ---------------------------------------------------------
echo
echo "Rust:"
rustc --version
echo
echo "Cargo:"
cargo --version
echo
echo "rustfmt:"
rustfmt --version
echo
echo "Clippy:"
cargo clippy --version
echo
echo "MSRV:"
rustc +"${MSRV}" --version
echo
echo "cargo-audit:"
cargo audit --version
echo
echo "cargo-deny:"
cargo deny --version
echo
echo "Compiler:"
cc --version || true
echo
echo "LLD:"
ld.lld --version
echo
echo "Rust flags:"
echo "${RUSTFLAGS}"
echo
echo "Host:"
uname -a
echo
echo "Rust target:"
rustc -vV
'''
}
}
stage('Cargo Audit') {
steps {
sh '''
set -eu
echo "Auditing the locked dependency graph with RustSec..."
cargo audit --deny warnings
'''
}
}
stage('Cargo Deny') {
steps {
sh '''
set -eu
echo "Checking dependency licenses, sources and policy..."
cargo deny check
'''
}
}
stage('MSRV') {
steps {
sh '''
set -eu
echo "Checking tiny-wb with Rust ${MSRV}..."
cargo +"${MSRV}" check \
--locked \
--all-targets \
--all-features
'''
}
}
stage('Format') {
steps {
sh '''
set -eu
echo "Checking Rust formatting..."
cargo fmt \
--all \
-- \
--check
'''
}
}
stage('Check') {
steps {
sh '''
set -eu
echo "Checking tiny-wb..."
cargo check \
--locked \
--all-targets \
--all-features
'''
}
}
stage('Tests') {
steps {
sh '''
set -eu
echo "Running tests..."
cargo test \
--locked \
--all-targets \
--all-features
'''
}
}
stage('Library feature matrix') {
steps {
sh '''
set -eu
cargo test --locked --no-default-features --lib
cargo check --locked --no-default-features --features serial --lib
cargo test --locked --no-default-features --features mock --lib --test mock_device
cargo build --locked --no-default-features --features mock --example mock-tinysa-server
python3 scripts/test-mock-server.py "${CARGO_TARGET_DIR}/debug/examples/mock-tinysa-server"
'''
}
}
stage('Documentation') {
steps {
sh '''
set -eu
cargo test --locked --doc --all-features
RUSTDOCFLAGS="-D warnings" cargo doc --locked --no-deps --all-features
'''
}
}
stage('Coverage') {
steps {
sh '''
set -eu
scripts/collect-coverage.sh
touch "coverage/.tests-passed-${BUILD_NUMBER}"
touch "coverage/.coverage-ready-${BUILD_NUMBER}"
'''
}
}
stage('Clippy') {
steps {
sh '''
set -eu
echo "Running Clippy..."
cargo clippy \
--locked \
--all-targets \
--all-features \
-- \
-D warnings
'''
}
}
stage('Build Release') {
steps {
sh '''
set -eu
echo "Building tiny-wb release..."
cargo build \
--locked \
--release \
--all-features
BINARY="${CARGO_TARGET_DIR}/release/tiny-wb"
if [ ! -f "${BINARY}" ]; then
echo "ERROR: expected release binary not found:" >&2
echo "${BINARY}" >&2
exit 1
fi
echo
echo "Release binary:"
ls -lh "${BINARY}"
echo
echo "Binary information:"
file "${BINARY}" || true
echo
echo "Dynamic dependencies:"
ldd "${BINARY}" || true
'''
}
}
stage('Smoke Test') {
steps {
sh '''
# ---------------------------------------------------------
# NON-FATAL DIAGNOSTIC
# ---------------------------------------------------------
#
# tiny-wb is an interactive serial/TUI application.
#
# On the current FreeBSD Jenkins worker the optimized
# executable currently receives SIGILL during startup,
# even with target-cpu=x86-64.
#
# Compilation, tests and release linking remain CI gates.
# This stage records the runtime behaviour without making
# it fail the complete CI job.
# ---------------------------------------------------------
BINARY="${CARGO_TARGET_DIR}/release/tiny-wb"
echo "Diagnostic release-binary smoke test..."
set +e
"${BINARY}" --help
RESULT=$?
set -e
echo
if [ "${RESULT}" -eq 0 ]; then
echo "Smoke test passed."
else
echo "WARNING: release executable exited with ${RESULT}."
echo
echo "This is currently diagnostic only."
echo "The FreeBSD Jenkins worker has previously produced"
echo "SIGILL (exit 132) when starting the optimized binary."
fi
# Deliberately succeed.
exit 0
'''
}
}
}
post {
success {
publishChecks(
conclusion: 'SUCCESS',
name: 'Rust CI',
summary: 'tiny-wb passed CI.',
text: 'RustSec audit, dependency policy, MSRV, formatting, compilation checks, tests, documentation, coverage, Clippy and the release build completed successfully. Badge generation and archival run in cleanup. The release runtime smoke test is currently diagnostic only.',
title: 'Build Successful'
)
echo '✅ tiny-wb passed CI.'
}
failure {
publishChecks(
conclusion: 'FAILURE',
name: 'Rust CI',
summary: 'tiny-wb failed CI.',
text: 'RustSec audit, dependency policy, MSRV, formatting, compilation, tests, documentation, coverage, Clippy, or the release build failed. Cleanup generates and archives current badges, including failure fallbacks. Check the Jenkins log.',
title: 'Build Failed'
)
echo '❌ tiny-wb CI failed.'
}
unstable {
publishChecks(
conclusion: 'ACTION_REQUIRED',
name: 'Rust CI',
summary: 'tiny-wb CI is unstable.',
text: 'The Jenkins build completed with an unstable status.',
title: 'Build Unstable'
)
echo '⚠️ tiny-wb CI is unstable.'
}
cleanup {
sh 'scripts/finalize-badges.sh'
archiveArtifacts artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg',
fingerprint: true, allowEmptyArchive: false
script {
// BRANCH_NAME is supplied by Jenkins multibranch jobs.
// Fail closed for other job types; do not infer from detached HEAD.
if (!env.BRANCH_NAME) {
echo 'Badge publication skipped: BRANCH_NAME unavailable; verify multibranch job configuration.'
} else if (env.BRANCH_NAME == env.BADGE_BRANCH && !env.CHANGE_ID && !env.TAG_NAME) {
sh 'scripts/publish-badges.sh "$BADGE_ROOT" "$BADGE_OWNER" "$BADGE_PROJECT" "$BADGE_BRANCH" version test coverage'
}
}
}
}
}

148
README.md
View File

@ -1,43 +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>
Simple tinySA to Workbench converter
![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)
![Line coverage](https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/coverage.svg)
# First window
> Selection
Scan a frequency range with your **tinySA**, see the spectrum in your terminal,
and save the measurements as CSV. Start with one scan; no configuration-file
editing is needed.
Starts with the most likely com port selected (last used, then usual suspect, then port 0)
Enter selects it (in the validation sense)
Selects the first likely baudrate (same algo)
Enter selects it
Selects the validate text box
## Open source and development
First selection should be enter, then with L/R U/D (or mouse?) you can change the params
(P) to select a port (B) to select a baudrate (Enter) to be put on the <Next> selection
tiny-wb is open-source software under the [MIT license](LICENSE). Its
development includes LLM-generated or LLM-assisted work, with human review.
It is used in professional settings; supported workflows and current
limitations are documented in this repository.
# Second window
> Customisation
## Get running
Tab/L/R for navigation, Enter to change a parameter
Starts with <Scan> selected and either (L/R/U/D) to be put on the fields
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).
# Third window
> Result
To build from source, install Rust **1.91 or newer**, then run:
Show a progress bar, then show a nice message with a prompt to ask where to save, then exits
```console
git clone https://proxy.dandaedre.com/gitea/idle-org/tiny-wb.git
cd tiny-wb
cargo run --locked --release
```
# References
Already have the checkout? Run just the last command from its root. On Linux,
building also requires the libudev development package and `pkg-config`; this
checkout's linker configuration uses `lld`.
* First line is discardable as it contains only a repead of sent command
* Read needs to stop on "ch>" 99, 104, 62
* Need to send resume afterward
* Doc: https://tinysa.org/wiki/pmwiki.php?n=Main.USBInterface
* Working example: http://athome.kaashoek.com/tinySA/python/
* Firmwares: All firmware files are located in http://athome.kaashoek.com/tinySA/DFU/
* QT5 GUI:https://github.com/g4ixt/QtTinySA?tab=readme-ov-file
* TUI: Rattatui
* ProgressB: Indicatif
* Version: tinySA4: Ultra, tinySA_ Tiny
* Scan will start with 123 and end with 125
* https://groups.io/g/tinysa
* https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c
* NANOVNA: https://github.com/ttrftech/NanoVNA?tab=readme-ov-file
## Your first scan
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.
![Scan setup with Start 280 MHz, Stop 320 MHz, 1001 points and Repeat 1](docs/images/scan-settings.png)
*Scan settings in the real application. Screenshots use the mock device; no
physical instrument or RF source is needed to reproduce this demonstration.*
![Completed simulated scan with a peak near 300 MHz and the visible-peak readout enabled](docs/images/scan-result.png)
*Example result from simulated data, with **m** pressed to show the peak.
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
cargo run --locked --release -- --view scan.csv
```
Want repeated sweeps? Start with `cargo run --locked --release -- --live`, then
choose the connection and range as above. In live mode, **s** saves the visible
trace and **q** stops after the current sweep and saves it. See
[live controls](docs/tiny-wb-operations.md#live-display) for averaging and hold modes.
## If something does not work
- **No port, or access denied?** Check the USB cable, close other serial software,
and follow the [serial-permission guide](docs/tiny-wb-operations.md#serial-permissions).
- **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.
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.
## 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).

BIN
assets/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

BIN
assets/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

BIN
assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

23
build.rs Normal file
View File

@ -0,0 +1,23 @@
//! Application-only resources; library-only builds need neither Git nor windres.
#[cfg(feature = "tui")]
fn main() -> std::io::Result<()> {
if std::env::var_os("CARGO_CFG_WINDOWS").is_some() {
winresource::WindowsResource::new()
.set_icon("assets/icon.ico")
.compile()?;
}
// Source archives and path dependencies may not have Git installed/a checkout.
let revision = std::process::Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.output()
.ok()
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.unwrap_or_else(|| "unknown".into());
println!("cargo:rustc-env=GIT_HASH={}", revision.trim());
Ok(())
}
#[cfg(not(feature = "tui"))]
fn main() {}

70
config/default.toml Normal file
View File

@ -0,0 +1,70 @@
# Embedded defaults. Copy to config.toml to customize; partial overrides work.
# Frequencies here and in CSV are MHz; commands sent to tinySA use Hz.
port = ""
baudrate = 115200
start_frequency = 240
stop_frequency = 800
points = 10001
repeat = 1
[connection]
backend = "serial"
# Numeric socket address only; used by the TCP bridge/mock, not by native tinySA USB.
tcp_address = "127.0.0.1:7355"
tcp_timeout_ms = 3000
[serial]
# Timeout for each blocking serial read, not a whole-scan deadline.
timeout_ms = 3000
command_delay_ms = 20
settle_delay_ms = 200
scan_delay_ms = 2000
max_response_bytes = 65536
baudrates = [19200, 38400, 57600, 115200, 230400, 460800, 921600, 1843200, 2000000, 3000000]
preferred_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]
[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.
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.
auto_zero_offset = true
# Manual fallback used only when auto_zero_offset is false. The selected value
# is sent with `zero`; the decoder must use that same value.
zero_offset = 128
frequency_step_mhz = 10
points_step = 100
min_points = 101
max_points = 1000001
max_repeat = 1000
# Match scanraw's integer-truncated span / points mapping. Use `inclusive` only
# to reproduce CSV files created by older tiny-wb releases.
frequency_axis = "firmware"
# Retain the historical preparatory text scan until hardware confirms removal.
legacy_pre_scan = true
[ui]
poll_interval_ms = 16
chart_min_dbm = -128.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]
directory = "."
filename_prefix = "scan"
include_header = false
[logging]
filter = "info"
directory = "."

12
config/mock-basic.toml Normal file
View File

@ -0,0 +1,12 @@
# Synthetic Basic; only the documented subset in docs/mock-device.md is implemented.
model = "basic"
echo = true
read_chunk_bytes = 7
write_chunk_bytes = 3
max_points = 10001
floor_dbm = -96.0
peak_dbm = -32.0
peak_frequency_hz = 300000000
peak_width_hz = 10000000
fault = "none"
fault_command = "scanraw"

13
config/mock-client.toml Normal file
View File

@ -0,0 +1,13 @@
# Run the standard TUI against the Basic mock server, without USB hardware.
points = 101
[connection]
backend = "tcp"
tcp_address = "127.0.0.1:7355"
tcp_timeout_ms = 3000
[serial]
command_delay_ms = 0
settle_delay_ms = 0
scan_delay_ms = 0
[scan]
frequency_axis = "firmware"
legacy_pre_scan = false

15
config/mock-ultra.toml Normal file
View File

@ -0,0 +1,15 @@
# Synthetic generic Ultra identity/syntax. Production additionally recognizes
# explicit ZS406 identity for normal scans through 900 MHz and opt-in Ultra mode.
model = "ultra"
echo = true
read_chunk_bytes = 7
write_chunk_bytes = 3
max_points = 10001
# Simulation ceiling only; detect real model/firmware capabilities separately.
ultra_max_hz = 6000000000
floor_dbm = -96.0
peak_dbm = -32.0
peak_frequency_hz = 1000000000
peak_width_hz = 10000000
fault = "none"
fault_command = "scanraw"

36
deny.toml Normal file
View File

@ -0,0 +1,36 @@
[graph]
all-features = true
[advisories]
ignore = []
[licenses]
allow = [
"Apache-2.0",
"MIT",
"MPL-2.0",
"Unicode-3.0",
"Zlib",
]
confidence-threshold = 0.8
exceptions = []
clarify = []
[bans]
multiple-versions = "warn"
wildcards = "deny"
allow = []
deny = []
skip = []
skip-tree = []
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
allow-git = []
[sources.allow-org]
github = []
gitlab = []
bitbucket = []

59
docs/README.md Normal file
View File

@ -0,0 +1,59 @@
# tiny-wb technical documentation
This directory is the local reference for the project and the instruments it
controls. It is deliberately split by concern so that maintainers normally do
not need to reread the upstream wiki before changing the code.
## Reading order
1. [Project architecture](architecture.md) explains what `tiny-wb` does and
how control and data move through the Rust application.
2. [tinySA field guide](tinysa-field-guide.md) identifies the hardware,
explains the RF signal paths, and covers safe and accurate use.
3. [USB console and `scanraw` protocol](usb-protocol.md) is the implementation
reference for serial commands and binary acquisition.
4. [tiny-wb compatibility and operations](tiny-wb-operations.md) maps those
facts onto the behavior, restrictions, and failure modes of this repository.
5. [Security, dependency policy, and MSRV](security-and-ci.md) documents the
reproducible-build and supply-chain gates.
6. [Upstream source catalogue](sources.md) records the primary references and
their scope.
7. [Hardware validation](hardware-validation.md) provides guided Basic and Ultra
checklists and the interactive validator command.
## Scope and authority
There are three different kinds of statement in these documents:
- **Instrument facts** come from the official tinySA wiki or the upstream
firmware source.
- **Application facts** come from the code in this repository.
- **Engineering conclusions** are called out as implications, risks, or
recommendations.
The material was verified on **2026-10-04**. Specifications and console
commands can change with firmware and hardware revisions. When a connected
device disagrees with this documentation, record its `version`, `info`, and
`help` output and treat those results plus the matching firmware source as
authoritative.
## Why this is not an mdBook yet
The documentation is a small, navigable set of Markdown files with direct
cross-links. Adding mdBook configuration and a CI publication stage now would
introduce a new build dependency without improving navigation. If the guide
grows into many chapters, the files are already organized so that a future
`SUMMARY.md` can include them with little restructuring.
## Contributor references
- [Configuration](configuration.md): embedded defaults, partial overrides and persistence.
- [Testing](testing.md): regression seams and hardware verification boundaries.
- [Agent/contributor guidance](../AGENTS.md): code structure, comments, documentation and atomic commits.
- [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.
- [Feature roadmap](roadmap.md): model-aware Basic/Ultra completion tasks.
- [Implementation task backlog](../task.md): detailed milestones and optional stretch goals.
- [Library integration](library.md): feature selection and public interfaces.
- [Mock device](mock-device.md): in-memory and TCP simulation.

174
docs/architecture.md Normal file
View File

@ -0,0 +1,174 @@
# Project architecture
`tiny-wb` has a reusable acquisition library and a thin terminal application.
The core accepts typed values and I/O interfaces; it does not depend on UI
widgets, port discovery, worker threads, or the application's working directory.
## Source map
| File | Responsibility |
| --- | --- |
| `src/lib.rs` | Public core module boundary. |
| `src/config.rs` | Typed settings, recursive partial overrides, legacy-key compatibility and validation. |
| `config/default.toml` | Authoritative embedded defaults, with units and comments. |
| `src/storage.rs` | Same-directory atomic replacement for saved configuration. |
| `src/protocol.rs` | Structural scan validation, wire invariants and pure raw-frame decoding. |
| `src/device.rs` | Family identification, model-specific ranges, input paths and native offsets. |
| `src/transport.rs` | Buffered `Read + Write` shell I/O, complete command writes, text prompts and length-delimited raw frames. |
| `src/connection.rs` | Runtime serial/TCP adapter; native serial is optional. |
| `src/mock/` | Opt-in bounded device simulation and stream server. |
| `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/export.rs` | CSV parsing/serialization over I/O traits and collision-safe file export. |
| `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/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/state.rs` | UI state, configured port/baud choices and bounded numeric input. |
| `src/ui/view.rs` | Ratatui rendering and selection styling. |
| `build.rs` | Embed Git revision and compile the Windows icon resource. |
| `Jenkinsfile` | Required quality gates, coverage, badge cleanup/archival/publication and diagnostic smoke execution. |
## Data flow
```text
embedded defaults + runtime overrides -> validated Config
|
startup / terminal controller
|
ScanRequest (Hz) + selected Config
|
connection worker
|
Shell<Connection> -> acquisition
|
decode_frame -> Vec<Sample>
|
CSV export + completed UI snapshot
```
`ScanRequest` carries Hz, sample count and repeat count. `Sample` carries MHz
and dBm. Units are converted at the UI/core boundary, not inside widgets or
file naming. The selected zero offset is both sent to the instrument and used
by the decoder. Frequency labeling is an explicit policy; the default mirrors
the reviewed firmware's integer/single-precision `scanraw` calculation, while
legacy endpoint-inclusive labels remain available for compatibility.
Protocol constants record the native raw-level biases (Basic 128, Ultra 174).
`device.rs` detects the family and validates its acquisition plan. Both the
application and validator select the native bias automatically and confirm
the readback. See [support scope](ultra-support.md).
The core reports `ScanEvent` values. `ScanState` adapts them to one
`Arc<Mutex<Progress>>`; completion publishes samples, filename, status and 100%
progress together only after export succeeds. The UI transfers the completed
sample vector once, rather than cloning it every frame. Error reporting uses
the original error's message instead of a second exhaustive mapping.
## UI state machine
```text
SelectingConnection -> SelectingScan -> Scanning -> Complete -> exit
^ | |
+---- n -------+ +-- r --> Scanning
| | |
+------------------+-------------+-> Error -> exit
CSV file -------------------------------------> Complete -> exit
--live: SelectingConnection -> SelectingScan -> Live --stop+save--> exit
```
The constructor takes configuration and enumerated ports as values, without
reading files. Selection is clamped before rendering, including empty lists.
Before a scan starts, the controller validates the complete selected settings
and request, atomically saves settings, then starts a worker. The controller
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.
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.
## Acquisition and protocol boundary
1. Validate structural request and sample/repeat limits before using a port.
2. Synchronize with stale input, allowing an idle timeout only during this step.
3. Query `version`/`info`, validate the detected model's range, check `help`, and run advertised diagnostics.
4. Set `repeat` and the selected raw zero offset, then verify its readback.
5. Attempt `pause`, select input mode, and configure the display sweep.
6. Optionally retain the historical `scan START STOP 290 101` preparation.
7. Request `scanraw`, consume exactly the expected framed record count, then
consume the trailing shell prompt.
8. Decode/validate all records and attempt `resume` on success or failure after
pause was attempted. Preserve both failures if resume also fails.
9. Export validated samples and mark the application scan complete.
The transport uses a persistent buffered stream. Prompt matching spans serial
reads; bytes beyond a prompt remain available. Binary records are read by
length, so sample bytes equal to braces or text characters are not delimiters.
EOF, disconnect, oversized text and missing prompts are errors rather than
successful partial reads. Writers use `write_all`, and protocol sequencing does
not require `unsafe`.
See [USB protocol](usb-protocol.md) for firmware evidence and the unresolved
frequency-label compatibility decision. Device facts are not inferred from
our synthetic test transcripts.
## Configuration and persistence
The six legacy selection keys remain top-level. Additional sections cover
serial timing/choices, scan policy, event timing, chart bounds, output and
logging. Partial files merge with embedded defaults; unknown or invalid values
fail explicitly. Saving selection values retains all recognized sections.
CSV formatting is independent of file creation. The worker does not create a
CSV until a complete frame has been validated and acquisition has returned
success. Filenames contain microseconds plus a collision counter; exclusive
creation avoids overwriting earlier scans. Failed writes remove incomplete
files when the filesystem permits it. A file may be visible while being
written; the returned path/completed status is the success indicator.
See [configuration](configuration.md) for settings, paths and exact behavior.
## Extension points and remaining limits
- Add model/capability recognition ahead of request planning. The current
Basic mode rules must not be stretched to imply Ultra support.
- Add new output formats beside `write_csv`, consuming `Sample` values rather
than parsing the wire format again.
- Inject transcript streams into `Shell` and writers into export tests. Keep
UI tests on Ratatui's in-memory backend. See [testing](testing.md).
- Settings change policy and timing; wire delimiters, fixed-point scaling and
command grammar remain protocol invariants.
- Known error/usage replies reject configuration commands, but responses are
not a complete typed acknowledgement protocol. An echo-only identity can
appear nonempty; prompt arrival alone is not proof of acceptance.
- Serial timeouts are per-read idle timeouts, not a whole-transaction deadline.
Cancellation/abort and complete device-state restoration remain future work.
Quitting during a scan can terminate the worker before its resume attempt.
- Synthetic tests do not establish the connected firmware's frequency stepping,
raw-offset acceptance, or need for the legacy preliminary scan. Defaults retain
previous behavior until hardware evidence supports changing it.
## Dependency policy
The core uses standard-library byte decoding instead of `packed_struct`, and
buffered framing instead of a separate direct `memchr` dependency. Transitive
`memchr` use elsewhere in the graph is unrelated. Serde/TOML handle settings;
serialport, Ratatui, jiff, log/flexi_logger, color-eyre and thiserror retain
their device, presentation, timestamp and error-reporting roles.
Library consumers can omit terminal and serial dependencies; see [feature selection](library.md).
The [mock](mock-device.md) uses the same shell/acquisition code over memory or TCP.

115
docs/configuration.md Normal file
View File

@ -0,0 +1,115 @@
# Application configuration
`config/default.toml` is the authoritative, commented set of defaults embedded
in the binary at compile time. To customize them, copy it to `config.toml` in
the working directory, or supply a partial file containing only overrides.
Rebuild after changing the embedded file; it is not read at runtime.
At startup the application reads `config.toml`, or the path named by the
`TINY_WB_CONFIG` environment variable. For example:
```console
TINY_WB_CONFIG=/path/to/session.toml cargo run --release
```
Settings and logging are validated before entering the terminal interface.
Saving a scan selection writes to this same path; unrelated configuration
sections are retained. An invalid file is reported rather than silently reset.
The configuration API is in `src/config.rs`. It recursively merges supplied
TOML tables with the embedded defaults, deserializes into typed settings, and
validates before use. Arrays replace their defaults. Unknown keys, invalid
numbers, malformed files and I/O failures are errors; only an absent file uses
defaults. The original six top-level keys remain compatible:
```toml
port = "/dev/ttyACM0"
baudrate = 115200
start_frequency = 240
stop_frequency = 960
points = 10001
repeat = 1
```
Start/stop frequencies are **MHz**. The shared entry envelope is 0–5,400 MHz,
with stop at least 10 MHz; detected model/revision policy applies before the
instrument is mutated. Basic remains limited to 960 MHz, generic Ultra to 800
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 |
| --- | --- |
| `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, 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, finite increasing chart bounds in dBm, and plot navigation bindings. |
| `output` | CSV directory, filename prefix, and optional column header. |
| `logging` | Logger filter expression and destination directory. |
`scan.device_model = "auto"` detects the family before changing settings.
`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
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).
For example, this partial file changes the serial timeout and output format
while retaining the default scan selection:
```toml
[serial]
timeout_ms = 5000
[output]
directory = "scans"
filename_prefix = "measurement"
include_header = true
```
All relative paths are relative to the process working directory. Saving a
selection preserves every recognized section, using a same-directory temporary
file, flush, and rename. The old configuration survives validation or write
failure. TOML formatting and comments are not preserved; retain comments in a
separate template if needed. The configuration file's parent must exist.
`scan.frequency_axis = "firmware"` is the default. It reproduces the reviewed
`scanraw` integer division, single-precision multiplication and conversion back
to integer Hz. `"inclusive"` preserves the legacy tiny-wb labels
(`span / (points - 1)`) and includes the requested stop frequency. Neither
setting changes the request or proves RF frequency accuracy. Existing saved
files that explicitly contain `frequency_axis = "inclusive"` keep their old
labels; partial configurations that omit the key adopt the corrected default.
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
`scan.legacy_pre_scan = true` for compatibility. Its undocumented output mask
is not a tunable protocol contract. Disable the step only after checking the
target instrument; hardware validation remains necessary.
Protocol delimiters, fixed-point scaling, command grammar and Basic input-path
limits remain code invariants. Configuration cannot turn a Basic-only client
into an Ultra-compatible one by increasing a numeric limit.
## Connection backends
`[connection] backend = "serial"` preserves USB behavior. Select `"tcp"` with
`tcp_address = "127.0.0.1:7355"` and `tcp_timeout_ms = 3000` for an explicit
mock/bridge. The address must be numeric IPv4/IPv6 with a nonzero port; timeout
is 1–600,000 ms and applies to connect/read/write operations. All backend fields
are validated, including inactive ones. TCP bypasses USB enumeration and ignores
serial port/baud selections; protocol pacing still uses `[serial]` timing fields.
See the [mock client template](../config/mock-client.toml) and [mock guide](mock-device.md).

117
docs/hardware-validation.md Normal file
View File

@ -0,0 +1,117 @@
# tinySA hardware validation checklist
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
Basic and once with each supported tinySA Ultra profile; keep reports separate.
## Before each run
- [ ] Identify the rear-label model and record the firmware shown by the device.
- [ ] Disconnect every RF source. This test needs only the analyzer and a
data-capable USB cable.
- [ ] Close serial terminals and other tinySA software. Confirm the current user
can open the USB serial port without running the validator as root.
- [ ] If the front-panel configuration matters, save a preset. The validator
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:
```console
scripts/test-hardware.sh basic
```
For an Ultra, use:
```console
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
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,
runs two 101-point scans, validates the returned values, writes CSV files and an
identity report under ignored `hardware-validation/`, and asks whether the
front-panel sweep resumed.
## Basic acceptance
- [ ] The automatically selected port belongs to the Basic.
- [ ] Both `legacy` (240–300 MHz low input) and `direct` (350–400 MHz high input)
scans report `PASS` and create CSV files with 101 data rows plus a units header.
- [ ] The printed `version`/`info` text matches the connected Basic and its
recorded firmware.
- [ ] The live front-panel sweep resumes after the scans; answer `y` only after
checking it.
- [ ] The final `basic-report.txt` records both CSV paths and
`operator_confirmed=y` (or `yes`).
- [ ] Each report entry records `raw_level_offset_db=128`.
### Recorded Basic evidence
The Basic acquisition path was validated on physical hardware on 2026-10-05
with firmware `tinySA_v1.4-175-g1419a93`. Both the 240–300 MHz low-input scan
and the 350–400 MHz high-input scan returned 101 valid samples, exercised the
fixed-record binary decoder, produced CSV output, and resumed the live sweep.
This is communications and workflow evidence, not frequency or level-accuracy
calibration.
## Ultra acceptance and limit
- [ ] The automatically selected port belongs to the Ultra.
- [ ] Both `legacy` and `direct` scans report `PASS` at 240–300 MHz and create
CSV files with 101 data rows plus a units header.
- [ ] The printed `version`/`info` text identifies the exact connected Ultra
variant and firmware.
- [ ] The live front-panel sweep resumes after the scans; answer `y` only after
checking it.
- [ ] The final `ultra-report.txt` records both CSV paths and
`operator_confirmed=y` (or `yes`).
- [ ] Each report entry records `raw_level_offset_db=174`.
A passing Ultra run validates only the shared low-input command path below
350 MHz, including the native `zero 174` encoding, binary framing, CSV export,
and best-effort
resume. It does not validate Ultra mode, harmonic mode, LNA behavior, ranges at
or above 350 MHz, level accuracy, or frequency accuracy. Those require
model-aware acquisition and a controlled reference source; do not infer them
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
- [ ] Keep the generated report and any completed CSV; do not edit them.
- [ ] Record the command, host OS, selected port, exact model, firmware, and the
complete `FAIL:` line.
- [ ] If the sweep did not resume, disconnect any RF setup and use `resume`,
reload the saved preset, or power-cycle the instrument.
- [ ] Do not connect a transmitter merely to reproduce a communications failure.

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

62
docs/library.md Normal file
View File

@ -0,0 +1,62 @@
# Rust library integration
The package builds both `tiny_wb` (Rust library) and `tiny-wb` (terminal app).
Rust 1.91 or newer is required. To integrate a checkout without terminal, serial,
libudev or Windows resource dependencies:
```toml
[dependencies]
tiny-wb = { path = "../tiny-wb", default-features = false }
```
| Cargo feature | Purpose |
| --- | --- |
| no features | Configuration, protocol, shell, Basic acquisition, CSV, TCP adapter |
| `serial` | Native USB/serial adapter |
| `tui` | Terminal dependencies and application build resources |
| `mock` | In-memory simulator and stream server; no additional dependencies |
| default | `tui` + `serial`, preserving the existing application |
The application requires both default features. Build only the library with
`cargo build --locked --lib --no-default-features`. This is a Rust API, not a
stable C ABI, shared-library binding or published crates.io compatibility promise.
Mock support is opt-in; the server is a Cargo example, preserving the existing
single-binary release artifact contract.
`Shell<T>` accepts any synchronous `Read + Write` stream. Use
`connection::open_connection(&config)` for configured serial/TCP connections,
or inject your own adapter. Transport deadlines belong to the adapter; an
arbitrary blocking `Read` implementation cannot be interrupted by the shell.
`acquisition::acquire` accepts a validated Basic `ScanRequest`, scan/timing
settings and a progress callback, and returns samples without opening files.
`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
use tiny_wb::{config::Config, connection::open_connection,
acquisition::acquire, protocol::ScanRequest, transport::Shell};
fn scan(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
config.validate()?;
let mut shell = Shell::new(open_connection(config)?, 65_536);
let request = ScanRequest {
start_hz: 240_000_000, stop_hz: 960_000_000, points: 101, repeat: 1,
};
let samples = acquire(&mut shell, &request, &config.scan, &config.serial, |_| {})?;
tiny_wb::export::write_csv(&mut std::io::stdout(), &samples, true)?;
Ok(())
}
```
Frequencies in requests are Hz; samples expose MHz and dBm. Keep the decoding
zero offset and frequency-axis convention explicit. Acquisition attempts
`resume` after every attempted pause and preserves both errors if recovery
fails. It does not restore all device settings. Known `error:`, `usage:` and
`unknown command` text replies reject configuration commands; this is not
universal firmware acknowledgement or automatic capability detection.
See [the mock guide](mock-device.md) for deterministic integration tests and
[the roadmap](roadmap.md) for the model-aware API still needed for Ultra.
Generate API documentation with `cargo doc --no-default-features --features mock --no-deps`.

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.

126
docs/mock-device.md Normal file
View File

@ -0,0 +1,126 @@
# Mock tinySA device
The optional `mock` feature provides a deterministic in-memory duplex stream
and a TCP server backed by the same device model. Standard `Read + Write`
keeps this portable without pseudo-terminal pairs, virtual COM drivers or
privileged serial setup. TCP is a mock/bridge transport, not a native tinySA
network feature. Simulated success is not hardware validation.
## Run the server and application
From the checkout, start the server:
```console
cargo run --locked --no-default-features --features mock --example mock-tinysa-server -- --config config/mock-basic.toml
```
In a second terminal, copy the client template to a writable settings file
outside the checkout, then point `TINY_WB_CONFIG` at that copy:
```sh
cp config/mock-client.toml /tmp/tiny-wb-mock-client.toml
TINY_WB_CONFIG=/tmp/tiny-wb-mock-client.toml cargo run --locked --bin tiny-wb
```
On Windows, copy the template to a chosen temporary file and set
`$env:TINY_WB_CONFIG` in PowerShell before running Cargo. The app saves settings
to this path; do not use the tracked template as the runtime file. The connection
screen offers `tcp://127.0.0.1:7355` without enumerating USB devices. Serial port
and baud selections have no effect on a TCP connection. Successful scans still
write CSV to the configured export directory.
Options: `--bind IP:port` (default `127.0.0.1:7355`), `--config FILE`, `--once`,
`--help`. Port zero asks the OS for a free port; the actual endpoint is printed.
Each accepted connection gets fresh state. The example serves one client at a
time; disconnected/error sessions allow the next client. `--once` exits after
one session, returning failure for session I/O errors. The library's
`serve_connection` lets integrations supply their own listener and concurrency.
Keep this unauthenticated test service on loopback.
## In-memory integration
Enable `mock` alongside `default-features = false` in the dependency entry:
```rust
use tiny_wb::{mock::{MockConfig, MockStream}, transport::Shell};
use std::time::Duration;
let mut device = MockStream::new(MockConfig::default()).unwrap();
{
let mut shell = Shell::new(&mut device, 65_536);
shell.synchronize().unwrap();
shell.command_checked("pause", Duration::ZERO, Duration::ZERO).unwrap();
}
assert!(device.state().paused);
```
`tests/mock_device.rs` runs production acquisition with one-byte reads/writes,
both echo modes, legacy preparation enabled/disabled, recovery faults, and a
real loopback TCP connection. Run without terminal or native serial dependencies:
```console
cargo test --locked --no-default-features --features mock --lib --test mock_device
```
## Supported synthetic behavior
| Commands | Behavior |
| --- | --- |
| `version`, `info`, `help` | Explicitly synthetic identity and implemented subset |
| `pause`, `resume` | Observable sweep state |
| `mode low/high input` | Basic input paths; Basic low stop below 350 MHz, high start at least 240 MHz |
| `mode input`, `mode low input` | Ultra mock input syntax; high mode rejected |
| `repeat N`, `zero N` | Stored count and fixed-point offset |
| `sweep start/stop Hz`, `sweep` | Stored bounds and query |
| `scanraw start stop points` | Bounded deterministic binary spectrum |
| `scan start stop 290 101` | Current app's compatibility preparation only; no trace data |
| `leveloffset`, `vbat`, `usart_cfg`, `threads`, `marker` | Fixed diagnostic fixtures, not measurement implementations |
| `lna on/off`, `ultra on/off` | Ultra-only state toggles with no RF effect |
Other commands or invalid arguments return an explicit error. No calibration,
RF output, display capture, arbitrary firmware behavior or complete console
emulation is claimed. The Ultra profile exercises automatic detection, native
offset readback and low-input acquisition. Production Ultra scans are limited
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).
Samples use the reviewed firmware's integer-divided, single-precision
`scanraw` point frequencies, a triangular peak above a configured floor, and
`round((dBm + zero_offset) * 32)` clamped to `u16`.
Frames contain `{`, repeated `x` plus little-endian `u16`, then `}` and a prompt.
Use the firmware frequency-axis setting for matching labels. There is no noise,
RF physics, timing model or amplitude change from LNA/repeat/Ultra toggles.
The mock Ultra ceiling is adjustable synthetic policy, not a model specification.
## Configuration and failures
[Basic](../config/mock-basic.toml) and [Ultra](../config/mock-ultra.toml) profiles
are partial TOML overrides of `MockConfig::default()`, separate from application
settings. Unknown keys and invalid bounds fail before accepting a session.
Public Rustdoc lists every field and unit. `session_timeout_ms` defaults to
30,000 and bounds server socket reads/writes; client timeouts are independent.
`read_chunk_bytes` and `write_chunk_bytes` exercise partial I/O. TCP may coalesce
chunks. Commands, frame allocations, pending responses and command history are
bounded; integrations must read responses instead of pipelining indefinitely.
`fault` is one of `none`, `reject`, `timeout`, `disconnect`, `missing_prompt`,
`truncated_frame`, `bad_alignment`. It fires once per session on the first
`fault_command` (default `scanraw`). Frame corruption requires `scanraw`.
Rejection/timeout/disconnect do not execute the command. Missing prompt and
frame corruption occur after execution. Timeout drops the response: an empty
in-memory read immediately returns `TimedOut`; a TCP client waits for its own
socket deadline. Disconnect yields EOF, then `BrokenPipe` on later writes.
Example fault override:
```toml
fault = "truncated_frame"
fault_command = "scanraw"
read_chunk_bytes = 1
write_chunk_bytes = 1
```
Faults verify error handling and resume attempts, not reliable recovery from
all possible real firmware stream states. Hardware transcripts and per-firmware
acceptance tests remain [roadmap work](roadmap.md).

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.

234
docs/releases.md Normal file
View File

@ -0,0 +1,234 @@
# 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
[`rust_realease`](https://proxy.dandaedre.com/gitea/idle-org/rust_realease).
It is based on the
[john-slop wrapper](https://proxy.dandaedre.com/gitea/idle-org/john-slop/src/branch/main/release.sh),
with this project's package, targets, tag convention and repository mapping.
The wrapper does not edit metadata, commit, tag, push, or repair a release.
A normal invocation **does publish** through the delegated publisher; begin
with a dry run and obtain publication authorization separately.
## Release contract
| Property | Source/policy |
| --- | --- |
| Cargo package | `tiny-wb`, the single root package in `Cargo.toml`. |
| 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. |
| Tag | Package version without a prefix, preserving existing tags such as `0.1.1`. |
| 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`, `aarch64-apple-darwin`, `x86_64-apple-darwin`. |
| Artifacts | Both cargo-binstall `.tgz` archives and standalone executables, plus `SHA256SUMS`. |
| Builds | Locked dependencies; tracked `Cargo.lock`; review toolchain/container inputs for repeatability. |
| Public repository | `https://proxy.dandaedre.com/gitea/idle-org/tiny-wb`. |
| Development origin | `git@git.dandaedre.com:idle-org/tiny-wb.git`. |
| Prerelease | A hyphen in the version before any `+build` suffix adds `--prerelease`. |
`rust-release.toml` sets the target matrix, profile, tag prefix, lock policy,
`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,
and Apple targets use the publisher's direct cargo-zigbuild backend. FreeBSD
remains a CI host, not an additional promised release artifact. Cross-compilation
does not establish native runtime or hardware compatibility.
The fallback does not rewrite the Git origin. `Cargo.toml` records the public
repository and the publisher-compatible binstall archive layout. Tag URLs lack
`v`; archive names retain `-v{version}`. For example, version `0.1.1` plans:
```text
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-pc-windows-gnu-v0.1.1.tgz
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
```
Each archive contains a matching stem directory and its one executable.
Public release/download verification and cargo-binstall checks are supported;
they remain unverified until a separately authorized real release succeeds.
Use cargo-binstall's `--git` mode for this repository rather than assuming it
is published to crates.io. This workflow does not run `cargo publish`.
## Prerequisites
Required: Git, Cargo/Rust (at least the declared MSRV), `rust_realease`, Cross,
and a usable Docker or Podman backend. Archives additionally need cargo-binstall
for installation verification. Local wrapper tests use Python 3.11+ (`tomllib`).
Use a publisher containing automated Apple support, released upstream in
`0.1.6-rc.3`; older publishers may reject `[build.apple]`. There is no repository
pin for the publisher. Confirm its installed version and help before use.
Tool installation is a maintainer action, not performed by the wrapper. Upstream's preferred installation command is:
```console
cargo binstall --git https://proxy.dandaedre.com/gitea/idle-org/rust_realease rust_realease
rust_realease --version
rust_realease --help
```
For Cross installation and image setup, follow the
[Cross project](https://github.com/cross-rs/cross). Select a working backend with
`CROSS_CONTAINER_ENGINE=podman` or `docker` when necessary. Check `cross --version`,
`cargo binstall -V`, and the selected engine's `info` command before building.
The Linux target needs libudev development files and pkg-config configuration;
the Windows target needs the GNU resource compiler used by `build.rs`
(`windres`). Native host compilation alone does not verify those container
prerequisites. [`release/Cross.toml`](../release/Cross.toml) installs
`libudev-dev` and `pkg-config` in the Linux image. `release.sh` exports its
absolute path as `CROSS_CONFIG` for the publisher process. The file is kept away
from the repository root because the publisher rejects root `pre-build`,
`dockerfile`, and `runner` hooks. Package installation requires access to the
image's Debian/Ubuntu repositories. A caller-supplied `CROSS_CONFIG` is
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
Store a token in a readable regular file outside the checkout, with only the
token on its first line; restrict its permissions to its owner. The account
needs repository read access and release write access. Do not commit tokens or
token paths. The wrapper reads the first line verbatim (also without a trailing
newline), rejects an empty first line, and exports it as `GITEA_TOKEN` only to
the publisher. It never passes the token in arguments or prints it. The publisher
is responsible for keeping it out of child builds and for download verification.
Compile-only builds do not access Gitea and need no token:
```console
./release.sh --compile-only
```
`--compile-only` builds local artifacts in ignored `dist/release-*/`, without
contacting Gitea. Inspect `SHA256SUMS`, archive members, executables and the
binstall layout before publication.
Preview the configured matrix without a token or containers:
```console
rust_realease . --package tiny-wb --artifact-format both --dry-run
```
Dry-run and compile-only are separate modes. Dry-run does not build, create
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.
After all readiness checks and separate publication authorization:
```console
./release.sh "$TOKEN_FILE"
```
You can invoke the script by its absolute path from another working directory.
The repository resolves from the script location; relative token and forwarded
file paths remain relative to your invoking directory. Additional options are
forwarded exactly, including spaces. For example, use `--message-file` with a
reviewed release-notes file. The publisher can update an existing release body
when notes are explicitly supplied. Do not add preparation/push/replacement flags
without deliberate authorization for those operations.
## Readiness, collisions and repeatability
Before publication:
1. Run the [local quality gates](security-and-ci.md#local-verification),
`python3 scripts/test-release.py`, `sh -n release.sh`, and ShellCheck when
available. Run `cargo package --locked` to verify the source package; this is
a local build/check, not registry publication.
2. Review release notes/changelog and set the intended package version. There
was no tracked changelog when this wrapper was introduced. Do not invent
historical entries or bump versions automatically. Record changes for the
next chosen version before publishing.
3. Require a clean checkout, a local unprefixed version tag at `HEAD`, and the
same tag/commit on origin. Inspect `git status --short`, `git rev-parse HEAD`,
`git rev-parse '<version>^{commit}'`, and `git ls-remote --tags origin`.
Tag creation and pushing are separate maintainer operations; never move an
existing tag to make this check pass.
4. Inspect the release-by-tag API at
`https://proxy.dandaedre.com/gitea/api/v1/repos/idle-org/tiny-wb/releases/tags/<version>`.
A 404 means missing; authentication, network and server errors are blockers,
not absence. Check draft/prerelease status and **all** asset names.
5. Compare the planned archive, binary and `SHA256SUMS` names to existing assets.
Any collision stops publication. `--replace-assets` requires inspection and
explicit approval to replace those exact assets; replacement is not atomic.
An existing empty release can be reused only after tag/version checks pass.
6. Run the publisher dry run shown above. Resolve every prerequisite or metadata error.
Repeat tag and release/asset inspection immediately before live publication.
The publisher normalizes archive metadata, but this is not a bit-for-bit build
reproducibility claim. Host Rust toolchains and Cross image digests are not pinned
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.
## 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
- Package and binary: `tiny-wb` 0.1.1. Expected tag: `0.1.1`, not `v0.1.1`.
- Both local and public-HTTPS remote `0.1.1` point to
`82aa266e18454905c01287035c377b8edf9f9c60`, not the current refactored checkout.
This is a publication blocker. The repository already has a later `0.1.2`
release, so choose the next version deliberately rather than retagging 0.1.1.
- The `0.1.1` release API returned HTTP 200: public, non-draft, non-prerelease,
**no assets**. None of the five planned names collide in that snapshot.
The `v0.1.1` endpoint returned 404. These checks do not authorize reuse.
- Git 2.56.0, Cargo 1.93.0, cargo-binstall 1.17.5 and Podman 6.1.3 were present.
Podman reported a usable `amd64` backend. The SSH origin query failed
(connection closed), so the remote tag was checked through the public HTTPS
Git endpoint; SSH push access remains unverified.
`rust_realease`, Cross and ShellCheck were unavailable and were not installed.
Publisher CLI/configuration and artifact names were inspected from upstream
source, not confirmed by a runnable local publisher.
- The real publisher dry run could not start (`command not found`). A real-token
wrapper dry run, Cross `--compile-only`, built-asset/checksum inspection and
cargo-binstall download verification remain **not verified**. No token file
was supplied, and no release or asset was created or replaced.

183
docs/roadmap.md Normal file
View File

@ -0,0 +1,183 @@
# tinySA feature completion roadmap
For implementation subtasks, dependencies, acceptance gates and selectable
stretch goals, use the detailed [task backlog](../task.md). Shared task IDs
refer to the same features; this document is the concise overview.
This is the task list for reaching documented feature coverage on tinySA Basic
and tinySA Ultra. It is a plan, not a claim that either model is fully supported.
Reviewed 2026-10-04 against the official console/menu documentation and firmware
sources linked below. No physical instrument was available for this change.
“Complete” means every feature of an explicitly supported hardware/firmware
combination has either a tested library API and user interface or a documented
remote-control limitation. A feature present on the touchscreen is not necessarily
available over USB. Ultra+, hardware revisions and firmware build options must
be distinct capability profiles, not inferred from the name “Ultra”.
## Foundations delivered
- [x] F01: Build a Rust library without terminal/native serial dependencies;
retain optional serial and existing default application builds.
- [x] F02: Share `Read + Write` framing across native serial, TCP and in-memory
adapters; keep acquisition and export independent of UI/filesystem ownership.
- [x] F03: Add bounded, stateful mock Basic/Ultra profiles, deterministic raw
samples, one-shot faults and a runnable TCP server example.
- [x] F04: Exercise production Basic acquisition over fragmented mock I/O and
real loopback TCP, including malformed responses and resume attempts.
These foundations do not complete Ultra acquisition or firmware emulation.
See [library integration](library.md) and [mock scope](mock-device.md).
## Priority 0 — trustworthy model-aware acquisition
Initial family/revision detection, native-offset readback, common Ultra
normal-range planning and the ZS406 non-harmonic Ultra profile are implemented;
see [support status](ultra-support.md). The broader P01–P04 acceptance gates
remain open pending further revision profiles and RF accuracy qualification.
- [ ] P01 **Inventory and capability negotiation** (depends F01–F04). Capture
`version`, `info`, `help` and matching firmware commit/build options for Basic
and each supported Ultra revision. Create a versioned command/capability
manifest, including argument forms, units, readback and unsupported features.
Unknown firmware must expose uncertainty and permit explicit profile selection.
Acceptance: recorded fixtures cover both families and unknown variants; no
model selection based only on a shared substring or successful prompt.
- [ ] P02 **Separate model rules from raw framing** (P01). Replace Basic-only
range/input validation with per-model input paths, ranges, zero offsets,
sweep/point limits and frequency-axis semantics. Add Ultra acquisition without
sending Basic `mode high input`. Acceptance: boundary tests for each declared
profile, hardware scans below/above 960 MHz where supported, and independently
verified frequency/dBm values. Do not use the mock's synthetic ceiling as evidence.
- [ ] P03 **Robust command sessions** (P01). Typed commands/replies, explicit
rejection handling, bounded binary capture readers, deadlines, cancellation,
reconnect and resynchronization; preserve context and partial results policy.
Acceptance: echoed/un-echoed and fragmented real transcripts, timeout/EOF at
each phase, stale prompts, rejected commands, and no silent partial success.
- [ ] P04 **State ownership and recovery** (P02–P03). Query and restore supported
settings, model pause/resume and generator state explicitly, define exclusive
session ownership. Acceptance: failure/cancellation tests for every mutation
plus hardware readback; report when full restoration is unavailable.
## Priority 1 — spectrum analyzer controls and data
Each item depends on P01–P04. Implement library API first, then mock behavior,
CLI/TUI access, documentation and hardware acceptance fixtures in the same task.
- [ ] A01 **Frequency and sweeps:** start/stop, center/span, CW/zero span, point
count, sweep time, continuous/single acquisition, repeat, frequency tables,
external frequency reference/offset, wideband and multiband where exposed.
Acceptance: requested versus actual frequencies and sweep completion verified.
- [ ] A02 **RF input chain:** per-model paths, attenuation/auto attenuation,
LNA and other gain/AGC controls, Ultra/auto/harmonic mode, IF choices and
overload state where queryable. Acceptance: legal combinations enforced by
profile and actual device readback; explain expected RF measurement limitations.
- [ ] A03 **Bandwidth and processing:** RBW/automatic RBW, VBW where available,
averaging, min/max hold, subtraction/reference traces, spur suppression,
detector/calculation modes and reset behavior. Acceptance: trace provenance
includes processing settings and corresponding firmware behavior is verified.
- [ ] A04 **Amplitude and units:** reference level, scale, displayed units,
external gain/loss, level correction tables and offsets. Acceptance: documented
conversion semantics and tests prevent double application of corrections.
- [ ] A05 **Trace acquisition/export:** ASCII scans, raw scans, trace/data and
frequencies queries, multiple/stored traces, streaming/repeated scans and
timestamped metadata. Acceptance: bounded memory/backpressure, aligned axes,
round-trip datasets and explicit firmware/model/settings metadata.
- [ ] A06 **Markers and measurements:** enable/select/move, peak search/tracking,
delta/reference markers and firmware-supported measurement readouts.
Acceptance: typed units and host-computed versus firmware-computed provenance;
values checked against the device display or matching trace.
- [ ] A07 **Triggers:** supported sources, level, polarity, position and
single-shot/auto modes. Acceptance: trigger waiting can be cancelled and is
distinguished from transport failure, with captured hardware trigger cases.
## Priority 2 — generator and complete instrument workflows
- [ ] G01 **RF generator** (P01–P04): supported output paths, CW/swept frequency,
level/attenuation, output enable, level sweep and available modulation modes
(AM/FM/narrow FM and other per-build modes). Acceptance: explicit output state,
validated limits, predictable stop/disconnect handling and external measurement
of supported settings. Never enable RF output as a probing side effect.
- [ ] D01 **Display/remote panel** (P03, A05): screenshot/capture decoding,
display refresh, touch injection, remote navigation and color/trace settings
where exposed. Acceptance: exact dimensions/pixel encoding per profile,
truncated-image tests and documented controls unavailable through the console.
- [ ] D02 **Presets and storage** (P04): load/save/recall instrument presets,
host profiles, saved traces/screenshots and SD features where remotely exposed.
Acceptance: distinguish volatile state, instrument persistence and host files;
prevent accidental overwrite and support versioned configuration migration.
- [ ] D03 **Calibration and self-test** (P01–P04): calibration output, self-test,
calibration/correction readback and firmware-supported calibration workflows.
Acceptance: guided prerequisites, explicit persistent changes, captured results
and hardware verification; simulator results always identified as synthetic.
- [ ] D04 **Device management** (P03): battery, device identity, firmware/build,
time/RTC, console/USART settings, reset and firmware-update/bootloader workflow
if a documented safe interface exists. Acceptance: reconnect behavior tested;
unsupported remote update is clearly documented rather than guessed.
## Priority 3 — access, integrations and qualification
- [ ] I01 **Headless command interface** (P02, A01–A07): scriptable discovery,
inspect/configure/acquire/export commands, stable machine-readable errors and
structured output. Acceptance: noninteractive workflows require no terminal,
exit codes are tested, and long operations support cancellation.
- [ ] I02 **Capability-driven UI** (A01–D04 incrementally): model/firmware banner,
units and supported control visibility, streaming plot, markers, generator and
saved workflows. Acceptance: every implemented remotely accessible feature
has a discoverable entry point; unavailable controls explain the reason.
- [ ] I03 **Library API lifecycle** (P02–P04): stable typed device/session facade,
builder/configuration versioning, integration examples and a release policy.
Decide on asynchronous adapters or foreign-language bindings only with actual
integration requirements. Acceptance: downstream example crates compile on
the MSRV and API compatibility is assessed before releases.
- [ ] Q01 **Expanded mock contracts** (each feature): add tested behavior only
for newly implemented commands, transcript replay, delayed/stalled responses,
noise fixtures and injected failures at transaction boundaries. Acceptance:
shared contract tests exercise adapters and real recorded replies; unsupported
commands continue to fail explicitly. Simulation does not certify RF accuracy.
- [ ] Q02 **Hardware and platform matrix** (all supported features): Basic and
declared Ultra revisions/firmware, Linux/macOS/Windows serial operation,
disconnects, permissions and extended acquisition. Acceptance: reproducible
test reports with firmware identifiers and reference measurements, separate
from mock coverage; Jenkins and packaged releases exercised on their hosts.
- [ ] Q03 **Completion audit** (all above): reconcile the capability manifest
with the official console list and menu tree. For every entry record API,
interface, tests, hardware evidence or precise remote-interface limitation.
Acceptance: no unclassified feature or unsupported broad “all tinySA” claim.
## Coverage audit map
Use this map when splitting tasks into issues. Command names are discovery
candidates, not a universal command contract; firmware conditionals matter.
| Feature family | Console/menu evidence to inventory | Tasks |
| --- | --- | --- |
| Identity and build | `version`, `info`, `help`, `deviceid` | P01, D04 |
| Frequency/time | `freq`, `sweep`, `sweeptime`, `actual_freq`, `frequencies`, menu multiband | A01 |
| Input and gain | `mode`, `attenuate`, `agc`, `lna`, `lna2`, `ultra`, `if`, `if1` | A02 |
| Filtering/calculation | `rbw`, `calc`, `spur`, menu VBW | A03 |
| Level/units/corrections | `level`, `leveloffset`, `ext_gain`, `correction`, `zero`, display units | A04 |
| Data/traces | `scan`, `scanraw`, `data`, `trace`, `repeat`, `pause`, `resume` | A05 |
| Markers/triggers | `marker`, `trigger`, measurement menus | A06, A07 |
| Generator | output `mode`, `output`, `level`, `levelchange`, `modulation` | G01 |
| Display/touch | `capture`, `refresh`, `color`, `touch`, `touchcal`, `touchtest` | D01, D03 |
| Presets/files | `save`, `recall`, `load`, `saveconfig`, SD/menu storage | D02 |
| Calibration/service | `caloutput`, `selftest`, `test`, `dac`, `sweep_voltage`, `clearconfig` | D03 |
| Device lifecycle | `vbat`, `time`, `usart`, `reset`, `release`, build/debug diagnostics | D04 |
Front-panel-only features may require upstream firmware work. Record that as a
separate dependency after checking the matching source; touch emulation alone
is not a reliable typed API for every menu feature.
## Primary references
- [Official USB interface and commands](https://tinysa.org/wiki/pmwiki.php?n=Main.USBInterface).
- [Ultra console transcript](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.ConsoleCommands): historical snapshot, not a current universal schema.
- [Ultra menu tree](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.MenuTree): includes functions that may lack console access.
- [Basic specifications](https://tinysa.org/wiki/pmwiki.php?n=Main.Specification),
[Ultra specifications](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Specification),
[Ultra hardware comparison](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Comparison).
- [Upstream firmware](https://github.com/erikkaashoek/tinySA), especially
[command handlers](https://github.com/erikkaashoek/tinySA/blob/main/sa_cmd.c)
and [command registration](https://github.com/erikkaashoek/tinySA/blob/main/main.c).
These links move; P01 must pin a commit matching each captured device firmware.

272
docs/security-and-ci.md Normal file
View File

@ -0,0 +1,272 @@
# Security, dependency policy, and MSRV
This project applies a deliberately small supply-chain hardening policy. It
tracks the application lockfile, verifies a stable compatibility floor, and
runs `cargo-audit` plus `cargo-deny`. No other hardening tools are in scope.
## Rust compatibility floor
The declared and CI-tested minimum supported Rust version (MSRV) is
**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.
The application code and the former Ratatui 0.28 dependency could be made to
compile with older compilers, but that graph contained the unmaintained `paste`
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
is the first tested upstream line that clears those findings, and it declares
Rust 1.88.0. That established the previous compatibility floor.
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:
```console
cargo +1.91.0 check --locked --all-targets --all-features
```
The normal CI jobs use current stable Rust, while the MSRV job prevents source
or dependency changes from silently raising the floor. `.cargo/config.toml`
asks modern Cargo to prefer dependency releases compatible with the declared
MSRV when the lockfile is deliberately refreshed.
## Reproducible dependency graph
`Cargo.lock` is tracked because tiny-wb is an executable. All CI compilation,
test, Clippy, and release-build commands use `--locked`; an uncommitted
resolution change is therefore a CI error. Do not update dependencies by
deleting the lockfile casually. After an intentional update, rerun every gate
in this document and review the lockfile diff.
Unused direct dependencies were removed while establishing the lock:
`clap`, `once_cell`, `ratatui-splash-screen`, and `tui-textarea`. Removing them
reduces download/build surface and makes policy results describe code that the
application actually uses. The acquisition refactor also removed direct
`packed_struct` and `memchr` dependencies: standard-library little-endian
decoding and buffered framing now provide those functions.
## Pinned policy tools
CI pins:
| Tool | Version | CI command |
| --- | ---: | --- |
| `cargo-audit` | 0.22.2 | `cargo audit --deny warnings` |
| `cargo-deny` | 0.20.2 | `cargo deny check` |
The setup stage checks the installed version and installs only when it does not
match exactly:
```console
cargo install --locked --version 0.22.2 cargo-audit
cargo install --locked --version 0.20.2 cargo-deny
```
Installing the tools and running both gates requires network access. The audit
jobs must refresh advisory and registry information; CI must fail rather than
silently using a stale or unavailable database.
## RustSec audit policy
`cargo audit --deny warnings` evaluates the complete tracked lockfile against
the current RustSec database and crates.io yanked status. Warnings such as
unmaintained or unsound advisories are promoted to failures, as are
vulnerabilities, yanked packages, database refresh failures, and tool errors.
There are no advisory ignores. If a future finding has no upgrade path, adding
an ignore requires an explicit maintainer decision documenting why tiny-wb is
unaffected and the condition that will remove the ignore.
`cargo-audit` is dependency/advisory matching. It does not prove exploit
reachability, review application logic, scan native system libraries, or
replace timely dependency maintenance.
## Dependency policy
`deny.toml` is evaluated with all features and enforces:
- license confidence of 0.8;
- only licenses currently needed by the resolved graph: Apache-2.0, MIT,
MPL-2.0, Unicode-3.0, and Zlib;
- denial of wildcard dependency requirements;
- warnings for duplicate crate versions;
- denial of unknown registries and Git sources;
- crates.io as the only allowed registry and no allowed Git sources;
- RustSec advisory checks with no ignores;
- empty crate bans, duplicate skips, license exceptions, and license
clarifications.
The MPL-2.0 allowance is needed by `serialport`. It is a graph-wide allowed
license, not an exception for one crate.
Duplicate warnings remain visible. The reviewed graph currently contains
transitive version splits for `bitflags`, `hashbrown`, `syn`, `toml`,
`toml_edit`, `windows-sys`, and `winnow`. They come from incompatible upstream
constraints in the serial, Ratatui, packed-struct, TOML, and Windows build
paths. No `skip` entries hide them. Direct `strum` and `thiserror` versions were
aligned with the graph where the duplicates were avoidable.
`cargo-deny` relies on package metadata and configured source URLs. It does not
perform source-code review, establish legal advice, verify downloaded artifact
provenance, or find vulnerabilities outside its advisory check.
## Local verification
Run from the repository root, in this order:
```console
cargo audit --deny warnings
cargo deny check
cargo fmt --all -- --check
cargo +1.91.0 check --locked --all-targets --all-features
cargo check --locked --all-targets --all-features
cargo test --locked --all-targets --all-features
cargo test --locked --no-default-features --lib
cargo check --locked --no-default-features --features serial --lib
cargo test --locked --no-default-features --features mock --lib --test mock_device
cargo test --locked --doc --all-features
RUSTDOCFLAGS="-D warnings" cargo doc --locked --no-deps --all-features
cargo clippy --locked --all-targets --all-features -- -D warnings
cargo build --locked --release --all-features
```
The first two commands require the network. Duplicate-version warnings from
`cargo deny check` are expected to stay visible and should be reviewed whenever
the graph changes.
## Scope limit
This is intentionally “semi-hardened” CI. The repository does not add
`cargo-vet`, SBOM generation, dependency vendoring, registry proxies,
provenance/signing systems, or additional security scanners. Expanding that
scope needs a separate design and maintenance decision.
## CI badges and coverage
The README references version, tests and line coverage at these mutable URLs:
- https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/version.svg
- https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/test.svg
- https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/coverage.svg
Repository identity and `main` were verified against the origin remote, its
HEAD, and Gitea repository metadata. The version comes from `Cargo.toml` via
`cargo metadata --no-deps --locked --format-version 1`, never a Jenkins constant.
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:
```console
rustup component add llvm-tools-preview
cargo install --locked --version 0.9.1 cargo-llvm-cov
mkdir -p coverage
cargo coverage
```
The exact alias is tracked in `.cargo/config.toml` and expands to:
```console
cargo llvm-cov --locked --all-targets --all-features --ignore-filename-regex /registry/src/ --json --summary-only --fail-under-lines 85 --output-path coverage/summary.json
```
The enforced line-coverage floor is **85%**, measured across the library and
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
tests, plus separately run Rustdoc examples. Tests
cover configuration, protocol, transport, acquisition, export, UI, startup and
mock device behavior. The floor leaves headroom for platform differences; it is
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
percentage from temporary `coverage/summary.json`, renders the coverage badge,
and deletes the summary, including on failure. Jenkins then creates the current
build's test and coverage markers only after unit/integration tests, Rustdoc tests, and the coverage test run succeed.
The release smoke test remains a nonfatal diagnostic.
The collector removes any stale summary before running Cargo and displays only
`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
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
runs never render a successful coverage badge.
The FreeBSD Jenkins report supplied on 2026-10-05 included 932 crates.io
source files alongside tiny-wb's 14 source files: 12,243/144,250 covered lines
(**8.49%**) overall, versus 1,852/2,038 (**90.87%**) for tiny-wb alone.
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
filter missed these paths. The alias explicitly filters
`/registry/src/` paths so dependency caches are excluded regardless of their
home directory. At that time, all tiny-wb production sources and the **85%** floor
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
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>()`,
compatible with the then-declared Rust 1.88 MSRV. Its exact frame-length validation
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.
In `post { cleanup { ... } }`, it uses only current-build markers to choose test
status and retain measured coverage, falling back to `failing` and neutral `-%`
when markers are absent. Cleanup reads the version, removes the summary and
markers, validates and archives exactly `coverage/version.svg`,
`coverage/test.svg` and `coverage/coverage.svg` with fingerprints and
`allowEmptyArchive: false`. A later lint/build failure can retain successful
test/coverage results; these badges report those individual stages.
Only `main` publishes to `/mnt/assets/coverage/idle-org/tiny-wb/main/`, with
`/mnt/assets/coverage` passed as the complete publication root. Publication
runs in cleanup even after failure. Each file is replaced atomically, with
0755 new directories and 0644 files; the script never prunes shared assets.
Concurrent builds of this job are disabled to avoid workspace/marker races.
The publication predicate requires a Jenkins **multibranch** job's `BRANCH_NAME`
and excludes change requests and tags. The actual job configuration is not in
this repository and remains unverified. When `BRANCH_NAME` is absent,
publication is skipped with a diagnostic; generation and archival still run.
Verify the job type and its branch variable before deployment. Real Jenkins
execution and access to the asset mount remain external deployment checkpoints.
The three public URLs were retrieved on 2026-10-05. Each returned HTTP 200 with
`image/svg+xml` content and parsed as XML. Their accessible labels reported
version 0.1.1, tests passing, and 90% coverage; the version matched
`Cargo.toml` as it stood at the time of the check. This confirms that the
publication endpoint is live, but does not independently verify the external
Jenkins job configuration or the freshness of its most recent build.
Server configuration is external: mount public assets read-only, disable
directory listing, serve SVG with a restrictive Content-Security-Policy, and
revalidate mutable URLs or give them a short cache lifetime.
Run isolated badge checks with `python3 scripts/test-badges.py`. The renderer
was copied from `Dandaedre/agent-tasks` at revision
`fb9d8f7d16f100c2d1377f23394a2302eac9ab18` (retrieved 2026-10-04), with local
fixes for literal newlines in width measurement, oversized integer validation,
unique temporary files, directory-output rejection and signal termination.
The library feature matrix runs before coverage markers are issued. Mock tests
require localhost listener permission and never connect to physical hardware.

86
docs/sources.md Normal file
View File

@ -0,0 +1,86 @@
# Upstream source catalogue
This catalogue records the authoritative references used to build the local
guide. The catalogue was checked on **2026-10-04**; the protocol and Ultra-support
pages record their targeted **2026-10-05** source review. Prefer these primary sources over
retailer listings, reposted manuals, videos, and forum recollections.
## Official overview and model data
- [tinySA official wiki home](https://www.tinysa.org/wiki/) — product-family
overview and navigation.
- [Model comparison](https://www.tinysa.org/wiki/pmwiki.php?n=TinySA4.Comparison)
— identify ZS405/ZS406/ZS407 and compare frequency, LNA, RBW, scan, generator,
storage, and phase-noise capabilities.
- [tinySA Basic specification](https://tinysa.org/wiki/pmwiki.php?n=Main.Specification)
— low/high input and output paths, level limits, filters, speed, and battery.
- [tinySA Ultra/Ultra+ specification](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Specification)
— analyzer/generator ranges, attenuation, LNA, filters, accuracy, and hardware
revisions.
## Architecture, limitations, and operation
- [Ultra technical description](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.TechnicalDescription)
— mixer, IF, filter, detector, generator, and calibration-source signal paths.
- [Ultra mode](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Ultra) — low-pass
bypass, mirror/spur elimination, sensitivity and bandwidth limitations, LO
leakage, and unlock behavior.
- [Ultra limitations](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Limitations)
— RBW, speed, images, low-frequency sensitivity, LNA overload, and 48 MHz MCU
radiation.
- [Ultra menu tree](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.MenuTree) —
front-panel settings, presets, SD, sweep controls, calibration, expert
settings, and generator modes.
- [Ultra best-performance settings](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.BestSettings)
— recommended automatic expert controls and cautions.
- [RBW](https://tinysa.org/wiki/pmwiki.php?n=Main.RBW) — coverage, noise-floor,
resolution, and sweep-time trade-offs.
- [Attenuation](https://www.tinysa.org/wiki/pmwiki.php?n=Main.ATTENUATION) —
protection and overload/spur diagnosis.
## Safety, first use, and maintenance
- [Safe operation](https://tinysa.org/wiki/pmwiki.php?n=Main.SafeOperation) —
current DC-block, transmitter attenuation, and static precautions.
- [First use](https://tinysa.org/wiki/pmwiki.php?n=Main.FirstUse) — charging,
authenticity, self-test, calibration, and connection warnings.
- [Safe transmitter measurement](https://tinysa.org/wiki/pmwiki.php?n=Main.Transmitters)
— dBm examples and external attenuation strategy.
- [Firmware update](https://tinysa.org/wiki/pmwiki.php?n=Main.UpdatingTheFirmware)
— correct download trees, DFU tools/modes, recovery, and post-update steps.
- [Ultra battery guidance](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Battery)
— charging current and the voltage needed for best RF performance.
## USB protocol and firmware implementation
- [Official USB interface](https://tinysa.org/wiki/pmwiki.php?n=Main.USBInterface)
— console syntax, command descriptions, `scan`, `scanraw`, framing, options,
and documented raw offsets.
- [Ultra console command example](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.ConsoleCommands)
— Ultra build command inventory and example outputs; treat it as a snapshot,
not a promise for every firmware.
- [Upstream tinySA firmware repository](https://github.com/Ho-Ro/tinySA) —
implementation authority for a matching firmware revision.
- [`sa_cmd.c` raw source](https://raw.githubusercontent.com/Ho-Ro/tinySA/main/sa_cmd.c)
— mode parsing, `zero`, RBW, Ultra commands, and exact `scanraw` byte order and
step calculation.
- [`main.c` raw source](https://raw.githubusercontent.com/Ho-Ro/tinySA/main/main.c)
— shell command registration, prompt behavior context, and build-conditional
command availability.
## Source-conflict policy
When sources disagree:
1. protect hardware using the most conservative official safety value;
2. use the comparison/specification page for the exact physical revision;
3. use on-device `version`, `info`, and `help` for the installed build;
4. use source at the matching firmware revision for byte-level behavior;
5. verify ambiguous scan semantics with a low-level known signal and preserve
the transcript as a regression fixture.
The local docs intentionally record two known conflicts: the wiki's textual
“MSB LSB” description versus firmware's little-endian byte writes, and
endpoint-inclusive intuition versus the reviewed firmware's integer-divided,
single-precision `scanraw` step. Both are explained in
[the protocol guide](usb-protocol.md).

77
docs/testing.md Normal file
View File

@ -0,0 +1,77 @@
# Testing without a tinySA
The library exposes configuration, protocol, transport, acquisition and CSV
boundaries independently of the terminal. Tests use small synthetic byte
transcripts rather than opening a serial device. They are regression checks,
not proof of behavior on a particular model or firmware.
```console
cargo test --locked --all-targets --all-features
cargo test --locked --doc
```
| Boundary | Regression cases |
| --- | --- |
| 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. |
| 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, 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. |
| 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. |
| 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
reader and capture its writes; vary read chunk size so a token may cross any
read boundary. Test both expected output and error behavior. Keep command side
effects outside logging macros because disabled log levels do not evaluate
format arguments.
`decode_frame` receives exactly the framed body (`{`, records, `}`), without
shell echo or prompt. Use raw bytes in tests: converting binary through UTF-8
can destroy the failure being reproduced. Check every truncated prefix when a
parser changes, and include payload bytes that equal framing characters.
`write_csv` accepts a writer; use an in-memory vector or a writer that fails
partway through. Filesystem tests use separate temporary directories and clean
up after themselves. They must never write shared public assets.
Run the coverage alias and badge tests as described in
[security and CI](security-and-ci.md). Keep the minimum tied to an actual
measurement over production code. Report test counts and hardware limitations
alongside percentages; a high line percentage does not test RF correctness.
Hardware validation still requires a known model/version, safe RF input, and a
bounded capture of the real command/response sequence. In particular, verify
frequency-axis policy, the legacy preparatory scan, zero-offset acceptance and
resume behavior against the connected firmware before changing their defaults.
Use the guided [Basic and Ultra hardware checklist](hardware-validation.md) to
produce CSV and identity evidence without connecting an RF source. Its Ultra
case intentionally stays below 350 MHz and does not certify extended ranges.
## Library feature matrix and mock integration
```console
cargo test --locked --no-default-features --lib
cargo check --locked --no-default-features --features serial --lib
cargo test --locked --no-default-features --features mock --lib --test mock_device
```
The mock suite includes real loopback sockets, so the test environment must
permit localhost listeners. Tests use ephemeral ports, bounded socket timeouts
and fresh sessions. See [mock scope and faults](mock-device.md). No mock result
certifies device command compatibility or RF accuracy. Full hardware acceptance
is tracked in the [roadmap](roadmap.md).
Standalone example CLI and socket smoke test:
```console
cargo build --locked --no-default-features --features mock --example mock-tinysa-server
python3 scripts/test-mock-server.py
```
With a custom `CARGO_TARGET_DIR`, pass its `debug/examples/mock-tinysa-server`
executable path to the script (append `.exe` on Windows). This checks argument
validation, dynamic-port binding, identity, binary scans and `--once` shutdown.
Local Linux validation on 2026-10-04 passed; Windows/macOS runtime, actual
hardware and Jenkins execution remain separate unverified acceptance checks.

357
docs/tiny-wb-operations.md Normal file
View File

@ -0,0 +1,357 @@
# tiny-wb compatibility and operations
This guide describes the application as it exists today. It is intentionally
more conservative than “the firmware probably accepts it”: a range is called
supported only when tiny-wb selects the right path, decodes it knowingly, and
can represent it in the UI.
## Compatibility matrix
| Instrument/use | Status | Reason |
| --- | --- | --- |
| tinySA Basic low input, range wholly below 350 MHz | Best-supported path | The client sends `mode low input`, uses the Basic-oriented range, and normalizes raw samples with `zero 128`. |
| tinySA Basic high input, range wholly from 350 to 960 MHz | Implemented | The client sends `mode high input`; the RF path itself is less accurate and more overload-prone than low input. |
| 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. |
| tinySA Ultra/Ultra+ 0.1–800 MHz | Implemented; awaiting hardware qualification | Family detection, `mode low input`, automatic `zero 174` and readback verification. |
| 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. |
| 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:
low accepts frequencies strictly below 350 MHz, while high accepts 350 MHz
through 960 MHz. A scan from 0 to exactly 350 MHz is rejected, but a scan from
240 to 350 MHz is assigned to the high path.
## Required equipment
- A genuine, powered tinySA Basic for the currently supported workflow.
- A data-capable USB cable. Charge-only cables do not enumerate a serial port.
- A host with permission to open the USB serial device.
- For conducted RF measurements: known-good 50-ohm coax/adapters, correctly
rated fixed attenuation, and a DC block when needed.
- For transmitter work: a suitable dummy load or sampler and power-rated
attenuation. Read the [safe-operation guide](tinysa-field-guide.md#safe-operation-read-before-connecting-a-signal)
before connecting a source.
Do initial software/serial testing with no external RF source connected. This
separates communications failures from unsafe or overloaded RF setups.
## Build and launch
Use a current stable Rust toolchain:
```console
cargo build --release
./target/release/tiny-wb
```
With no arguments the program starts the acquisition workflow. To inspect a
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).
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
On Linux, identify the device after plugging it in:
```console
ls -l /dev/ttyACM*
```
The exact permission mechanism is distribution-specific (often a `dialout` or
`uucp` group, or a udev rule). Do not solve it by running the RF application as
root when a scoped device permission is available.
On Windows, use Device Manager to find the COM port. Close serial terminals and
other tinySA applications before launching tiny-wb; only one process can
normally own the port.
## User interface
### Connection screen
The application enumerates ports at startup. Selection priority is:
1. the port saved in `config.toml`, if present;
2. the configured `serial.preferred_ports` (by default `/dev/ttyACM0`, `COM3`, `COM5`, `/dev/ttyS16`);
3. the first enumerated port.
Default baud choices range from 19,200 to 3,000,000, with 115,200 selected.
`serial.baudrates` defines the choices; the selected rate must belong to that
list. No available ports produces an actionable error rather than an index panic.
### Scan screen
The embedded defaults are shown below. Steps and sample/repeat bounds are
configurable; Basic frequency limits remain fixed protocol rules.
| Field | Unit | Default | Step | Bounds |
| --- | --- | ---: | ---: | ---: |
| Start frequency | MHz | 240 | 10 | 0–5,400 (model checked after identity) |
| Stop frequency | MHz | 800 | 10 | 10–5,400 (model checked after identity) |
| Points | samples | 10,001 | 100 | 101–1,000,001 |
| Repeat | measurements/point | 1 | 1 | 1–1,000 |
Left/right or `h`/`l` changes the selected field. Up/down or `k`/`j` changes
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
depends on RBW and instrument mode; the progress bar is based mainly on bytes
received, not a predictive time estimate.
### Progress and result
The scan runs on a worker thread while the UI displays shared progress and the
concatenated `version`/`info` response. On success, the final screen plots a
scatter trace. Its Y axis defaults to −128–0 dBm and uses the configured `ui.chart_min_dbm`
and `ui.chart_max_dbm` bounds. Values outside those bounds are clipped visually
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
### `config.toml`
The current selection is saved before acquisition starts:
```toml
port = "/dev/ttyACM0"
baudrate = 115200
start_frequency = 240
stop_frequency = 960
points = 10001
repeat = 1
```
Frequencies in this file are MHz, unlike protocol frequencies (Hz). Saving a selection atomically replaces this file while preserving every
recognized settings section. Missing files use embedded defaults; malformed,
unknown or invalid settings are reported before terminal startup. Override the
path with `TINY_WB_CONFIG`. See [configuration](configuration.md) for the schema.
### CSV
By default the scanner writes `scan_YYYYMMDD HH_MM_SS_microseconds_counter.csv`
in the working directory. The directory and filename prefix are configurable;
exclusive creation prevents overwriting earlier scans. The default has no header:
```csv
240,-92.4375
240.072,-91.96875
```
Column one is MHz and column two is dBm. The file is created only after complete frame validation and a successful
resume response. Failed writes are reported and incomplete files are removed
when possible. Enable `output.include_header` for named columns. Choose the
frequency-label convention explicitly after reviewing the
[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
`flexi_logger` uses `logging.filter` and `logging.directory`; defaults are
`info` and the working directory. The filter also applies in release builds. Logs
can contain instrument version/configuration details and port names. Attach the
relevant bounded excerpt—not an uncontrolled archive—when reporting a bug.
## Instrument state changed by a run
tiny-wb changes repeat count, raw zero offset, input mode, display sweep start
and stop, and pause/resume state. By default it also runs the legacy auxiliary textual scan before
the raw scan; `scan.legacy_pre_scan` can disable it after hardware validation. It does not snapshot and restore previous values. If preserving a
carefully tuned front-panel configuration matters, save it as an instrument
preset and reload it after tiny-wb exits.
After attempting `pause`, acquisition always attempts `resume`, including on
frame or I/O errors. This is best-effort recovery, not confirmation that a
disconnected device resumed or that its previous settings were restored. Quitting
during acquisition can still terminate the worker before recovery. Send `resume`, use the UI, or
power-cycle/reload a preset after making the RF setup safe.
## Troubleshooting
### No serial port is listed
- Confirm the device is powered on and the cable supports data.
- Try a direct USB port or known USB 2.0 hub/cable.
- Check OS device enumeration before debugging tiny-wb.
- On Linux, inspect `/dev/ttyACM*` and kernel logs; on Windows, Device Manager.
### Port cannot be opened
- Close other serial terminals and tinySA software.
- Check the selected COM/TTY name and user permissions.
- Unplug/reconnect if the device was just in DFU mode; DFU and CDC serial are
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
- Verify the selected port is the tinySA, not another CDC device.
- Wake/power the instrument and close auto-refreshing software.
- Manually send `version` in a serial terminal and confirm a `ch>` prompt.
- Record firmware version. The client relies on prompt timing and may fail on a
slow command when the configured read timeout is too short. Fragmented prompts
are handled by the buffered transport.
### Parse beginning/end/alignment error
- Reduce point count and repeat to minimize transfer time.
- Disable any other process reading the port.
- Ensure the firmware implements the documented `scanraw` framing.
- Preserve a raw byte capture if possible. Do not convert it through UTF-8.
- The decoder now rejects truncated, extra, misaligned and unterminated records.
Preserve the exact requested point count and firmware version with the capture.
### Trace is shifted in frequency
The default `firmware` labeling reproduces the reviewed `scanraw` integer and
single-precision arithmetic. If a saved configuration selects `inclusive`, it
uses `points - 1` intervals and can shift later labels by nearly one firmware
step. Remove that override or choose `scan.frequency_axis = "firmware"`, then
verify with a known narrow carrier and record the firmware version. The setting
changes CSV/chart labels; it does not change the instrument request or calibrate
the analyzer.
### Levels are wrong by about 46 dB
That is the difference between Ultra's documented default raw offset (174) and
Basic's (128). The application and hardware validator now select the detected
family's native offset automatically and verify its readback. A 46 dB shift
suggests that the configured command/decoder offset does not match the firmware
value. Stop treating the result as calibrated data and capture `version`,
`info`, and the `zero` command response. This bias is numeric encoding, not
model-specific record padding.
### Unexpected harmonics or spurs
Assume overload or an image until disproved. Add attenuation, reduce span,
change RBW, use a filter/preselector, and compare paths where possible. Consult
the [measurement controls](tinysa-field-guide.md#measurement-controls-and-trade-offs).
## Reproducible bug report checklist
Include:
- tiny-wb commit hash shown in the title;
- host OS and serial port type;
- exact tinySA model/rear label;
- `version`, `info`, and relevant `help` output;
- start/stop, points, repeat, and selected baud;
- RF setup, attenuation, DC block, expected maximum level, RBW, LNA, and Ultra
mode state where relevant;
- the smallest CSV/log excerpt that demonstrates the problem;
- whether the front panel was paused and whether `resume` recovered it.
Never include a dangerous live-transmitter reproduction just to demonstrate a
software bug; substitute a low-level known source or recorded serial fixture.
## Remaining engineering work
ZS407 extended detection, harmonic ranges above 5.4 GHz, overall
transaction deadlines, cancellation/abort, full instrument-state restoration,
and richer output metadata remain open. Buffered framing, strict record-count
validation, reusable core interfaces and hardware-free regression tests are
implemented. Real Basic/Ultra transcript fixtures and hardware checks are still
needed; see [architecture](architecture.md#extension-points-and-remaining-limits).
## Hardware-free operation
Use the [mock server](mock-device.md) with the TCP connection backend to run
the normal acquisition and CSV workflow without USB hardware. The production
app supports the common Ultra normal range; see [support scope](ultra-support.md).

314
docs/tinysa-field-guide.md Normal file
View File

@ -0,0 +1,314 @@
# tinySA and tinySA Ultra field guide
This is the instrument-side reference for tiny-wb maintainers and users. It
summarizes the official documentation needed to identify, protect, configure,
and interpret the supported hardware. It does not replace the safety labels on
the device, and limits are not targets.
## Names and model identification
The product name is **tinySA** (tiny spectrum analyzer). The larger device is
**tinySA Ultra**—not “tinySAultra”—and newer variants are **tinySA Ultra+**.
Firmware and source code often use hardware-family names:
| Product | How to identify it | Firmware/source shorthand |
| --- | --- | --- |
| tinySA Basic | 2.8-inch, 320×240 display; separate `LOW` and `HIGH` SMA ports | tinySA / `TINYSA3` |
| tinySA Ultra ZS405 | Front says `Ultra`; 4-inch, 480×320 display | tinySA4 / `TINYSA4` |
| tinySA Ultra+ ZS406 | Front says `Ultra+`; rear label says ZS406 | tinySA4 / `TINYSA4` |
| tinySA Ultra+ ZS407 | Front says `Ultra+`; rear label says ZS407 | tinySA4 / `TINYSA4` |
“Ultra mode” is also the name of a high-frequency measurement mode on Ultra
hardware. Do not confuse the physical Ultra model with whether Ultra mode is
currently enabled.
Counterfeits exist. Prefer the sellers listed by the official project. The
official first-use guidance recommends authentic firmware and the built-in
self-test as checks; a clone can be electrically unsafe or behave differently
at the console.
## What the instrument is
A tinySA is a swept, scalar spectrum analyzer and a signal generator. In
analyzer mode it steps a local oscillator across a range, passes the selected
mixing product through a resolution filter, measures power, and reports level
at each step. It measures magnitude versus frequency, not phase, and it is not
a real-time analyzer. Signals shorter than the time spent away from their
frequency may be missed.
In generator mode the RF path is reconfigured to produce an output. Never
assume an SMA connector is an input merely because it was one earlier: confirm
the mode before connecting a device under test.
## Model capability summary
Values below summarize the official model comparison and specification pages.
Some limits depend on firmware, mode, frequency, attenuation, LNA state, and
hardware revision.
| Capability | Basic | Ultra ZS405 | Ultra+ ZS406 | Ultra+ ZS407 |
| --- | --- | --- | --- | --- |
| Display | 2.8 in, 320×240 | 4 in, 480×320 | same | same |
| Normal analyzer range | low 100 kHz–350 MHz; high 240–960 MHz | 100 kHz–800 MHz | 100 kHz–900 MHz | 100 kHz–900 MHz |
| Extended analyzer range | none | Ultra mode to about 5.3 GHz; calibrated to 6 GHz | Ultra mode to about 5.4 GHz; calibrated to 6 GHz | Ultra mode and calibrated range to 7.3 GHz |
| Harmonic observation | none | about 10 GHz | about 10 GHz | about 11 GHz |
| RBW selections | roughly 3–600 kHz | 0.2–850 kHz | same | same |
| Maximum displayed points | 290 | 450 | 450 | 450 |
| Step attenuator | 0–31 dB on low path | 0–31 dB when LNA is off | same | same |
| Internal LNA | none on standard low path | nominal 20 dB to 4 GHz | same | 20 dB to 7.3 GHz, about 15 dB to 9 GHz |
| Sine generator | 100 kHz–350 MHz | 100 kHz–800 MHz | 100 kHz–900 MHz | 100 kHz–900 MHz |
| Higher-frequency generator | square 240–960 MHz | square to 4.4 GHz / RF test to 5.3 GHz | square to 4.4 GHz / RF test to 5.4 GHz | square around 6 GHz / RF test to 7.3 GHz |
| Storage/audio | no microSD; audio requires modification | microSD up to 32 GB; headphone output | same | same |
The official Ultra specification lists ±2 dB absolute level accuracy after
level calibration over its main calibrated region, detector resolution of
0.5 dB, more than 1,000 points/s with the widest filters, and selectable
200 Hz, 1, 3, 10, 30, 100, 300, 600, and 850 kHz filters. Those headline values
do not mean every signal at every frequency is measured to ±2 dB: mismatch,
compression, images, correction tables, RBW, battery voltage, and Ultra-mode
limitations still apply.
## RF architecture
### tinySA Basic
The Basic exposes two distinct bidirectional RF ports and four broad modes:
- **Low input:** the higher-quality 100 kHz–350 MHz analyzer path with a
0–31 dB step attenuator and input filtering.
- **High input:** a 240–960 MHz path with frequency-dependent impedance, no
input band filter, no adjustable step attenuator, lower intercept point, and
greater susceptibility to overload, images, and out-of-band signals.
- **Low output:** a filtered sine source over roughly 100 kHz–350 MHz.
- **High output:** a square-wave source over roughly 240–960 MHz.
The 240–350 MHz overlap is useful: compare paths when a result is suspicious.
The low path is generally preferable where it covers the frequency.
### tinySA Ultra and Ultra+
Ultra uses one main RF SMA path and a separate calibration/output connector.
In analyzer mode the signal path is conceptually:
```text
RF SMA
-> select LNA or 0–31 dB attenuator
-> select 800 MHz low-pass filter, bypass, or direct path
-> swept first LO + mixer
-> ~980 MHz high-IF band-pass filter
-> receiver / second mixer
-> ~870 kHz low IF
-> selectable RBW filter
-> power detector
```
The low-pass filter suppresses aliases in the normal range. In Ultra mode it
is bypassed above its useful passband, allowing higher-frequency mixing but
also allowing many more images and spurs. Firmware makes multiple measurements
with shifted conditions to reject candidates that do not behave like a real
input signal.
In generator mode a nominal 980 MHz source, filter/mixer network, switching,
and attenuation are reused to create the requested output. Above the normal
sine range the user trades spectral cleanliness, frequency granularity, level
accuracy, and maximum frequency between “cleanest” square-wave and “highest
accuracy” RF-test modes.
The CAL source derives 30, 15, 10, 4, 3, 2, or 1 MHz from a temperature-
controlled 30 MHz oscillator. It is a useful internal reference, not a general
laboratory-grade calibrated generator across the analyzer's entire range.
## Ultra mode and harmonic mode
Ultra mode bypasses the input low-pass filter when needed and applies a
multi-measurement mirror/spur-removal algorithm. On the ZS405, the filter is
normally retained below roughly 750 MHz. Above that point scans slow down.
It works best for stable, narrowband signals. Important failure modes are:
- short bursts may be absent because repeated observations do not coincide;
- swept or hopping signals may be rejected or placed incorrectly;
- complex or wideband signals (official guidance flags roughly 600 kHz–1 MHz
width, depending on the page/firmware) can create false results;
- sensitivity deteriorates with frequency;
- bypassing the filter increases LO leakage at the RF connector, reported as
high as approximately −10 dBm;
- results beyond the level-calibrated range lack trustworthy
frequency-dependent amplitude correction.
A band-limited antenna or external preselector can reject unwanted mixing
products before they enter the analyzer. This is often better than asking the
algorithm to disambiguate every possible image.
Harmonic mode extends observation beyond the calibrated Ultra range by mixing
on a selected LO harmonic. Treat it as signal discovery, not calibrated level
metrology. The official best-settings guidance says harmonic selection should
normally remain at 3 and key expert settings should remain automatic.
## Safe operation: read before connecting a signal
Absolute maximum ratings prevent immediate damage; they do not guarantee
linearity or accurate measurement. Use the most conservative applicable limit.
### Core rules
- Keep Ultra/Ultra+ below **+6 dBm at 0 dB internal attenuation**. Basic's
published absolute RF limit at 0 dB attenuation is **+10 dBm**. The official
recommendation for automatic attenuation is no more than **0 dBm**, and best
accuracy is generally obtained with signal level below about **−25 dBm** at
the analyzer input stage.
- The latest official safe-operation table says to use a **DC block plus at
least 3 dB external attenuation above 5 V DC offset**. When the DC content is
unknown, use a suitably rated DC block.
- Do not trust the internal attenuator as the sole protection from a powerful
source. Place external attenuation directly at the analyzer so a failed
cable or incorrect mode cannot expose the input.
- Never connect a transmitter directly. The official minimum examples are
40 dB attenuation for 1 W, 50 dB for 10 W, and 60 dB for 100 W. Real setups
must also account for peak/envelope power, attenuator power rating, mismatch,
transients, and harmonics.
- Avoid the supplied telescopic antenna where static discharge or a nearby
transmitter is possible. Do not touch objects with it.
- After Basic self-test/calibration, disconnect the cable between LOW and HIGH
before enabling an output. Driving a connected input can destroy the input
attenuator.
- Confirm whether the RF port is in analyzer or generator mode before every
connection change.
### A practical transmitter setup
Use a rated dummy load or directional/attenuating sampler, followed by
power-rated coarse attenuation, then a sacrificial fixed attenuator (the
official example uses 30 dB) immediately at the tinySA. Calculate the expected
level in dBm and leave margin for modulation peaks. For harmonic measurements,
an external high-pass/low-pass/band-pass filter may be required to prevent the
fundamental from generating analyzer distortion that looks like DUT harmonics.
## Measurement controls and trade-offs
### Frequency span and sample points
Displayed or requested points are not identical to analog resolution. Point
spacing is approximately span divided by the number of intervals. Firmware may
insert hidden measurements so the RBW covers the span without gaps. More
points improve trace sampling but increase time and do not substitute for a
narrower RBW.
### Resolution bandwidth (RBW)
RBW is the bandwidth of the measurement filter:
- narrower RBW separates nearby carriers and lowers displayed noise;
- narrower RBW takes longer, particularly below 30 kHz;
- wider RBW scans quickly and captures more energy from modulated signals, but
merges close signals and raises the displayed noise floor.
Auto RBW is a good default. A wide span with a narrow fixed RBW can take a very
long time because firmware adds steps to maintain coverage.
### Attenuation and overload diagnosis
Internal attenuation trades sensitivity for headroom. Automatic mode aims to
keep the strongest signal at a safe internal level. To test whether a harmonic
or spur is generated inside the analyzer, increase external or internal
attenuation:
- a real input signal, after compensation, should remain near the same
reported level;
- an internally generated intermodulation product often falls or disappears
disproportionately;
- the noise floor rises because attenuation reduces signal before the
receiver.
The Basic high path has no normal adjustable attenuator and is easy to
overload. Strong out-of-band signals also reach it because it lacks an input
band filter.
### LNA
Ultra's LNA improves sensitivity for weak signals but disables the step
attenuator and greatly reduces overload headroom. Do not enable it around
unknown or strong signals. The model comparison reports a roughly −26.5 dBm
1 dB compression level with the LNA on for the ZS405, versus about +0.5 dBm
with it off. If a trace changes unexpectedly when the LNA is toggled, suspect
compression or intermodulation before assuming a real RF change.
### Repeat and averaging
The `repeat` console setting takes multiple measurements at each frequency and
reduces random noise at the cost of proportional scan time. Trace calculations
such as min hold, max hold, and averaging are separate firmware features. For
bursty signals, max hold across repeated sweeps is often more informative than
per-point averaging.
### Spur and image checks
When a line is questionable:
1. change attenuation and see whether its corrected amplitude behaves like the
wanted signal;
2. change span/RBW and repeat the sweep;
3. switch the Basic path in the overlap region or use below/above-IF controls;
4. enable automatic spur removal;
5. add an external preselector or filter;
6. compare against a known source or another analyzer.
Remember that the instrument's own 48 MHz MCU clock and harmonics can be
visible, especially with an antenna or low RBW.
## First use, calibration, and health checks
1. Charge the device. Ultra RF performance can degrade at low supply voltage;
official guidance recommends more than 3.9 V for best performance.
2. Record the hardware label and current `version`/`info` output.
3. If updating firmware, first run the self-test so pre-existing damage is not
confused with an update problem.
4. For the Basic self-test, connect LOW and HIGH with the supplied SMA cable
and run `CONFIG -> SELF TEST`.
5. Perform input level calibration as directed by the on-device menu. Basic low
level calibration uses the two ports connected; high-path calibration is a
separate procedure. Ultra correction/calibration varies by range and model.
6. Disconnect any calibration loop before enabling generator output.
Calibration corrects systematic level error; it cannot remove front-end
overload, RF mismatch, an image, a damaged switch, insufficient shielding, or
an invalid Ultra-mode measurement.
## Firmware update and recovery
Use the firmware file for the exact family:
- Basic: the `tinySA/DFU` tree;
- Ultra/Ultra+: the `tinySA4/DFU` tree.
Do not flash a similarly named file from the other family. Configuration data
may be reset or become structurally incompatible, so record unusual correction
settings and expect to redo calibration when appropriate.
Ultra enters recovery/DFU mode by holding the jog control while powering on;
the screen remains black. The Basic normally enters DFU from its menu, with a
documented PCB BOOT0 recovery procedure if an update is interrupted. The
official guide supports `dfu-util` and vendor tools. After updating, power-cycle
the unit, verify normal USB serial enumeration, check the version, clear stale
configuration when advised, and rerun self-test.
## Settings baseline for Ultra
For general use, leave these expert controls automatic unless a documented
experiment requires otherwise: spur removal, IF frequency, mixer drive, scan
speed, and below-IF choice. Keep harmonic at 3. The official best-settings page
also warns against casual AGC/LNA expert changes and against its then-current
FAST sweep mode. Because firmware evolves, confirm that advice against the
version installed on the instrument.
## How this maps to tiny-wb
tiny-wb detects Basic/Ultra families and applies model-specific input commands
and native encoding offsets. Generic Ultra support covers 0.1–800 MHz; a
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).
For the wire format and exact command behavior, continue with
[USB console and `scanraw` protocol](usb-protocol.md).

71
docs/ultra-support.md Normal file
View File

@ -0,0 +1,71 @@
# Basic and Ultra acquisition support
Implemented 2026-10-05; synthetic verification is separate from hardware qualification.
The acquisition path reads `version`, `info`, and `help` before changing scan
settings. Recognized Basic (`tinySA_v…`) and Ultra-family (`tinySA4_v…`) identities
select different plans. Unknown or conflicting identities fail. Explicit
`scan.device_model = "basic"` or `"ultra"` requires a matching detected family;
the default is `"auto"`. Explicit identity text also distinguishes ZS405,
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 |
| --- | --- | --- | --- |
| Basic | Existing low/high policy through 960 MHz | `mode low input` or `mode high input` | 128 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)
lists 800 MHz normal range for ZS405 and 900 MHz for Ultra+ revisions. ZS406 is
recognized only from explicit `ZS406` or `HW Version:V0.4.6` evidence. Above
900 MHz, `scan.enable_ultra_mode = true` is required; acquisition sends
`ultra on` and verifies that `sweep` reads back the requested boundaries. The
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)
documents the family version prefix and zero readback. The reviewed
[mode handler](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c)
accepts `mode low input` for Ultra. Sources checked 2026-10-05.
Required commands must appear in `help`. Optional diagnostics run only when
advertised. After setting the selected bias with `zero N`, acquisition queries
`zero` and requires a matching `NdBm` readback. A missing or mismatched readback
fails before scanning. The decoder uses this confirmed value. Both families
share the same binary record layout; see [protocol](usb-protocol.md).
## Configuration migration
New defaults select `device_model = "auto"`, `auto_zero_offset = true`, and
240–800 MHz, usable by both families. Saved frequencies remain unchanged;
an old 960 MHz stop is rejected on Ultra with an actionable range error.
To preserve a custom raw bias, set `auto_zero_offset = false` alongside the
existing `zero_offset` value. Previously saved offsets remain parseable but
are ignored while automatic selection is enabled. No configuration is rewritten
until the normal save workflow runs.
The terminal uses integer MHz inputs and a shared 5,400 MHz entry ceiling.
Model-specific validation runs after identification in the acquisition worker;
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
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
Regression tests cover model detection, conflicts, range/path selection,
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)
and `cargo coverage`. The hardware validator requires its selected family to
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.
The ZS406 normal and Ultra command paths were physically validated on 2026-10-07
with firmware `tinySA4_v1.4-197-gaa78ccc`; see
[hardware validation](hardware-validation.md#recorded-zs406-evidence). This is
not RF accuracy qualification. Generic Ultra-family variants still need their
own hardware runs, and Ultra RF level/frequency accuracy, Windows/macOS, Jenkins
and publication have not been verified for this change.

314
docs/usb-protocol.md Normal file
View File

@ -0,0 +1,314 @@
# USB console and `scanraw` protocol
This document is the implementation reference for talking to tinySA firmware.
It combines the official USB-interface description with the behavior visible
in the upstream C source and in `src/protocol.rs`, `src/transport.rs`, and `src/acquisition.rs`.
## Transport
Connecting a powered tinySA by a data-capable USB cable exposes a virtual
serial port (USB CDC): commonly `/dev/ttyACM*` on Linux and `COM*` on Windows.
Drivers are built into most Linux systems and are normally installed
automatically on Windows.
The on-device shell is a command stream, not a packet protocol:
- commands are ASCII and are normally terminated by carriage return (`\r`);
- terminal input is commonly echoed, so a reply can begin with the command;
- ordinary output is text;
- the ready prompt is `ch>`;
- some commands (`capture`, display bulk data, and `scanraw`) place binary data
in the same byte stream;
- firmware performs limited parameter validation, so a prompt does not prove
that the intended operation occurred.
The baud selector in tiny-wb controls how the host opens the serial device.
USB CDC and the optional internal TTL USART are different transports;
`usart_cfg` configures/reports the internal serial interface in firmware. Do
not infer the physical USB transfer speed from that value.
## Shell grammar
Common scalar syntax is:
- frequency: integer/floating value, optionally suffixed `k`, `M`, or `G`;
- level: floating-point dB/dBm value;
- time: seconds, optionally suffixed `m` (milliseconds) or `u`
(microseconds).
For software, plain integer Hz is the least ambiguous frequency representation.
Commands and availability vary by build; issue `help`, then record `version`
and `info` before relying on optional commands.
## Commands relevant to tiny-wb
| Command | Meaning and notes |
| --- | --- |
| `version` | Firmware version/build text. |
| `info` | Model/platform information when enabled in the build. |
| `help` | Commands compiled into this firmware. Prefer this over a hard-coded global list. |
| `mode low input` | Select Basic low input; on Ultra, firmware also accepts `mode input` and has no Basic high path. |
| `mode high input` | Select Basic high input. Not an Ultra input mode. |
| `pause` / `resume` | Stop/restart normal display sweeping. |
| `repeat 1..1000` | Measurements per frequency. More repeats reduce random noise and increase time. |
| `zero N` | Set the additive raw-sample encoding offset used by `scanraw`; not an RF zero/calibration operation. |
| `sweep start F`, `sweep stop F` | Change display sweep boundaries. `sweep` alone reports settings. |
| `scan START STOP [POINTS] [OUTMASK]` | Perform a scan with at most 290 points and optional textual output. Outmask bits are 1 frequencies, 2 measured data, and 4 stored data. |
| `scanraw START STOP [POINTS] [OPTIONS]` | Perform an arbitrary-point binary scan. Option bit 0 requests unbuffered writes; bit 1 repeats continuously. |
| `rbw auto` or `rbw VALUE` | Set resolution bandwidth in kHz in current firmware syntax. Valid ranges differ by model. |
| `attenuate auto` or `attenuate 0..31` | Select automatic/manual front-end attenuation where supported. |
| `spur off\|on[\|auto]` | Control spur removal; `auto` is Ultra-specific. |
| `lna off\|on` | Ultra optional LNA; reduces overload headroom and disables its step attenuator path. |
| `ultra off\|on\|auto\|start\|harm ...` | Ultra-family build only; control extended-frequency behavior. |
| `leveloffset`, `vbat`, `threads`, `usart_cfg`, `marker` | Diagnostic/status queries used by tiny-wb; exact output is firmware-dependent. |
Avoid sending mutating calibration, output, correction, or configuration-save
commands until the model and active port are known.
## `scanraw` request
The request is:
```text
scanraw START_HZ STOP_HZ POINTS [OPTIONS]\r
```
Constraints visible in upstream firmware:
- at least start and stop are required;
- start must not exceed stop;
- points defaults to the current display sweep-point count;
- option values are bit flags: `1` unbuffered, `2` continuous, `3` both;
- waterfall is disabled before acquisition in current firmware;
- a continuous request must be explicitly aborted and needs a streaming parser.
tiny-wb omits OPTIONS, so ordinary acquisition requests one buffered sweep and
`--live` repeats that complete request over one configured connection. The
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
Ignoring command echo, line endings, and the final prompt, the firmware emits:
```text
0x7b # '{'
0x78 LOW_BYTE HIGH_BYTE # 'x', sample 0, little-endian
0x78 LOW_BYTE HIGH_BYTE # 'x', sample 1
...
0x7d # '}'
```
Thus the framed body length is `1 + 3 * points + 1` bytes. Each level is a
16-bit raw value. Although the official USB page describes the bytes in one
place as “MSB LSB,” the firmware source writes `val & 0xff` first and
`val >> 8` second. The repository correctly unpacks the value as little-endian.
The `x` byte is a per-record alignment marker, not padding. Basic and Ultra use
the same braces, marker, two-byte value and exact body length; there is no
model-specific padding in the documented or reviewed `scanraw` format. Their
model-specific difference is the numeric level bias described below.
Payload bytes are arbitrary. A payload byte can equal `{`, `}`, `x`, `c`, `h`,
or `>`. Framing logic must only interpret `{` before the records, `x` at every
three-byte record boundary, and `}` after exactly the requested record count
(or after an explicitly aborted short frame). Searching binary payload for
text tokens is unsafe.
## Level conversion and `zero`
The [official USB interface](https://tinysa.org/wiki/pmwiki.php?n=Main.USBInterface)
documents these native conversions:
```text
Basic dBm = raw_u16 / 32 - 128
Ultra dBm = raw_u16 / 32 - 174
```
This is a fixed-point value with 1/32 dB numeric steps. The detector itself has
coarser effective resolution, so the encoding precision is not the same as
measurement accuracy.
The reviewed [firmware defaults](https://github.com/Ho-Ro/tinySA/blob/main/main.c#L1099-L1200)
set `config.ext_zero_level` to 128 for Basic and 174 for Ultra. The
[`scanraw` implementation](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c#L1221-L1267)
adds that offset to the measured value, and the
[`zero` handler](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c#L602-L609)
lets `zero N` replace it. tiny-wb detects the family and selects its native
offset automatically, then requires matching `zero` readback before scanning.
For Basic this gives:
```text
dBm = raw_u16 / 32 - 128
```
Ultra uses 174. Manual normalization is still available with
`scan.auto_zero_offset = false`; readback must agree with `scan.zero_offset`.
A mismatch would shift levels by 46 dB between native defaults, so acquisition
now rejects missing or mismatched readback. See [support and migration](ultra-support.md).
### Worked record
Suppose the three bytes are:
```text
78 00 08
```
`0x0800` is 2048. With `zero 128`:
```text
2048 / 32 - 128 = -64 dBm
```
## Frequency assignment
The official USB command page specifies the `scanraw` request and record count,
but does not define a point-to-frequency formula. The upstream
[`cmd_scanraw` implementation](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c#L1221-L1263),
reviewed on 2026-10-05, is the byte-level authority used here. Its C expression
has three relevant conversions:
```text
integer_step_hz = integer_divide(stop_hz - start_hz, points)
firmware_step_hz = float32(integer_step_hz)
frequency_hz[i] = start_hz + truncate_to_freq_t(firmware_step_hz * float32(i))
for i = 0 .. points - 1
```
The denominator is `points`, not `points - 1`. Integer division discards any
remainder before the assignment to the 32-bit `float`; multiplication can then
round at large values before conversion back to `freq_t`. For example, a
0–10 Hz, three-point request measures nominally at 0, 3, and 6 Hz. The requested
stop is an upper boundary and the final point is normally roughly one step below
it. tiny-wb's `firmware` axis reproduces these conversions, including the
single-precision rounding.
The default is now `scan.frequency_axis = "firmware"`. The compatibility-only
`inclusive` setting retains labels produced by older tiny-wb releases:
```text
host_step = (stop - start) / (points - 1)
frequency[i] = start + host_step * i
```
`inclusive` labels both requested endpoints and disagrees with the reviewed
firmware. The discrepancy grows linearly through a sweep to almost one firmware
step at the last point. Existing saved configuration remains compatible because
an explicit `inclusive` value is still accepted. Record the connected device's
`version` when validating a narrow carrier: the synthetic tests establish source
parity, not RF frequency accuracy or behavior of every firmware revision.
## Prompt and synchronization behavior
A reliable request/response state machine should:
1. retain a persistent receive buffer across OS reads;
2. write the complete command plus `\r`;
3. parse optional echo and line endings;
4. for text commands, recognize `ch>` even when split across reads and retain
any bytes after it;
5. for `scanraw`, find the frame start in shell text, then consume exactly the
expected number of aligned records and the closing brace before looking for
the prompt;
6. use an overall deadline plus idle deadlines rather than treating one serial
timeout as a successfully completed short reply;
7. make cancellation explicit with the firmware's `abort` behavior;
8. return protocol errors that include command, stage, byte counts, and a
bounded hex/text diagnostic.
Sleeping a fixed duration is not a protocol guarantee. Sweep time changes with
span, RBW, repeat, mode, signal-processing options, and firmware.
## Current tiny-wb transaction
The current code sends the following logical sequence (frequency placeholders
are decimal Hz):
```text
version
info
help
leveloffset
vbat
usart_cfg
threads
marker
repeat REPEAT
zero MODEL_OFFSET
zero
pause
mode LOW_OR_HIGH input
sweep start START
sweep stop STOP
sweep
scan START STOP 290 101
scanraw START STOP POINTS
resume
```
Every item except `scanraw` goes through the text helper and waits for `ch>`.
The transport retains unread bytes and recognizes prompts split across serial
reads. It consumes the complete length-delimited raw frame before returning to
text prompt parsing; arbitrary sample bytes cannot prematurely end the frame.
The pure decoder requires the exact record count, alignment and closing brace.
After attempting `pause`, acquisition attempts `resume` even if frame decoding
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
can prevent recovery. The offset requires readback; other settings are checked
for recognizable command errors. Optional diagnostic queries require `help`
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
its returned data is discarded. The legacy preparation is enabled by default
for compatibility, controlled by `scan.legacy_pre_scan`. Establish its hardware
purpose before changing the default or copying it into another client.
## Manual diagnostic session
Use a serial terminal that can send carriage return, with every RF source
disconnected or safely attenuated. A minimally invasive identification session
is:
```text
version
info
help
sweep
vbat
```
Save the exact transcript. Do not test `scanraw` in a terminal that assumes all
input is UTF-8; it returns binary and may corrupt the display or its own log.
Use a byte-oriented program and a bounded point count instead.
## Compatibility rules for implementers
- Identify capabilities; do not infer Ultra merely from a version prefix if
`info` gives an explicit model.
- Treat the command list as a firmware-build property.
- Keep Basic low/high path selection separate from Ultra normal/Ultra/harmonic
range selection.
- Make raw offset, valid frequency range, RBW limits, and legal mode syntax
model capabilities.
- Do not use UTF-8 strings for the mixed shell/binary receive buffer.
- Never use an unescaped textual prompt as a delimiter inside a binary frame.
- Restore or clearly report every instrument setting that the client changes.
- Include model, firmware version, configured offset, start/stop, point count,
repeat, RBW, attenuation, LNA, and Ultra state in future output metadata.
See [Project architecture](architecture.md#extension-points-and-remaining-limits) for
remaining implementation limits and [tiny-wb operations](tiny-wb-operations.md)
for what users can safely expect today.
## Configuration command rejection
`Shell::command_checked` rejects text lines beginning with `error:`, `usage:`,
or `unknown command` (case-insensitive). Acquisition uses it for settings and
pause/resume; diagnostic queries retain raw replies. This catches known failure
forms, not every firmware-specific error or acknowledgement. Binary scan errors
still fail framing/timeout checks. Model-aware replies remain roadmap work.

View File

@ -0,0 +1,58 @@
//! Local TCP shell simulator. See docs/mock-device.md for scope and usage.
use std::{
io::{self, Write},
net::{SocketAddr, TcpListener},
path::PathBuf,
time::Duration,
};
use tiny_wb::mock::{serve_connection, MockConfig};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut address: SocketAddr = "127.0.0.1:7355".parse()?;
let mut config_path: Option<PathBuf> = None;
let mut once = false;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--bind" => address = args.next().ok_or("--bind requires IP:port")?.parse()?,
"--config" => {
config_path = Some(args.next().ok_or("--config requires a TOML path")?.into())
}
"--once" => once = true,
"--help" => {
println!("usage: mock-tinysa-server [--bind IP:port] [--config FILE] [--once]");
return Ok(());
}
_ => return Err(format!("unknown option: {arg}").into()),
}
}
let config = match config_path {
Some(path) => toml::from_str(&std::fs::read_to_string(path)?)?,
None => MockConfig::default(),
};
config.validate()?;
let listener = TcpListener::bind(address)?;
println!(
"Mock tinySA listening on {} ({:?}, synthetic)",
listener.local_addr()?,
config.model
);
io::stdout().flush()?;
for connection in listener.incoming() {
let stream = connection?;
stream.set_read_timeout(Some(Duration::from_millis(config.session_timeout_ms)))?;
stream.set_write_timeout(Some(Duration::from_millis(config.session_timeout_ms)))?;
stream.set_nodelay(true)?;
if let Err(error) = serve_connection(stream, config.clone()) {
eprintln!("mock session ended: {error}");
if once {
return Err(error.into());
}
}
if once {
break;
}
}
Ok(())
}

View File

@ -0,0 +1,417 @@
//! Guided, conservative hardware acceptance for tinySA Basic and Ultra.
use std::{
collections::HashSet,
env,
error::Error,
fs,
io::{self, Write},
path::PathBuf,
thread,
time::Duration,
};
use tiny_wb::{
acquisition::{acquire, ScanEvent},
config::{Config, FrequencyAxis, ModelSelection, OutputConfig},
connection::open_connection,
export::save_csv,
protocol::{Sample, ScanRequest, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB},
transport::Shell,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Model {
Basic,
Ultra,
Zs406,
}
impl Model {
fn parse(value: &str) -> Option<Self> {
match value.to_ascii_lowercase().as_str() {
"basic" => Some(Self::Basic),
"ultra" => Some(Self::Ultra),
"zs406" => Some(Self::Zs406),
_ => None,
}
}
fn name(self) -> &'static str {
match self {
Self::Basic => "Basic",
Self::Ultra => "Ultra",
Self::Zs406 => "ZS406",
}
}
fn raw_level_offset_db(self) -> u16 {
match self {
Self::Basic => BASIC_RAW_LEVEL_OFFSET_DB,
Self::Ultra | Self::Zs406 => ULTRA_RAW_LEVEL_OFFSET_DB,
}
}
fn scans(self) -> [(&'static str, ScanRequest, bool, bool); 2] {
let low = ScanRequest {
start_hz: 240_000_000,
stop_hz: 300_000_000,
points: 101,
repeat: 1,
};
let second = match self {
Self::Basic => ScanRequest {
start_hz: 350_000_000,
stop_hz: 400_000_000,
..low
},
// Generic Ultra validation stays on the shared low-input path.
Self::Ultra => low,
Self::Zs406 => ScanRequest {
start_hz: 900_000_000,
stop_hz: 5_400_000_000,
points: 101,
repeat: 1,
},
};
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),
],
}
}
}
struct Arguments {
model: Model,
port: Option<String>,
output: PathBuf,
}
fn usage() -> &'static str {
"usage: validate-hardware <basic|ultra|zs406> [--port DEVICE] [--output DIRECTORY]"
}
fn parse_arguments(arguments: impl IntoIterator<Item = String>) -> Result<Arguments, String> {
let mut arguments = arguments.into_iter();
let model = arguments
.next()
.as_deref()
.and_then(Model::parse)
.ok_or_else(|| usage().to_owned())?;
let mut port = None;
let mut output = PathBuf::from("hardware-validation");
while let Some(option) = arguments.next() {
let value = arguments
.next()
.ok_or_else(|| format!("missing value for {option}\n{}", usage()))?;
match option.as_str() {
"--port" if port.is_none() && !value.is_empty() => port = Some(value),
"--output" if !value.is_empty() => output = PathBuf::from(value),
_ => return Err(format!("invalid option: {option}\n{}", usage())),
}
}
Ok(Arguments {
model,
port,
output,
})
}
fn prompt(message: &str) -> io::Result<String> {
print!("{message}");
io::stdout().flush()?;
let mut answer = String::new();
io::stdin().read_line(&mut answer)?;
Ok(answer.trim().to_owned())
}
fn ports() -> Result<Vec<String>, serialport::Error> {
Ok(serialport::available_ports()?
.into_iter()
.map(|port| port.port_name)
.collect())
}
fn select_port(explicit: Option<String>) -> Result<String, Box<dyn Error>> {
if let Some(port) = explicit {
prompt("Disconnect every RF source, plug in and power on the tinySA, then press Enter: ")?;
return Ok(port);
}
prompt("Disconnect the tinySA USB cable and every RF source, then press Enter: ")?;
let before: HashSet<_> = ports()?.into_iter().collect();
prompt("Plug in and power on the tinySA, then press Enter: ")?;
thread::sleep(Duration::from_millis(500));
let available = ports()?;
let added: Vec<_> = available
.iter()
.filter(|port| !before.contains(*port))
.cloned()
.collect();
if added.len() == 1 {
println!("Detected {}", added[0]);
return Ok(added[0].clone());
}
if available.len() == 1 {
println!("Using the only available serial port: {}", available[0]);
return Ok(available[0].clone());
}
if available.is_empty() {
return Err("no serial port appeared; check the USB data cable and permissions".into());
}
println!("Select the tinySA serial port:");
for (index, port) in available.iter().enumerate() {
println!(" {}. {port}", index + 1);
}
let selection: usize = prompt("Port number: ")?.parse()?;
available
.get(
selection
.checked_sub(1)
.ok_or("port number must be at least 1")?,
)
.cloned()
.ok_or_else(|| "port number is outside the displayed list".into())
}
fn validate_samples(samples: &[Sample], request: &ScanRequest) -> Result<(), Box<dyn Error>> {
if samples.len() != request.points {
return Err(format!(
"expected {} samples, received {}",
request.points,
samples.len()
)
.into());
}
if samples.iter().any(|sample| {
!sample.frequency_mhz.is_finite()
|| !sample.level_dbm.is_finite()
|| sample.frequency_mhz < request.start_hz as f64 / 1_000_000.0
|| sample.frequency_mhz > request.stop_hz as f64 / 1_000_000.0
}) {
return Err("CSV data contains a non-finite or out-of-range value".into());
}
Ok(())
}
fn safe_identity(identity: &str) -> String {
identity
.chars()
.filter(|character| *character == '\n' || *character == '\r' || !character.is_control())
.collect()
}
fn run() -> Result<(), Box<dyn Error>> {
let arguments = parse_arguments(env::args().skip(1)).map_err(io::Error::other)?;
println!(
"tinySA {} hardware validation\nNo RF source should be connected during this communications test.",
arguments.model.name()
);
let port = select_port(arguments.port)?;
let session = arguments.output.join(format!(
"{}-{}",
arguments.model.name().to_ascii_lowercase(),
jiff::ZonedDateTime::now().strftime("%Y%m%d-%H%M%S-%6f")
));
fs::create_dir_all(&session)?;
let mut report = format!(
"requested_model={}\nport={}\nbaudrate=115200\n",
arguments.model.name(),
port
);
let mut identity = String::new();
for (name, request, legacy_pre_scan, enable_ultra_mode) in arguments.model.scans() {
println!(
"Running {name} scan: {}–{} MHz, {} points...",
request.start_hz / 1_000_000,
request.stop_hz / 1_000_000,
request.points
);
let mut config = Config::default();
config.port.clone_from(&port);
config.start_frequency = (request.start_hz / 1_000_000) as usize;
config.stop_frequency = (request.stop_hz / 1_000_000) as usize;
config.points = request.points;
config.repeat = request.repeat;
config.scan.device_model = match arguments.model {
Model::Basic => ModelSelection::Basic,
Model::Ultra | Model::Zs406 => ModelSelection::Ultra,
};
config.scan.enable_ultra_mode = enable_ultra_mode;
config.scan.auto_zero_offset = true;
config.scan.zero_offset = arguments.model.raw_level_offset_db();
config.scan.frequency_axis = FrequencyAxis::Firmware;
config.scan.legacy_pre_scan = legacy_pre_scan;
config.validate()?;
let connection = open_connection(&config)?;
let mut shell = Shell::new(connection, config.serial.max_response_bytes);
let samples = acquire(
&mut shell,
&request,
&config.scan,
&config.serial,
|event| {
if let ScanEvent::InstrumentInfo(value) = event {
identity = safe_identity(&value);
}
},
)?;
validate_samples(&samples, &request)?;
let output = OutputConfig {
directory: session.clone(),
filename_prefix: format!("{}-{name}", arguments.model.name().to_ascii_lowercase()),
include_header: true,
};
let path = save_csv(&samples, &output)?;
println!(
"PASS: saved {} validated samples to {}",
samples.len(),
path.display()
);
report.push_str(&format!(
"scan={name},start_hz={},stop_hz={},points={},raw_level_offset_db={},legacy_pre_scan={},enable_ultra_mode={},csv={}\n",
request.start_hz,
request.stop_hz,
request.points,
config.scan.zero_offset,
legacy_pre_scan,
enable_ultra_mode,
path.display()
));
}
println!("\nInstrument identity returned by the device:\n{identity}");
let confirmed = prompt(&format!(
"Does this match a tinySA {} and is its live sweep running again? [y/N] ",
arguments.model.name()
))?;
report.push_str(&format!(
"identity=\n{identity}\noperator_confirmed={}\n",
confirmed
));
let report_path = session.join(format!(
"{}-report.txt",
arguments.model.name().to_ascii_lowercase()
));
fs::write(&report_path, report)?;
if !matches!(confirmed.as_str(), "y" | "Y" | "yes" | "YES" | "Yes") {
return Err(format!(
"operator confirmation failed; partial report: {}",
report_path.display()
)
.into());
}
println!(
"PASS: hardware validation report saved to {}",
report_path.display()
);
if arguments.model == Model::Ultra {
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(())
}
fn main() {
if let Err(error) = run() {
eprintln!("FAIL: {error}");
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use super::*;
use tiny_wb::device::DeviceModel;
#[test]
fn plans_keep_ultra_on_the_shared_low_input_path() {
assert_eq!(Model::Basic.raw_level_offset_db(), 128);
assert_eq!(Model::Ultra.raw_level_offset_db(), 174);
let basic = Model::Basic.scans();
assert_eq!(
DeviceModel::Basic.plan(&basic[0].1).unwrap().input_command,
"mode low input"
);
assert_eq!(
DeviceModel::Basic.plan(&basic[1].1).unwrap().input_command,
"mode high input"
);
let ultra = Model::Ultra.scans();
assert!(ultra.iter().all(|(_, request, _, enable_ultra_mode)| {
request.stop_hz < 350_000_000
&& !enable_ultra_mode
&& DeviceModel::Ultra
.plan(request)
.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[1].2);
}
#[test]
fn sample_validation_rejects_bad_count_and_values() {
let request = ScanRequest {
start_hz: 240_000_000,
stop_hz: 300_000_000,
points: 2,
repeat: 1,
};
let valid = [
Sample {
frequency_mhz: 240.0,
level_dbm: -90.0,
},
Sample {
frequency_mhz: 270.0,
level_dbm: -80.0,
},
];
assert!(validate_samples(&valid, &request).is_ok());
assert!(validate_samples(&valid[..1], &request).is_err());
let invalid = [
valid[0],
Sample {
frequency_mhz: 270.0,
level_dbm: f64::NAN,
},
];
assert!(validate_samples(&invalid, &request).is_err());
}
#[test]
fn arguments_require_a_known_model_and_option_values() {
assert_eq!(
parse_arguments(["ultra".into(), "--port".into(), "COM7".into()])
.unwrap()
.port
.as_deref(),
Some("COM7")
);
assert!(parse_arguments(["unknown".into()]).is_err());
assert!(parse_arguments(["basic".into(), "--port".into()]).is_err());
assert!(parse_arguments(["basic".into(), "--bad".into(), "x".into()]).is_err());
}
}

79
release.sh Executable file
View File

@ -0,0 +1,79 @@
#!/bin/sh
# Project-local rust_realease entry point. See docs/releases.md before publishing.
set -eu
# Do not expose the first token-file line if a caller enables shell tracing.
set +x
unset GITEA_TOKEN
usage() {
echo "usage: $0 <gitea-token-file> [rust_realease options...]" >&2
echo " $0 --compile-only [rust_realease options...]" >&2
exit 2
}
[ "$#" -ge 1 ] || usage
token_file=
if [ "$1" = "--compile-only" ]; then
shift
set -- --compile-only "$@"
else
token_file=$1
shift
if [ ! -f "$token_file" ] || [ ! -r "$token_file" ] || [ ! -s "$token_file" ]; then
echo "token file must be readable, regular and nonempty" >&2
exit 2
fi
fi
if ! command -v rust_realease >/dev/null 2>&1; then
echo "rust_realease is not installed or not available in PATH; see docs/releases.md" >&2
exit 2
fi
repository_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
# This repository has one root package with a literal version. Fail closed if
# it is changed to an inherited/workspace version instead of guessing a value.
manifest_version=$(awk '
/^[[:space:]]*\[/ { package = ($0 ~ /^[[:space:]]*\[package\][[:space:]]*(#.*)?$/) }
package && /^[[:space:]]*version[[:space:]]*=[[:space:]]*"[^"]+"[[:space:]]*(#.*)?$/ {
value = $0
sub(/^[^"]*"/, "", value)
sub(/".*$/, "", value)
count++
}
END {
if (count != 1 || value !~ /^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.+-]+)?$/) exit 1
print value
}
' "$repository_dir/Cargo.toml") || {
echo "could not determine the tiny-wb package version from Cargo.toml" >&2
exit 2
}
set -- "$repository_dir" --package tiny-wb --artifact-format both "$@"
# A hyphen in build metadata alone does not make a SemVer prerelease.
case "${manifest_version%%+*}" in
*-*) set -- "$@" --prerelease ;;
esac
# Read after subprocess-based discovery, and export only when publishing or
# performing an authenticated dry run. Compile-only mode needs no token.
if [ -n "$token_file" ]; then
GITEA_TOKEN=
IFS= read -r GITEA_TOKEN <"$token_file" || :
if [ -z "$GITEA_TOKEN" ]; then
echo "the token file's first line must not be empty" >&2
exit 2
fi
export GITEA_TOKEN
fi
# Cross builds in an isolated Debian/Ubuntu image, so native libraries from the
# maintainer's host are unavailable. Keep this explicitly selected file away
# from the root Cross.toml path validated by rust_realease.
CROSS_CONFIG=$repository_dir/release/Cross.toml
if [ ! -f "$CROSS_CONFIG" ] || [ ! -r "$CROSS_CONFIG" ]; then
echo "release Cross configuration is missing or unreadable: $CROSS_CONFIG" >&2
exit 2
fi
export CROSS_CONFIG
exec rust_realease "$@"

7
release/Cross.toml Normal file
View File

@ -0,0 +1,7 @@
# Native dependencies required by the GNU/Linux release target. This file is
# selected explicitly by release.sh because rust_realease reserves a root
# Cross.toml for its validated repository configuration.
[target.x86_64-unknown-linux-gnu]
pre-build = [
"apt-get update && apt-get install --assume-yes --no-install-recommends libudev-dev pkg-config",
]

30
rust-release.toml Normal file
View File

@ -0,0 +1,30 @@
# Public release policy; independent of runtime config/default.toml.
[release]
# Existing tiny-wb tags have no leading v. Do not retag historical versions.
tag-prefix = ""
[build]
# Desktop targets. Linux uses glibc because serialport links system libudev.
# release/Cross.toml injects target libudev/pkg-config; the base images provide
# the remaining target toolchains, including the Windows windres executable.
targets = [
"x86_64-unknown-linux-gnu",
"x86_64-pc-windows-gnu",
"aarch64-apple-darwin",
"x86_64-apple-darwin",
]
profile = "release"
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]
token-env = "GITEA_TOKEN"
[[repository.fallbacks]]
origin = "git@git.dandaedre.com:idle-org/tiny-wb.git"
fallback-url = "https://proxy.dandaedre.com/gitea/idle-org/tiny-wb"

272
scripts/ci-coverage-badges.sh Executable file
View File

@ -0,0 +1,272 @@
#!/bin/sh
set -eu
usage() {
cat >&2 <<'EOF'
usage: $0 <version|test|coverage> [options]
Render one deterministic SVG badge. Defaults:
version --text version --value unknown --color #007ec6
test --text tests --value passing --color #4c1
coverage --text coverage --value - --color #9f9f9f --suffix %
Options:
--text TEXT left-hand label
--value VALUE right-hand value
--color COLOR value background (#RGB or #RRGGBB)
--size PX font size, from 6 through 24 (default: 11)
--height PX badge height, from 14 through 64 (default: 20)
--label-width PX fixed label width instead of automatic sizing
--value-width PX fixed value width instead of automatic sizing
--suffix TEXT text appended to the displayed value
--output PATH output file (default: coverage/<kind>.svg)
-h, --help show this help
Examples:
./ci-coverage-badges.sh version --value 1.2.3
./ci-coverage-badges.sh test --value failing
./ci-coverage-badges.sh coverage --value 87.4
./ci-coverage-badges.sh version --text release --value rc.12 --size 12 --color '#8a2be2'
EOF
exit "${1:-2}"
}
[ "$#" -ge 1 ] || usage
kind=$1
shift
case "$kind" in
version)
text=version
value=unknown
color='#007ec6'
suffix=
output=coverage/version.svg
;;
test)
text=tests
value=passing
color=
suffix=
output=coverage/test.svg
;;
coverage)
text=coverage
value=-
color=
suffix=%
output=coverage/coverage.svg
;;
-h|--help) usage 0 ;;
*)
echo "unsupported badge kind: $kind" >&2
usage
;;
esac
font_size=11
height=20
label_width=
value_width=
color_set=false
while [ "$#" -gt 0 ]; do
option=$1
case "$option" in
--text|--value|--color|--size|--height|--label-width|--value-width|--suffix|--output)
[ "$#" -ge 2 ] || {
echo "missing value for $option" >&2
exit 2
}
option_value=$2
shift 2
case "$option" in
--text) text=$option_value ;;
--value) value=$option_value ;;
--color) color=$option_value; color_set=true ;;
--size) font_size=$option_value ;;
--height) height=$option_value ;;
--label-width) label_width=$option_value ;;
--value-width) value_width=$option_value ;;
--suffix) suffix=$option_value ;;
--output) output=$option_value ;;
esac
;;
-h|--help) usage 0 ;;
*)
echo "unknown option: $option" >&2
usage
;;
esac
done
validate_text() {
field_name=$1
field_value=$2
if ! printf '%sX\n' "$field_value" | LC_ALL=C awk '
BEGIN { valid = 1 }
NR != 1 || $0 !~ /^[ -~]+X$/ || length($0) <= 1 { valid = 0 }
END { exit(valid == 0 ? 1 : 0) }
'; then
echo "$field_name must contain printable ASCII characters: $field_value" >&2
exit 2
fi
}
validate_integer() {
field_name=$1
field_value=$2
minimum=$3
maximum=$4
case "$field_value" in
''|*[!0-9]*)
echo "$field_name must be an integer from $minimum through $maximum: $field_value" >&2
exit 2
;;
esac
if ! awk -v value="$field_value" -v low="$minimum" -v high="$maximum" 'BEGIN { exit (value >= low && value <= high ? 0 : 1) }'; then
echo "$field_name must be an integer from $minimum through $maximum: $field_value" >&2
exit 2
fi
}
validate_text text "$text"
validate_text value "$value"
if [ -n "$suffix" ]; then
validate_text suffix "$suffix"
fi
validate_integer size "$font_size" 6 24
validate_integer height "$height" 14 64
if [ -n "$label_width" ]; then
validate_integer label-width "$label_width" 20 1000
fi
if [ -n "$value_width" ]; then
validate_integer value-width "$value_width" 20 1000
fi
case "$output" in
''|*/) echo "output must name an SVG file: $output" >&2; exit 2 ;;
esac
case "$kind" in
test)
if [ "$color_set" = false ]; then
case "$value" in
passing) color='#4c1' ;;
failing) color='#e05d44' ;;
*) color='#9f9f9f' ;;
esac
fi
;;
coverage)
if [ "$value" = '-' ]; then
[ "$color_set" = true ] || color='#9f9f9f'
else
if ! awk -v candidate="$value" 'BEGIN {
valid = candidate ~ /^[0-9]+([.][0-9]+)?$/ && candidate >= 0 && candidate <= 100
exit(valid ? 0 : 1)
}'; then
echo "coverage value must be - or a number from 0 through 100: $value" >&2
exit 2
fi
value=$(awk -v candidate="$value" 'BEGIN { printf "%.0f", candidate }')
if [ "$color_set" = false ]; then
if [ "$value" -ge 90 ]; then
color='#4c1'
elif [ "$value" -ge 70 ]; then
color='#dfb317'
else
color='#e05d44'
fi
fi
fi
;;
esac
case "$color" in
\#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]|\#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]) ;;
*) echo "color must be #RGB or #RRGGBB: $color" >&2; exit 2 ;;
esac
display_value=$value$suffix
if [ -z "$label_width" ]; then
label_width=$(printf '%s\n' "$text" | awk -v size="$font_size" '{
width = int(length($0) * size * 0.64 + 14)
print (width < 35 ? 35 : width)
}')
fi
if [ -z "$value_width" ]; then
value_width=$(printf '%s\n' "$display_value" | awk -v size="$font_size" '{
width = int(length($0) * size * 0.64 + 14)
print (width < 35 ? 35 : width)
}')
fi
badge_width=$((label_width + value_width))
label_center=$(awk -v width="$label_width" 'BEGIN { printf "%.1f", width / 2 }')
value_center=$(awk -v left="$label_width" -v width="$value_width" 'BEGIN {
printf "%.1f", left + width / 2
}')
vertical_center=$(awk -v badge_height="$height" 'BEGIN { printf "%.1f", badge_height / 2 }')
xml_escape() {
sed \
-e 's/&/\&amp;/g' \
-e 's/</\&lt;/g' \
-e 's/>/\&gt;/g' \
-e 's/"/\&quot;/g'
}
sed_replacement_escape() {
sed -e 's/[\\&|]/\\&/g'
}
escaped_text=$(printf '%s' "$text" | xml_escape | sed_replacement_escape)
escaped_value=$(printf '%s' "$display_value" | xml_escape | sed_replacement_escape)
escaped_title=$(printf '%s: %s' "$text" "$display_value" | xml_escape | sed_replacement_escape)
[ ! -d "$output" ] || { echo "output must not be a directory: $output" >&2; exit 2; }
output_dir=${output%/*}
if [ "$output_dir" != "$output" ]; then
mkdir -p "$output_dir"
fi
temporary=$(mktemp "${output}.tmp.XXXXXX")
trap 'rm -f "$temporary"' 0
trap 'exit 1' HUP INT TERM
sed \
-e "s/@BADGE_WIDTH@/$badge_width/g" \
-e "s/@HEIGHT@/$height/g" \
-e "s/@LABEL_WIDTH@/$label_width/g" \
-e "s/@VALUE_WIDTH@/$value_width/g" \
-e "s/@LABEL_CENTER@/$label_center/g" \
-e "s/@VALUE_CENTER@/$value_center/g" \
-e "s/@VERTICAL_CENTER@/$vertical_center/g" \
-e "s/@FONT_SIZE@/$font_size/g" \
-e "s/@COLOR@/$color/g" \
-e "s|@TITLE@|$escaped_title|g" \
-e "s|@TEXT@|$escaped_text|g" \
-e "s|@VALUE@|$escaped_value|g" \
>"$temporary" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" width="@BADGE_WIDTH@" height="@HEIGHT@" role="img" aria-label="@TITLE@">
<title>@TITLE@</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
<stop offset=".9" stop-opacity=".3"/>
<stop offset="1" stop-opacity=".5"/>
</linearGradient>
<clipPath id="r"><rect width="@BADGE_WIDTH@" height="@HEIGHT@" rx="3"/></clipPath>
<g clip-path="url(#r)">
<rect width="@LABEL_WIDTH@" height="@HEIGHT@" fill="#555"/>
<rect x="@LABEL_WIDTH@" width="@VALUE_WIDTH@" height="@HEIGHT@" fill="@COLOR@"/>
<rect width="@BADGE_WIDTH@" height="@HEIGHT@" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" dominant-baseline="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="@FONT_SIZE@">
<text x="@LABEL_CENTER@" y="@VERTICAL_CENTER@">@TEXT@</text>
<text x="@VALUE_CENTER@" y="@VERTICAL_CENTER@">@VALUE@</text>
</g>
</svg>
EOF
mv "$temporary" "$output"
trap - 0 HUP INT TERM

30
scripts/collect-coverage.sh Executable file
View File

@ -0,0 +1,30 @@
#!/bin/sh
set -eu
mkdir -p coverage
summary=coverage/summary.json
log=coverage/coverage.log
trap 'rm -f "$summary"' 0
trap 'exit 1' HUP INT TERM
# Alias and honest initial floor live in .cargo/config.toml.
rm -f "$summary"
coverage_status=0
cargo coverage >"$log" 2>&1 || coverage_status=$?
# Preserve the explicit status check even when Cargo writes a valid report.
# Print the measurement before cleanup, but never mask a failed Cargo run.
if [ ! -s "$summary" ]; then
echo "ERROR: cargo coverage produced no summary (exit $coverage_status); see coverage/coverage.log." >&2
[ "$coverage_status" -ne 0 ] || coverage_status=1
exit "$coverage_status"
fi
if ! percentage=$(jq -er '.data | if type == "array" and length == 1 then .[0].totals.lines.percent else error("expected one overall total") end | select(type == "number" and . >= 0 and . <= 100)' "$summary"); then
echo "ERROR: cargo coverage produced an invalid line-coverage summary (exit $coverage_status); see coverage/coverage.log." >&2
[ "$coverage_status" -ne 0 ] || coverage_status=1
exit "$coverage_status"
fi
LC_ALL=C awk -v percentage="$percentage" 'BEGIN { printf "Final line coverage: %.2f%%\n", percentage }'
if [ "$coverage_status" -ne 0 ]; then
echo "ERROR: cargo coverage failed (exit $coverage_status); check the measurement against --fail-under-lines and coverage/coverage.log." >&2
exit "$coverage_status"
fi
scripts/ci-coverage-badges.sh coverage --value "$percentage"
rm -f "$summary"

19
scripts/finalize-badges.sh Executable file
View File

@ -0,0 +1,19 @@
#!/bin/sh
set -eu
: "${BUILD_NUMBER:?BUILD_NUMBER is required}"
case "$BUILD_NUMBER" in *[!0-9]*) exit 1 ;; esac
trap 'rm -f coverage/summary.json "coverage/.tests-passed-${BUILD_NUMBER}" "coverage/.coverage-ready-${BUILD_NUMBER}"' 0
trap 'exit 1' HUP INT TERM
status=failing
[ ! -f "coverage/.tests-passed-${BUILD_NUMBER}" ] || status=passing
scripts/ci-coverage-badges.sh test --value "$status"
if [ ! -f "coverage/.coverage-ready-${BUILD_NUMBER}" ]; then
scripts/ci-coverage-badges.sh coverage --value -
fi
version=$(cargo metadata --no-deps --locked --format-version 1 | jq -er '.packages[] | select(.name == "tiny-wb") | .version')
scripts/ci-coverage-badges.sh version --value "$version"
rm -f coverage/summary.json "coverage/.tests-passed-${BUILD_NUMBER}" "coverage/.coverage-ready-${BUILD_NUMBER}"
for name in version test coverage; do
file="coverage/$name.svg"
[ ! -L "$file" ] && [ -f "$file" ] && [ -s "$file" ] || exit 1
done

46
scripts/publish-badges.sh Executable file
View File

@ -0,0 +1,46 @@
#!/bin/sh
# Run from the repository root. The root already includes /coverage.
set -eu
fail() { echo "$*" >&2; exit 1; }
[ "$#" -ge 5 ] || fail 'usage: publish-badges.sh ROOT OWNER PROJECT BRANCH NAME...'
root=$1 owner=$2 project=$3 branch=$4
shift 4
case "$root" in /*) ;; *) fail 'publication root must be absolute' ;; esac
[ -d "$root" ] && [ -w "$root" ] || fail 'publication root must exist and be writable'
for component in "$owner" "$project" "$branch"; do
case "$component" in ''|.|..|*[!a-zA-Z0-9_.-]*) fail 'invalid path component' ;; esac
done
seen=' '
for name do
case "$name" in coverage|test|version) ;; *) fail 'invalid badge name' ;; esac
case "$seen" in *" $name "*) fail 'duplicate badge name' ;; esac
seen="$seen$name "
source="coverage/$name.svg"
[ ! -L "$source" ] && [ -f "$source" ] && [ -s "$source" ] || fail "invalid source: $source"
done
# Explicit chmod makes newly created directories readable even under umask 077.
destination=${root%/}
for component in "$owner" "$project" "$branch"; do
destination="$destination/$component"
if [ "$destination" = "${root%/}/$owner/$project/$branch" ] && [ -L "$destination" ]; then
unlink "$destination"
fi
[ ! -L "$destination" ] || fail "symlink destination: $destination"
if [ ! -e "$destination" ]; then
mkdir -m 0755 "$destination"
chmod 0755 "$destination"
fi
[ -d "$destination" ] || fail "not a directory: $destination"
done
temporary=
trap '[ -z "$temporary" ] || rm -f "$temporary"' 0
trap 'exit 1' HUP INT TERM
for name do
# Never let mv interpret an existing directory (or link to one) as a target.
[ ! -d "$destination/$name.svg" ] || fail 'badge destination is a directory'
temporary=$(mktemp "$destination/.$name.svg.XXXXXX")
cp "coverage/$name.svg" "$temporary"
chmod 0644 "$temporary"
mv -f "$temporary" "$destination/$name.svg"
temporary=
done

239
scripts/test-badges.py Normal file
View File

@ -0,0 +1,239 @@
#!/usr/bin/env python3
"""Isolated renderer/publication contract checks; no public assets are touched."""
import os
import json
import re
from pathlib import Path
import stat
import shlex
import shutil
import subprocess
import tempfile
import xml.etree.ElementTree as ET
REPO = Path(__file__).resolve().parent.parent
RENDER = str(REPO / 'scripts/ci-coverage-badges.sh')
PUBLISH = str(REPO / 'scripts/publish-badges.sh')
def run(*args, ok=True):
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert (result.returncode == 0) == ok, (args, result.stderr.decode())
return result
with tempfile.TemporaryDirectory() as directory:
os.chdir(directory)
os.umask(0o077)
for kind in ('version', 'test', 'coverage'):
run(RENDER, kind)
for kind, value, color in [
('version', '1.2.3', '#007ec6'),
('version', '1.2.3-very-long-prerelease.123456789', '#007ec6'),
('test', 'passing', '#4c1'), ('test', 'failing', '#e05d44'),
('test', 'pending', '#9f9f9f'), ('coverage', '0', '#e05d44'),
('coverage', '69', '#e05d44'), ('coverage', '70', '#dfb317'),
('coverage', '87.4', '#dfb317'), ('coverage', '90', '#4c1'),
('coverage', '100', '#4c1'), ('coverage', '-', '#9f9f9f'),
]:
run(RENDER, kind, '--value', value)
root = ET.parse(f'coverage/{kind}.svg').getroot()
assert color in Path(f'coverage/{kind}.svg').read_text()
if value == '1.2.3':
normal_width = int(root.attrib['width'])
if value == '1.2.3-very-long-prerelease.123456789':
assert int(root.attrib['width']) > normal_width
if value == '87.4':
assert root.attrib['aria-label'] == 'coverage: 87%'
run(RENDER, 'version', '--text', 'A<&"', '--value', 'B>&"', '--suffix', '&',
'--size', '14', '--height', '30', '--label-width', '80',
'--value-width', '120', '--color', '#abcdef', '--output', 'custom/badge.svg')
root = ET.parse('custom/badge.svg').getroot()
assert root.attrib['width'] == '200' and root.attrib['height'] == '30'
assert root.attrib['aria-label'] == 'A<&": B>&"&'
Path('directory-output').mkdir()
run(RENDER, 'version', '--output', 'directory-output', ok=False)
original = Path('coverage/coverage.svg').read_bytes()
for args in [
['unknown'], ['coverage', '--bogus'], ['coverage', '--value'],
*[['coverage', '--value', v] for v in ('-1', '101', 'nan', '1e2', 'x', '')],
*[['coverage', flag, v] for flag, v in (
('--size', '5'), ('--size', '25'), ('--height', '13'), ('--height', '65'),
('--label-width', '19'), ('--value-width', '1001'),
('--height', '999999999999999999999999999'), ('--color', 'red'),
('--color', '#1234567'), ('--text', 'bad\ntext'), ('--value', '\t'))],
]:
run(RENDER, *args, ok=False)
assert Path('coverage/coverage.svg').read_bytes() == original
assert not list(Path('.').rglob('*.tmp.*'))
for svg in Path('.').rglob('*.svg'):
ET.parse(svg)
root = Path(directory) / 'assets'
root.mkdir()
args = [PUBLISH, str(root), 'idle-org', 'tiny-wb', 'main']
names = ['version', 'test', 'coverage']
run(*args, *names)
destination = root / 'idle-org/tiny-wb/main'
for path in (root/'idle-org', root/'idle-org/tiny-wb', destination):
assert stat.S_IMODE(path.stat().st_mode) == 0o755
old_inode = (destination/'test.svg').stat().st_ino
run(*args, *names)
assert (destination/'test.svg').stat().st_ino != old_inode
for name in names:
target = destination/f'{name}.svg'
assert target.read_bytes() == Path(f'coverage/{name}.svg').read_bytes()
assert stat.S_IMODE(target.stat().st_mode) == 0o644
run(*args, 'test', 'test', ok=False)
run(*args, 'invalid', ok=False)
run(PUBLISH, 'relative', 'o', 'p', 'main', 'test', ok=False)
run(PUBLISH, str(root/'missing'), 'o', 'p', 'main', 'test', ok=False)
run(PUBLISH, str(root), '..', 'p', 'main', 'test', ok=False)
saved = Path('coverage/test.svg').read_bytes()
Path('coverage/test.svg').unlink()
Path('coverage/test.svg').symlink_to('version.svg')
run(*args, 'test', ok=False)
Path('coverage/test.svg').unlink()
Path('coverage/test.svg').touch()
run(*args, 'test', ok=False)
Path('coverage/test.svg').write_bytes(saved)
(root/'linked').symlink_to(root/'idle-org', target_is_directory=True)
run(PUBLISH, str(root), 'linked', 'tiny-wb', 'main', 'test', ok=False)
(root/'idle-org/linked').symlink_to(root/'idle-org/tiny-wb', target_is_directory=True)
run(PUBLISH, str(root), 'idle-org', 'linked', 'main', 'test', ok=False)
(root/'file').touch()
run(PUBLISH, str(root), 'file', 'p', 'main', 'test', ok=False)
# Migration unlinks the old branch link, preserving its target and contents.
old = destination.with_name('old')
destination.rename(old)
destination.symlink_to(old, target_is_directory=True)
run(*args, *names)
assert destination.is_dir() and not destination.is_symlink()
assert (old/'test.svg').read_bytes() == saved
# Failed copy, chmod and rename must preserve the published badge and
# remove the unfinished temporary file.
tools = Path(directory) / 'fake-bin'
tools.mkdir()
old_path = os.environ['PATH']
for command in ('cp', 'chmod', 'mv'):
stub = tools / command
stub.write_text('#!/bin/sh\nexit 1\n')
stub.chmod(0o755)
os.environ['PATH'] = str(tools) + ':' + old_path
run(*args, 'test', ok=False)
os.environ['PATH'] = old_path
stub.unlink()
assert (destination/'test.svg').read_bytes() == saved
assert not list(destination.glob('.*.svg.*'))
stub = tools / 'mv'
stub.write_text('#!/bin/sh\nkill -TERM "$PPID"\nexit 1\n')
stub.chmod(0o755)
os.environ['PATH'] = str(tools) + ':' + old_path
run(*args, 'test', ok=False)
run(RENDER, 'coverage', '--value', '50', ok=False)
os.environ['PATH'] = old_path
stub.unlink()
assert Path('coverage/coverage.svg').read_bytes() == original
assert not list(Path('coverage').glob('*.tmp.*'))
assert not list(destination.glob('.*.svg.*'))
# Exercise cleanup with real Cargo metadata from this repository while
# keeping all generated files in the isolated directory.
Path('scripts').symlink_to(REPO/'scripts', target_is_directory=True)
cargo = tools/'cargo'
cargo.write_text('#!/bin/sh\nexec ' + shlex.quote(shutil.which('cargo')) +
' metadata --manifest-path ' + shlex.quote(str(REPO/'Cargo.toml')) +
' --no-deps --locked --format-version 1\n')
cargo.chmod(0o755)
os.environ['PATH'] = str(tools) + ':' + old_path
os.environ['BUILD_NUMBER'] = '123'
for marker in ('tests-passed', 'coverage-ready'):
Path(f'coverage/.{marker}-122').touch()
run(str(REPO/'scripts/finalize-badges.sh'))
assert ET.parse('coverage/test.svg').getroot().attrib['aria-label'] == 'tests: failing'
assert ET.parse('coverage/coverage.svg').getroot().attrib['aria-label'] == 'coverage: -%'
run(RENDER, 'coverage', '--value', '87.4')
for marker in ('tests-passed', 'coverage-ready'):
Path(f'coverage/.{marker}-123').touch()
run(str(REPO/'scripts/finalize-badges.sh'))
assert ET.parse('coverage/test.svg').getroot().attrib['aria-label'] == 'tests: passing'
assert ET.parse('coverage/coverage.svg').getroot().attrib['aria-label'] == 'coverage: 87%'
assert not list(Path('coverage').glob('.*-123'))
os.environ['PATH'] = old_path
cargo.unlink()
# A coverage-floor failure can write a valid report and exit silently.
# Exercise the collector with real jq and rendering, but no Rust rebuild.
cargo.write_text('''#!/bin/sh
[ "$*" = coverage ] || exit 99
echo "fake compiler output"
echo "fake test output" >&2
if [ -n "$FAKE_COVERAGE_REPORT" ]; then
printf '%s\\n' "$FAKE_COVERAGE_REPORT" > coverage/summary.json
fi
exit "$FAKE_COVERAGE_STATUS"
''')
cargo.chmod(0o755)
os.environ['PATH'] = str(tools) + ':' + old_path
for percentage, status in ((91.49, 0), (85, 0), (84.99, 1), (91.49, 7)):
os.environ['FAKE_COVERAGE_REPORT'] = json.dumps({'data': [{
'totals': {'lines': {'percent': percentage}},
'files': [{'filename': 'src/example.rs', 'summary': {
'lines': {'percent': 80, 'count': 100, 'covered': 80}}}],
}]})
os.environ['FAKE_COVERAGE_STATUS'] = str(status)
before = Path('coverage/coverage.svg').read_bytes()
result = run(str(REPO/'scripts/collect-coverage.sh'), ok=status == 0)
assert result.returncode == status
assert result.stdout.decode() == f'Final line coverage: {percentage:.2f}%\n'
assert 'fake compiler output' in Path('coverage/coverage.log').read_text()
assert 'fake test output' in Path('coverage/coverage.log').read_text()
if status:
assert '--fail-under-lines' in result.stderr.decode()
assert 'src/example.rs' not in result.stderr.decode()
assert 'coverage/coverage.log' in result.stderr.decode()
assert Path('coverage/coverage.svg').read_bytes() == before
else:
assert ET.parse('coverage/coverage.svg').getroot().attrib['aria-label'] == f'coverage: {percentage:.0f}%'
assert not Path('coverage/summary.json').exists()
for report in ('', '{broken', '{"data": []}', '{"data": [{}, {}]}',
*[json.dumps({'data': [{'totals': {'lines': {'percent': p}}}]})
for p in (None, '90', -1, 101)]):
for status in (0, 7):
# An old successful report must not hide a missing current report.
Path('coverage/summary.json').write_text('{"data":[{"totals":{"lines":{"percent":99}}}]}')
os.environ['FAKE_COVERAGE_REPORT'] = report
os.environ['FAKE_COVERAGE_STATUS'] = str(status)
result = run(str(REPO/'scripts/collect-coverage.sh'), ok=False)
assert result.returncode == (status or 1)
assert 'ERROR: cargo coverage produced' in result.stderr.decode()
assert not Path('coverage/summary.json').exists()
os.environ['PATH'] = old_path
del os.environ['FAKE_COVERAGE_REPORT'], os.environ['FAKE_COVERAGE_STATUS']
cargo.unlink()
root.chmod(0o555)
if os.geteuid() != 0:
run(*args, 'test', ok=False)
root.chmod(0o700)
(destination/'test.svg').unlink()
(destination/'test.svg').mkdir()
run(*args, 'test', ok=False)
assert not list(destination.glob('.*.svg.*'))
# Keep the alias's dependency filter portable across cache roots without
# excluding any production module (including low-coverage startup/scan code).
alias = next(line for line in (REPO/'.cargo/config.toml').read_text().splitlines()
if line.startswith('coverage = '))
arguments = shlex.split(alias.split('"', 1)[1].rsplit('"', 1)[0])
pattern = arguments[arguments.index('--ignore-filename-regex') + 1]
assert arguments[arguments.index('--fail-under-lines') + 1] == '85'
for cache in ('/root/.cargo', '/home/user/.cargo', '/custom/cargo-cache'):
assert re.search(pattern, cache + '/registry/src/index.crates.io-123/serde-1.0/src/lib.rs')
for source in (REPO/'src').rglob('*.rs'):
assert not re.search(pattern, str(source))
readme = (REPO/'README.md').read_text()
for name in ('version', 'test', 'coverage'):
assert readme.count(f'https://assets.dandaedre.com/coverage/idle-org/tiny-wb/main/{name}.svg') == 1
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 'fingerprint: true, allowEmptyArchive: false' in pipeline
print('Badge rendering, XML, validation, coverage diagnostics, publication, README and archive checks passed.')

14
scripts/test-hardware.sh Executable file
View File

@ -0,0 +1,14 @@
#!/bin/sh
set -eu
case "${1:-}" in
basic|ultra|zs406) ;;
*)
echo "usage: $0 <basic|ultra|zs406> [--port DEVICE] [--output DIRECTORY]" >&2
exit 2
;;
esac
repository=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$repository"
exec cargo run --locked --release --example validate-hardware -- "$@"

View File

@ -0,0 +1,41 @@
"""Smoke-test the built mock server CLI over loopback; run from the repo root.
Build with cargo build --no-default-features --features mock --example
mock-tinysa-server. Optionally pass an executable path (for CARGO_TARGET_DIR).
"""
import os
import socket
import subprocess
import sys
exe = sys.argv[1] if len(sys.argv) > 1 else 'target/debug/examples/mock-tinysa-server' + ('.exe' if os.name == 'nt' else '')
assert subprocess.run([exe, '--help'], capture_output=True, timeout=5).returncode == 0
assert subprocess.run([exe, '--unknown'], capture_output=True, timeout=5).returncode != 0
server = subprocess.Popen([exe, '--bind', '127.0.0.1:0', '--config', 'config/mock-basic.toml', '--once'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
line = server.stdout.readline()
address = line.split()[4]
host, port = address.rsplit(':', 1)
with socket.create_connection((host, int(port)), timeout=3) as client:
def response():
data = b''
while not data.endswith(b'ch>'):
block = client.recv(4096)
assert block, 'unexpected EOF'
data += block
return data
assert response() == b'ch>'
client.sendall(b'version\r')
assert b'tinySA_v1.4-mock' in response()
client.sendall(b'mode high input\r')
assert b'error:' not in response()
client.sendall(b'scanraw 240000000 360000000 4\r')
data = response()
frame = data[data.index(b'{'):]
assert frame[1] == ord('x') and frame[13] == ord('}')
assert server.wait(timeout=5) == 0, server.stderr.read()
print('Standalone mock server: CLI validation, dynamic port, synthetic identity, scanraw and --once lifecycle passed.')
finally:
if server.poll() is None:
server.kill()
server.wait()

198
scripts/test-release.py Normal file
View File

@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Exercise release.sh in disposable repositories with an inert publisher."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import tomllib
import unittest
REPO = Path(__file__).resolve().parent.parent
class ReleaseWrapperTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix='tiny-wb release ')
self.root = Path(self.temporary.name)
self.project = self.root / 'project with spaces'
self.project.mkdir()
for name in ('release.sh', 'Cargo.toml', 'rust-release.toml'):
shutil.copy2(REPO / name, self.project / name)
(self.project / 'release').mkdir()
shutil.copy2(REPO / 'release' / 'Cross.toml', self.project / 'release' / 'Cross.toml')
self.tools = self.root / 'tools'
self.tools.mkdir()
# An isolated PATH tests missing publishers without relying on the host.
for tool in ('awk', 'dirname'):
(self.tools / tool).symlink_to(shutil.which(tool))
self.capture = self.root / 'captured.json'
self.fake = self.tools / 'rust_realease'
self.fake.write_text('#!' + sys.executable + '\n' + '''import json, os, pathlib, sys
repository = pathlib.Path(sys.argv[1])
cross_config = pathlib.Path(os.environ["CROSS_CONFIG"])
record = {"args": sys.argv[1:], "token": os.environ.get("GITEA_TOKEN"),
"fallback": (repository / "rust-release.toml").read_text(),
"cross_config": str(cross_config),
"cross_config_contents": cross_config.read_text()}
pathlib.Path(os.environ["CAPTURE"]).write_text(json.dumps(record))
sys.exit(int(os.environ.get("PUBLISHER_EXIT", "0")))
''')
self.fake.chmod(0o755)
self.token = self.root / 'token with spaces'
self.token.write_text('inert-test-token-123\nignored-second-line\n')
self.token.chmod(0o600)
self.env = {**os.environ, 'PATH': str(self.tools), 'CAPTURE': str(self.capture)}
self.env.pop('GITEA_TOKEN', None)
self.env.pop('PUBLISHER_EXIT', None)
subprocess.run(['git', 'init', '-q', str(self.project)], check=True)
subprocess.run(['git', '-C', str(self.project), 'remote', 'add', 'origin',
'git@git.dandaedre.com:idle-org/tiny-wb.git'], check=True)
def tearDown(self):
self.temporary.cleanup()
def run_wrapper(self, arguments, expected=0):
result = subprocess.run(['/bin/sh', str(self.project / 'release.sh'), *arguments],
cwd=self.root, env=self.env, capture_output=True, text=True)
self.assertEqual(result.returncode, expected, result.stderr)
self.assertNotIn('inert-test-token-123', result.stdout + result.stderr)
return result
def set_version(self, version):
manifest = self.project / 'Cargo.toml'
text = manifest.read_text()
old = tomllib.loads(text)['package']['version']
manifest.write_text(text.replace(f'version = "{old}"', f'version = "{version}"', 1))
def test_exact_arguments_token_environment_and_fallback(self):
before = subprocess.check_output(['git', '-C', str(self.project), 'remote', 'get-url', 'origin'])
extra = ['--dry-run', '--message-file', 'notes with spaces; $(not-a-command) *.md']
self.run_wrapper([self.token.name, *extra])
record = json.loads(self.capture.read_text())
version = tomllib.loads((self.project / 'Cargo.toml').read_text())['package']['version']
prerelease = ['--prerelease'] if '-' in version.split('+', 1)[0] else []
self.assertEqual(record['args'], [str(self.project), '--package', 'tiny-wb',
'--artifact-format', 'both', *extra, *prerelease])
self.assertEqual(record['token'], 'inert-test-token-123')
self.assertNotIn(record['token'], '\n'.join(record['args']))
self.assertEqual(tomllib.loads(record['cross_config_contents']), {
'target': {'x86_64-unknown-linux-gnu': {
'pre-build': [
'apt-get update && apt-get install --assume-yes '
'--no-install-recommends libudev-dev pkg-config']}}})
self.assertEqual(Path(record['cross_config']), self.project / 'release' / 'Cross.toml')
self.assertTrue(Path(record['cross_config']).is_file())
config = tomllib.loads(record['fallback'])
self.assertEqual(config['repository']['fallbacks'], [{
'origin': before.decode().strip(),
'fallback-url': 'https://proxy.dandaedre.com/gitea/idle-org/tiny-wb'}])
after = subprocess.check_output(['git', '-C', str(self.project), 'remote', 'get-url', 'origin'])
self.assertEqual(before, after)
def test_prerelease_and_build_metadata(self):
for version, prerelease in [('1.2.3', False), ('1.2.3-rc.1', True),
('1.2.3+build-with-hyphen', False), ('1.2.3-rc.1+build', True)]:
with self.subTest(version=version):
self.set_version(version)
self.run_wrapper([str(self.token), '--dry-run'])
self.assertEqual('--prerelease' in json.loads(self.capture.read_text())['args'], prerelease)
def test_publisher_exit_status_and_nonterminated_token(self):
self.env['PUBLISHER_EXIT'] = '37'
self.token.write_text('inert-test-token-123')
self.run_wrapper([str(self.token), '--compile-only'], expected=37)
record = json.loads(self.capture.read_text())
self.assertEqual(record['token'], 'inert-test-token-123')
def test_compile_only_needs_no_token(self):
self.run_wrapper(['--compile-only', '--recompile'])
record = json.loads(self.capture.read_text())
version = tomllib.loads((self.project / 'Cargo.toml').read_text())['package']['version']
prerelease = ['--prerelease'] if '-' in version.split('+', 1)[0] else []
self.assertEqual(record['args'], [str(self.project), '--package', 'tiny-wb',
'--artifact-format', 'both', '--compile-only',
'--recompile', *prerelease])
self.assertIsNone(record['token'])
def test_missing_release_cross_config_never_invokes_publisher(self):
(self.project / 'release' / 'Cross.toml').unlink()
result = self.run_wrapper(['--compile-only'], expected=2)
self.assertIn('release Cross configuration is missing or unreadable', result.stderr)
self.assertFalse(self.capture.exists())
def test_invalid_token_inputs_never_invoke_publisher(self):
self.run_wrapper([], expected=2)
self.run_wrapper([str(self.root / 'missing')], expected=2)
self.run_wrapper([str(self.root)], expected=2)
for contents in ('', '\nsecond-line-is-not-a-token\n'):
self.token.write_text(contents)
self.run_wrapper([str(self.token)], expected=2)
self.assertFalse(self.capture.exists())
@unittest.skipIf(os.geteuid() == 0, 'root bypasses ordinary readability checks')
def test_unreadable_token(self):
self.token.chmod(0)
try:
self.run_wrapper([str(self.token)], expected=2)
self.assertFalse(self.capture.exists())
finally:
self.token.chmod(0o600)
def test_missing_publisher_and_unresolved_version(self):
self.fake.unlink()
self.run_wrapper([str(self.token)], expected=2)
self.fake.write_text('#!/bin/sh\nexit 99\n')
self.fake.chmod(0o755)
for manifest in ('[package]\nname="tiny-wb"\n',
'[package]\nversion.workspace=true\n[dependencies.example]\nversion="1.2.3"\n',
'[package]\nversion="not-semver"\n'):
(self.project / 'Cargo.toml').write_text(manifest)
self.run_wrapper([str(self.token)], expected=2)
(self.project / 'Cargo.toml').unlink()
self.run_wrapper([str(self.token)], expected=2)
def test_xtrace_does_not_expose_token(self):
result = subprocess.run(['/bin/sh', '-x', str(self.project / 'release.sh'), str(self.token), '--dry-run'],
cwd=self.root, env=self.env, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn('inert-test-token-123', result.stdout + result.stderr)
def test_metadata_agrees_with_tag_and_archive_policy(self):
manifest = tomllib.loads((REPO / 'Cargo.toml').read_text())['package']
config = tomllib.loads((REPO / 'rust-release.toml').read_text())
self.assertEqual(manifest['name'], 'tiny-wb')
self.assertEqual(config['release']['tag-prefix'], '')
self.assertEqual(config['build']['profile'], 'release')
self.assertTrue(config['build']['locked'])
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'], {
'pkg-url': '{ repo }/releases/download/{ version }/{ name }-{ target }-v{ version }.tgz',
'pkg-fmt': 'tgz',
'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__':
unittest.main()

725
src/acquisition.rs Normal file
View File

@ -0,0 +1,725 @@
//! Acquisition orchestration over an injected shell connection.
//!
//! This layer owns command ordering and progress, but not port discovery, files,
//! UI state or threads. After attempting `pause`, it always attempts `resume`,
//! preserving both failures when recovery also fails. This is not full device
//! state restoration. Identity and the required command inventory are checked
//! before model-specific settings are changed.
use crate::{
config::{ModelSelection, ScanConfig, SerialConfig},
device::{DeviceError, DeviceIdentity, DeviceModel},
protocol::{self, ProtocolError, Sample, ScanRequest},
transport::{Shell, TransportError},
};
use std::{
io::{Read, Write},
time::Duration,
};
/// UI-neutral acquisition notifications.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScanEvent {
/// Description of the active operation.
Message(&'static str),
/// Approximate completion percentage, from 0 through 100.
Progress(u8),
/// Unparsed version and information replies; not a verified model identity.
InstrumentInfo(String),
}
/// Failure running a scan; no output file is created by this layer.
#[derive(Debug, thiserror::Error)]
pub enum AcquisitionError {
/// An I/O or shell framing failure.
#[error(transparent)]
Transport(#[from] TransportError),
/// Invalid request or malformed binary frame.
#[error(transparent)]
Protocol(#[from] ProtocolError),
/// An identification reply contained no content.
#[error("the instrument returned an empty version or info reply")]
MissingIdentity,
/// Identity did not unambiguously identify a supported device family.
#[error(transparent)]
Device(#[from] DeviceError),
/// A configured family expectation did not match the detected device.
#[error("configured model {expected} does not match detected {actual}")]
UnexpectedModel {
/// Family required by configuration.
expected: DeviceModel,
/// Family established from device replies.
actual: DeviceModel,
},
/// The device does not advertise a command required by this scan plan.
#[error("{model} firmware does not advertise required command {command:?}")]
MissingCommand {
/// Detected family.
model: DeviceModel,
/// Required console command verb.
command: &'static str,
},
/// The firmware did not return a parseable raw-level offset after setting it.
#[error("could not confirm the raw-level offset after configuring zero {requested}")]
MissingZeroReadback {
/// Offset sent to the device, in dB.
requested: u16,
},
/// The raw-level offset readback differed from the requested decoder value.
#[error("raw-level offset readback is {actual} dB after requesting {requested} dB")]
ZeroReadbackMismatch {
/// Offset sent to the device, in dB.
requested: u16,
/// Offset reported by the device, in dB.
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.
#[error("{primary}; additionally, resume failed: {recovery}")]
Recovery {
/// Original acquisition failure.
#[source]
primary: Box<AcquisitionError>,
/// Failure attempting to restart the instrument's normal sweep.
recovery: TransportError,
},
}
/// Detect the device, execute a supported acquisition and return decoded samples.
///
/// Settings should come from a validated [`crate::config::Config`]. The request
/// is structurally validated before I/O and checked against the detected model
/// before mutation. Basic supports its existing low/high paths through 960 MHz.
/// 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>(
shell: &mut Shell<T>,
request: &ScanRequest,
scan: &ScanConfig,
serial: &SerialConfig,
mut report: impl FnMut(ScanEvent),
) -> 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()?;
let delay = Duration::from_millis(serial.command_delay_ms);
let settle = Duration::from_millis(serial.settle_delay_ms);
report(ScanEvent::Message("Identifying instrument"));
report(ScanEvent::Progress(5));
shell.synchronize()?;
let identity = identify_with_retry(shell, delay, settle, report)?;
let expected = match scan.device_model {
ModelSelection::Auto => None,
ModelSelection::Basic => Some(DeviceModel::Basic),
ModelSelection::Ultra => Some(DeviceModel::Ultra),
};
if let Some(expected) = expected.filter(|expected| *expected != identity.model) {
return Err(AcquisitionError::UnexpectedModel {
expected,
actual: identity.model,
});
}
let plan = identity.plan(request, scan.enable_ultra_mode)?;
let help = shell.command("help", delay, settle)?;
for command in [
"repeat", "zero", "pause", "mode", "sweep", "scanraw", "resume",
]
.into_iter()
.chain(plan.enable_ultra_mode.then_some("ultra"))
.chain(scan.legacy_pre_scan.then_some("scan"))
{
if !advertises_command(&help, command) {
return Err(AcquisitionError::MissingCommand {
model: identity.model,
command,
});
}
}
let revision = identity
.ultra_revision
.map(|revision| format!(" {revision}"))
.unwrap_or_default();
report(ScanEvent::InstrumentInfo(format!(
"Detected {}{} (native raw offset {} dB)\n{}{}",
identity.model, revision, plan.native_zero_offset_db, identity.version, identity.info
)));
for command in ["leveloffset", "vbat", "usart_cfg", "threads", "marker"] {
if advertises_command(&help, command) {
let response = shell.command(command, delay, settle)?;
log::debug!("{command}: {response}");
}
}
report(ScanEvent::Message("Configuring scan"));
let zero_offset = if scan.auto_zero_offset {
plan.native_zero_offset_db
} else {
scan.zero_offset
};
shell.command_checked(&format!("repeat {}", request.repeat), delay, settle)?;
shell.command_checked(&format!("zero {zero_offset}"), delay, settle)?;
let zero_response = shell.command("zero", delay, settle)?;
match parse_zero_offset(&zero_response) {
Some(actual) if actual == zero_offset => {}
Some(actual) => {
return Err(AcquisitionError::ZeroReadbackMismatch {
requested: zero_offset,
actual,
});
}
None => {
return Err(AcquisitionError::MissingZeroReadback {
requested: zero_offset,
})
}
}
report(ScanEvent::Progress(20));
Ok(PreparedAcquisition {
delay,
settle,
plan,
zero_offset,
})
}
fn configure_paused<T: Read + Write>(
shell: &mut Shell<T>,
request: &ScanRequest,
scan: &ScanConfig,
serial: &SerialConfig,
prepared: PreparedAcquisition,
) -> Result<(), AcquisitionError> {
shell.command_checked("pause", prepared.delay, prepared.settle)?;
shell.command_checked(prepared.plan.input_command, prepared.delay, prepared.settle)?;
if prepared.plan.enable_ultra_mode {
shell.command_checked("ultra on", prepared.delay, prepared.settle)?;
}
shell.command_checked(
&format!("sweep start {}", request.start_hz),
prepared.delay,
prepared.settle,
)?;
shell.command_checked(
&format!("sweep stop {}", request.stop_hz),
prepared.delay,
prepared.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) {
(Ok(value), Ok(_)) => Ok(value),
(Err(primary), Err(recovery)) => Err(AcquisitionError::Recovery {
primary: Box::new(primary),
recovery,
}),
(Err(error), Ok(_)) => Err(error),
(Ok(_), Err(error)) => Err(error.into()),
}
}
/// 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 {
help.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
.any(|word| word.eq_ignore_ascii_case(command))
}
fn parse_zero_offset(response: &str) -> Option<u16> {
response.split_whitespace().find_map(|word| {
word.trim_matches(|character: char| !character.is_ascii_alphanumeric() && character != '-')
.to_ascii_lowercase()
.strip_suffix("dbm")
.and_then(|value| value.parse().ok())
})
}
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)]
mod tests {
use super::*;
use crate::config::Config;
use std::{
cell::Cell,
io::{self, Cursor},
sync::{Arc, Mutex},
};
/// Scripted replies plus shared command capture, independent of serialport.
struct Transcript {
input: Cursor<Vec<u8>>,
commands: Arc<Mutex<Vec<u8>>>,
}
impl Read for Transcript {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
self.input.read(bytes)
}
}
impl Write for Transcript {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.commands.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn exercise(
frame: &[u8],
resume: bool,
legacy: bool,
) -> (
Result<Vec<Sample>, AcquisitionError>,
String,
Vec<ScanEvent>,
) {
let mut config = Config::default();
config.serial.command_delay_ms = 0;
config.serial.settle_delay_ms = 0;
config.serial.scan_delay_ms = 0;
config.scan.legacy_pre_scan = legacy;
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 scan scanraw resume leveloffset vbat usart_cfg threads marker\r\nch>".to_vec();
// Five optional diagnostics, repeat, zero mutation/readback, pause, mode and sweep commands.
input.extend_from_slice(b"okch>".repeat(7).as_slice());
input.extend_from_slice(b"usage: zero {level}\r\n128dBm\r\nch>");
input.extend_from_slice(b"okch>".repeat(5 + usize::from(legacy)).as_slice());
input.extend_from_slice(frame);
input.extend_from_slice(b"ch>");
if resume {
input.extend_from_slice(b"okch>");
}
let commands = Arc::new(Mutex::new(Vec::new()));
let mut shell = Shell::new(
Transcript {
input: Cursor::new(input),
commands: commands.clone(),
},
256,
);
let mut events = Vec::new();
let result = acquire(
&mut shell,
&request,
&config.scan,
&config.serial,
|event| events.push(event),
);
let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap();
(result, written, events)
}
#[test]
fn full_acquisition_preserves_command_order_and_reports_progress() {
let (result, commands, events) = exercise(b"{x\0\x08x\0\x10}", true, true);
assert_eq!(result.unwrap().len(), 2);
assert_eq!(commands, "version\rinfo\rhelp\rleveloffset\rvbat\rusart_cfg\rthreads\rmarker\rrepeat 1\rzero 128\rzero\rpause\rmode high input\rsweep start 240000000\rsweep stop 960000000\rsweep\rscan 240000000 960000000 290 101\rscanraw 240000000 960000000 2\rresume\r");
assert_eq!(events.last(), Some(&ScanEvent::Progress(100)));
assert!(events.iter().any(|event| matches!(event, ScanEvent::InstrumentInfo(info) if info.contains("Detected tinySA Basic"))));
}
#[test]
fn legacy_pre_scan_can_be_disabled() {
let (result, commands, _) = exercise(b"{x\0\x08x\0\x10}", true, false);
assert!(result.is_ok());
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]
fn malformed_frames_still_resume_and_preserve_original_error() {
let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", true, true);
assert!(matches!(
result,
Err(AcquisitionError::Protocol(ProtocolError::Alignment {
index: 0,
..
}))
));
assert!(commands.ends_with("resume\r"));
let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", false, true);
assert!(matches!(result, Err(AcquisitionError::Recovery { .. })));
assert!(commands.ends_with("resume\r"));
}
#[test]
fn help_and_zero_readback_parsers_are_token_bounded() {
assert!(advertises_command("Commands: scan scanraw zero", "scan"));
assert!(!advertises_command("Commands: scanraw", "scan"));
assert_eq!(
parse_zero_offset("usage: zero {level}\r\n174dBm\r\n"),
Some(174)
);
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]
fn failed_detection_capabilities_and_readback_stop_before_scan() {
for (version, info, help, zero, expected) in [
("unknown", "unknown", "", "", "unsupported device"),
("tinySA_v1", "tinySA Ultra", "", "", "conflicting"),
(
"tinySA4_v1",
"tinySA Ultra",
"repeat",
"",
"required command",
),
(
"tinySA4_v1",
"tinySA Ultra",
"repeat zero pause mode sweep scanraw resume",
"128dBm",
"readback is 128",
),
(
"tinySA4_v1",
"tinySA Ultra",
"repeat zero pause mode sweep scanraw resume",
"unknown",
"could not confirm",
),
] {
let config = Config::from_toml(
"[scan]\nlegacy_pre_scan=false\n[serial]\ncommand_delay_ms=0\nsettle_delay_ms=0",
)
.unwrap();
let commands = Arc::new(Mutex::new(Vec::new()));
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(
Transcript {
input: Cursor::new(input.into_bytes()),
commands: commands.clone(),
},
1024,
);
let request = ScanRequest {
start_hz: 100_000_000,
stop_hz: 800_000_000,
points: 2,
repeat: 1,
};
let error =
acquire(&mut shell, &request, &config.scan, &config.serial, |_| {}).unwrap_err();
assert!(error.to_string().contains(expected), "{error}");
let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap();
assert!(!written.contains("pause\r"));
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"));
}
}

494
src/config.rs Normal file
View File

@ -0,0 +1,494 @@
//! Typed configuration with embedded defaults and validated partial overrides.
//!
//! The six original top-level selection keys remain supported. Missing files
//! use defaults; unreadable files, unknown keys and invalid values are errors.
//! Paths in settings are relative to the process working directory.
use serde::{Deserialize, Serialize};
use std::{
fs, io,
path::{Path, PathBuf},
};
/// Human-readable defaults, also used by tests and packaged with the binary.
pub const DEFAULT_CONFIG: &str = include_str!("../config/default.toml");
/// Failures reading, validating or persisting configuration.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
/// The path could not be read or atomically replaced.
#[error("configuration I/O: {0}")]
Io(#[from] io::Error),
/// TOML syntax or a typed setting is invalid.
#[error("invalid configuration: {0}")]
Parse(#[from] toml::de::Error),
/// Serialization failed before replacing the existing file.
#[error("cannot serialize configuration: {0}")]
Serialize(#[from] toml::ser::Error),
/// A setting violates an application invariant.
#[error("invalid configuration: {0}")]
Validation(String),
}
/// Complete application settings; fields retain units from the configuration file.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Config {
/// Preferred serial port; empty selects the first available candidate.
pub port: String,
/// Selected baud rate, which must occur in `serial.baudrates`.
pub baudrate: u32,
/// Scan start in MHz, within the application's 0–5,400 MHz envelope.
pub start_frequency: usize,
/// Scan stop in MHz, no lower than the start.
pub stop_frequency: usize,
/// Number of samples in the raw scan.
pub points: usize,
/// Measurements per point.
pub repeat: usize,
/// Serial or TCP transport selection; TCP is useful for bridges and simulation.
pub connection: ConnectionConfig,
/// Serial timing, response limits and selection preferences.
pub serial: SerialConfig,
/// Acquisition and numeric input policy.
pub scan: ScanConfig,
/// Rendering and event timing.
pub ui: UiConfig,
/// CSV destination and format.
pub output: OutputConfig,
/// File logging settings.
pub logging: LoggingConfig,
}
/// Transport selected by the application, without changing shell framing.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Backend {
/// A native USB/serial port (requires the `serial` Cargo feature).
Serial,
/// A TCP bridge or mock server; tinySA hardware does not provide native TCP.
Tcp,
}
/// Connection settings; read deadlines apply to individual I/O operations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ConnectionConfig {
/// Which connection adapter to open.
pub backend: Backend,
/// Numeric IPv4/IPv6 socket address used for TCP (no DNS lookup).
pub tcp_address: String,
/// TCP connect, read and write timeout, in milliseconds.
pub tcp_timeout_ms: u64,
}
/// Serial settings, separate from the protocol's fixed byte grammar.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct SerialConfig {
/// Maximum idle wait for each read, in milliseconds.
pub timeout_ms: u64,
/// Delay after sending ordinary commands, in milliseconds.
pub command_delay_ms: u64,
/// Delay after a response, in milliseconds.
pub settle_delay_ms: u64,
/// Delay after the legacy preparatory scan, in milliseconds.
pub scan_delay_ms: u64,
/// Maximum text response or pre-frame echo size, in bytes.
pub max_response_bytes: usize,
/// Selectable nonzero baud rates, without duplicates.
pub baudrates: Vec<u32>,
/// Fallback port names, tried in order after `port`.
pub preferred_ports: Vec<String>,
}
/// Frequency labeling policy; this does not change the instrument's sweep.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FrequencyAxis {
/// Preserve legacy tiny-wb labels, including the requested stop frequency.
Inclusive,
/// Match the reviewed `scanraw` integer and single-precision calculation.
Firmware,
}
/// Optional identity expectation; acquisition always detects the connected family.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ModelSelection {
/// Accept either recognized family and apply its profile automatically.
Auto,
/// Require a detected tinySA Basic.
Basic,
/// Require a detected tinySA Ultra/Ultra+ family device.
Ultra,
}
/// Scan settings; model-specific frequency limits are enforced by device plans.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ScanConfig {
/// Expected device family; `auto` still rejects unknown or conflicting identity.
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.
pub auto_zero_offset: bool,
/// Offset sent with `zero` and subtracted from raw levels, in dB.
/// Used only when `auto_zero_offset` is false.
pub zero_offset: u16,
/// Keyboard step for frequencies, in MHz.
pub frequency_step_mhz: usize,
/// Keyboard step for sample count.
pub points_step: usize,
/// Lowest selectable sample count; at least two.
pub min_points: usize,
/// Highest selectable sample count; at most 1,000,001.
pub max_points: usize,
/// Highest repeat count; at most the firmware limit of 1,000.
pub max_repeat: usize,
/// Host-side frequency labeling convention.
pub frequency_axis: FrequencyAxis,
/// Whether to retain the legacy `scan START STOP 290 101` preparation.
pub legacy_pre_scan: bool,
}
/// Settings for the terminal presentation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct UiConfig {
/// Maximum event polling interval, in milliseconds.
pub poll_interval_ms: u64,
/// Chart lower bound, in dBm; finite and lower than the upper bound.
pub chart_min_dbm: f64,
/// Chart upper bound, in dBm.
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.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct OutputConfig {
/// Directory for completed scans; created on export if absent.
pub directory: PathBuf,
/// Filename prefix containing only ASCII letters, digits, `_` or `-`.
pub filename_prefix: String,
/// Emit a `frequency_MHz,level_dBm` header when true.
pub include_header: bool,
}
/// Settings accepted by the file logger.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct LoggingConfig {
/// flexi_logger filter expression, for example `info,tiny_wb=debug`.
pub filter: String,
/// Log destination directory.
pub directory: PathBuf,
}
impl Default for Config {
fn default() -> Self {
toml::from_str(DEFAULT_CONFIG).expect("embedded configuration must be valid")
}
}
impl Config {
/// Overlay a partial TOML document onto embedded defaults and validate it.
///
/// # Errors
/// Returns an error for unknown keys, malformed TOML or invalid settings.
pub fn from_toml(contents: &str) -> Result<Self, ConfigError> {
let mut defaults: toml::Value = toml::from_str(DEFAULT_CONFIG)?;
merge(&mut defaults, toml::from_str(contents)?);
let config: Self = defaults.try_into()?;
config.validate()?;
Ok(config)
}
/// Load settings, using defaults only if the path does not exist.
pub fn load(path: &Path) -> Result<Self, ConfigError> {
match fs::read_to_string(path) {
Ok(contents) => Self::from_toml(&contents),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
Err(error) => Err(error.into()),
}
}
/// Validate and atomically replace settings without depending on UI state.
///
/// All recognized sections survive saving; formatting and comments do not.
/// The parent directory must exist. The old file survives a failed write.
pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
self.validate()?;
crate::storage::replace(path, toml::to_string_pretty(self)?.as_bytes())?;
Ok(())
}
/// Check bounds before values become allocations, durations or scan commands.
pub fn validate(&self) -> Result<(), ConfigError> {
let require = |condition, message: &str| {
if condition {
Ok(())
} else {
Err(ConfigError::Validation(message.into()))
}
};
require(
!self.serial.baudrates.is_empty() && self.serial.baudrates.iter().all(|&v| v > 0),
"serial.baudrates must contain nonzero values",
)?;
let mut rates = self.serial.baudrates.clone();
rates.sort_unstable();
rates.dedup();
require(
rates.len() == self.serial.baudrates.len(),
"serial.baudrates must not contain duplicates",
)?;
require(
rates.contains(&self.baudrate),
"baudrate must be in serial.baudrates",
)?;
require(
self.start_frequency <= self.stop_frequency
&& self.stop_frequency <= 5_400
&& self.stop_frequency >= 10,
"frequencies must be ordered in 0–5400 MHz, with stop at least 10 MHz",
)?;
require(
self.scan.min_points >= 2
&& self.scan.min_points <= self.scan.max_points
&& self.scan.max_points <= 1_000_001,
"scan point bounds must satisfy 2 <= min_points <= max_points <= 1000001",
)?;
require(
(self.scan.min_points..=self.scan.max_points).contains(&self.points),
"points must be within scan.min_points and scan.max_points",
)?;
require(
(1..=1000).contains(&self.scan.max_repeat)
&& (1..=self.scan.max_repeat).contains(&self.repeat),
"repeat must be within 1..=scan.max_repeat, which cannot exceed 1000",
)?;
require(
(1..=5_400).contains(&self.scan.frequency_step_mhz)
&& (1..=self.scan.max_points).contains(&self.scan.points_step),
"scan keyboard steps must be positive and within their bounds",
)?;
require(
self.scan.zero_offset <= 2047,
"scan.zero_offset must fit the 16-bit fixed-point encoding (0..=2047)",
)?;
require(
(1..=600_000).contains(&self.serial.timeout_ms),
"serial.timeout_ms must be in 1..=600000",
)?;
require(
(1..=600_000).contains(&self.connection.tcp_timeout_ms),
"connection.tcp_timeout_ms must be in 1..=600000",
)?;
require(
self.connection
.tcp_address
.parse::<std::net::SocketAddr>()
.is_ok_and(|address| address.port() != 0),
"connection.tcp_address must be a numeric IP:port with a nonzero port",
)?;
for delay in [
self.serial.command_delay_ms,
self.serial.settle_delay_ms,
self.serial.scan_delay_ms,
] {
require(
delay <= 60_000,
"serial command delays cannot exceed 60000 ms",
)?;
}
require(
(256..=16_777_216).contains(&self.serial.max_response_bytes),
"serial.max_response_bytes must be in 256..=16777216",
)?;
require(
(1..=1000).contains(&self.ui.poll_interval_ms),
"ui.poll_interval_ms must be in 1..=1000",
)?;
require(
self.ui.chart_min_dbm.is_finite()
&& self.ui.chart_max_dbm.is_finite()
&& self.ui.chart_min_dbm < self.ui.chart_max_dbm,
"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.directory.as_os_str().is_empty()
&& !self.logging.directory.as_os_str().is_empty(),
"output and logging directories must not be empty",
)?;
require(
!self.logging.filter.trim().is_empty(),
"logging.filter must not be empty",
)
}
}
/// Recursively overlay supplied tables; scalar and array values replace defaults.
fn merge(base: &mut toml::Value, overrides: toml::Value) {
match (base, overrides) {
(toml::Value::Table(base), toml::Value::Table(overrides)) => {
for (key, value) in overrides {
if let Some(original) = base.get_mut(&key) {
merge(original, value);
} else {
base.insert(key, value);
}
}
}
(base, value) => *base = value,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_and_legacy_settings_are_supported() {
Config::default().validate().unwrap();
assert_eq!(
Config::default().scan.frequency_axis,
FrequencyAxis::Firmware
);
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.points, 101);
assert!(!config.scan.enable_ultra_mode);
assert_eq!(config.serial, Config::default().serial);
assert_eq!(
Config::from_toml("[scan]\nfrequency_axis = 'inclusive'")
.unwrap()
.scan
.frequency_axis,
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]
fn partial_sections_merge_and_round_trip() {
let config =
Config::from_toml("[serial]\ntimeout_ms = 5000\n[output]\ninclude_header = true")
.unwrap();
assert_eq!(config.serial.timeout_ms, 5000);
assert_eq!(config.serial.baudrates, Config::default().serial.baudrates);
assert!(config.output.include_header);
assert_eq!(
Config::from_toml(&toml::to_string(&config).unwrap()).unwrap(),
config
);
}
#[test]
fn malformed_unknown_and_unsafe_settings_are_rejected() {
for input in [
"broken",
"pointz = 100",
"points = 1",
"start_frequency = 5401",
"start_frequency = 900\nstop_frequency = 100",
"repeat = 0",
"[serial]\nbaudrates = []",
"[serial]\nbaudrates = [115200, 115200]",
"[serial]\ntimeout_ms = 0",
"[serial]\nmax_response_bytes = 0",
"[scan]\nmin_points = 0",
"[scan]\nfrequency_step_mhz = 0",
"[scan]\nzero_offset = 2048",
"[scan]\ndevice_model = 'unknown'",
"[scan]\nfrequency_axis = 'unknown'",
"[ui]\nchart_min_dbm = nan",
"[ui]\nchart_min_dbm = 1.0",
"[ui.bindings]\nzoom_in = []",
"[ui.bindings]\nzoom_in = ['q']",
"[ui.bindings]\nzoom_in = ['left']",
"[output]\nfilename_prefix = '../scan'",
"[logging]\nfilter = ''",
"[serial]\ntimeuot_ms = 5",
] {
assert!(Config::from_toml(input).is_err(), "accepted {input}");
}
}
#[test]
fn persistence_preserves_settings_and_rejects_invalid_replacement() {
let directory = std::env::temp_dir().join(format!("tiny-wb-config-{}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
let path = directory.join("settings.toml");
assert_eq!(
Config::load(&directory.join("missing")).unwrap(),
Config::default()
);
let mut config = Config::from_toml("[output]\ninclude_header = true").unwrap();
config.save(&path).unwrap();
assert_eq!(Config::load(&path).unwrap(), config);
let original = fs::read(&path).unwrap();
config.points = 0;
assert!(config.save(&path).is_err());
assert_eq!(fs::read(&path).unwrap(), original);
assert!(Config::load(&directory).is_err());
fs::write(&path, "unknown = true").unwrap();
assert!(Config::load(&path).is_err());
assert_eq!(fs::read_dir(&directory).unwrap().count(), 1);
fs::remove_dir_all(directory).unwrap();
}
}

136
src/connection.rs Normal file
View File

@ -0,0 +1,136 @@
//! Optional physical serial and portable TCP adapters for the same shell codec.
//!
//! Integrations may instead supply their own `Read + Write` stream directly to
//! [`crate::transport::Shell`]. TCP means an explicit bridge or mock server,
//! not native network support on the instrument.
use crate::config::{Backend, Config, ConfigError};
use std::{
io::{self, Read, Write},
net::TcpStream,
time::Duration,
};
/// An error opening a configured connection, before any command is sent.
#[derive(Debug, thiserror::Error)]
pub enum ConnectionError {
/// Settings failed validation.
#[error(transparent)]
Config(#[from] ConfigError),
/// The TCP connection or its timeout configuration failed.
#[error("TCP connection: {0}")]
Tcp(#[from] io::Error),
/// Native serial opening failed.
#[cfg(feature = "serial")]
#[error("serial connection: {0}")]
Serial(#[from] serialport::Error),
/// Native serial support was omitted from this library build.
#[error("enable the serial Cargo feature to open a USB/serial device")]
SerialFeatureDisabled,
}
/// A runtime-selected stream; the protocol layer only sees `Read + Write`.
pub enum Connection {
/// TCP socket with configured operation timeouts.
Tcp(TcpStream),
/// Native serial port with a configured read timeout.
#[cfg(feature = "serial")]
Serial(Box<dyn serialport::SerialPort>),
}
/// Validate settings and open the selected backend without sending commands.
///
/// TCP uses numeric addresses and bounded connect/read/write operations. Serial
/// is optional so library consumers do not require system libudev by default
/// when using `default-features = false`.
pub fn open_connection(config: &Config) -> Result<Connection, ConnectionError> {
config.validate()?;
match config.connection.backend {
Backend::Tcp => {
let address = config
.connection
.tcp_address
.parse()
.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
let timeout = Duration::from_millis(config.connection.tcp_timeout_ms);
let stream = TcpStream::connect_timeout(&address, timeout)?;
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
stream.set_nodelay(true)?;
Ok(Connection::Tcp(stream))
}
Backend::Serial => {
#[cfg(feature = "serial")]
{
Ok(Connection::Serial(
serialport::new(&config.port, config.baudrate)
.timeout(Duration::from_millis(config.serial.timeout_ms))
.open()?,
))
}
#[cfg(not(feature = "serial"))]
{
Err(ConnectionError::SerialFeatureDisabled)
}
}
}
}
impl Read for Connection {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
match self {
Self::Tcp(stream) => stream.read(buffer),
#[cfg(feature = "serial")]
Self::Serial(stream) => stream.read(buffer),
}
}
}
impl Write for Connection {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match self {
Self::Tcp(stream) => stream.write(bytes),
#[cfg(feature = "serial")]
Self::Serial(stream) => stream.write(bytes),
}
}
fn flush(&mut self) -> io::Result<()> {
match self {
Self::Tcp(stream) => stream.flush(),
#[cfg(feature = "serial")]
Self::Serial(stream) => stream.flush(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tcp_configuration_is_validated_before_connecting() {
for input in [
"[connection]\nbackend='udp'",
"[connection]\ntcp_address='localhost:7355'",
"[connection]\ntcp_address='127.0.0.1:0'",
"[connection]\ntcp_timeout_ms=0",
] {
assert!(Config::from_toml(input).is_err());
}
let mut config = Config::default();
config.connection.tcp_address = "invalid".into();
assert!(matches!(
open_connection(&config),
Err(ConnectionError::Config(_))
));
}
#[cfg(not(feature = "serial"))]
#[test]
fn native_serial_requires_explicit_feature() {
assert!(matches!(
open_connection(&Config::default()),
Err(ConnectionError::SerialFeatureDisabled)
));
}
}

351
src/device.rs Normal file
View File

@ -0,0 +1,351 @@
//! Device identity parsing and model-specific acquisition policy.
//!
//! Identification consumes explicit `version`/`info` evidence. This module
//! selects acquisition behavior only from explicit family and hardware-revision
//! evidence. ZS406 Ultra mode is opt-in; harmonic mode remains unsupported.
use crate::protocol::{
ProtocolError, ScanRequest, BASIC_MAX_HZ, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB,
};
use std::fmt;
/// Lowest documented Ultra analyzer frequency, in Hz.
pub const ULTRA_MIN_HZ: u64 = 100_000;
/// Common normal-mode ceiling across supported Ultra family revisions, in Hz.
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.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceModel {
/// Original 2.8-inch tinySA with low and high input paths.
Basic,
/// tinySA Ultra/Ultra+ family, restricted here to the common normal range.
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 {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Basic => "tinySA Basic",
Self::Ultra => "tinySA Ultra family",
})
}
}
/// Identity replies retained together with the detected family.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceIdentity {
/// Detected device family.
pub model: DeviceModel,
/// Ultra-family hardware revision, when the replies contain explicit evidence.
pub ultra_revision: Option<UltraRevision>,
/// Verbatim prompt-stripped `version` response.
pub version: String,
/// Verbatim prompt-stripped `info` response.
pub info: String,
}
/// A validated model-specific command and decoding plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AcquisitionPlan {
/// Detected device family.
pub model: DeviceModel,
/// Model-correct console command selecting the input path.
pub input_command: &'static str,
/// Native raw-level encoding offset, in dB.
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.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DeviceError {
/// Neither reply contained a recognized model signature.
#[error("unsupported device identity; expected tinySA_v… or tinySA4_v… in version/info")]
Unknown,
/// Basic and Ultra signatures occurred in the same identity exchange.
#[error("conflicting device identity: replies identify both tinySA Basic and Ultra")]
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 {
/// Detect a Basic or Ultra family from `version` and `info` replies.
///
/// Basic firmware uses a `tinySA_v…` version token; Ultra-family firmware
/// uses `tinySA4_v…`. Explicit Basic/Ultra names in `info` are also accepted.
/// Shared source URLs and generic `tinySA` substrings are not sufficient.
pub fn detect(version: String, info: String) -> Result<Self, DeviceError> {
let version_lower = version.to_ascii_lowercase();
let info_lower = info.to_ascii_lowercase();
let ultra = version_lower
.split_whitespace()
.any(|token| token.starts_with("tinysa4_v"))
|| info_lower.contains("tinysa ultra");
let basic = version_lower
.split_whitespace()
.any(|token| token.starts_with("tinysa_v"))
|| info_lower.contains("tinysa basic")
|| info_lower.lines().any(|line| line.trim() == "tinysa");
let model = match (basic, ultra) {
(true, false) => DeviceModel::Basic,
(false, true) => DeviceModel::Ultra,
(true, true) => return Err(DeviceError::Conflicting),
(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 {
model,
ultra_revision,
version,
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 {
/// Validate a request against this family and choose its input command.
pub fn plan(self, request: &ScanRequest) -> Result<AcquisitionPlan, ProtocolError> {
request.validate()?;
let (input_command, native_zero_offset_db) = match self {
Self::Basic => {
if request.stop_hz > BASIC_MAX_HZ {
return Err(ProtocolError::InvalidRequest(
"tinySA Basic frequencies must be within 0–960 MHz".into(),
));
}
let command = if request.stop_hz < 350_000_000 {
"mode low input"
} else if request.start_hz >= 240_000_000 {
"mode high input"
} else {
return Err(ProtocolError::InvalidRequest(
"a Basic span crossing 350 MHz must start at or above 240 MHz".into(),
));
};
(command, BASIC_RAW_LEVEL_OFFSET_DB)
}
Self::Ultra => {
if request.start_hz < ULTRA_MIN_HZ || request.stop_hz > ULTRA_NORMAL_MAX_HZ {
return Err(ProtocolError::InvalidRequest(
"tinySA Ultra first-tier support is limited to the common 0.1–800 MHz normal range; extended and harmonic modes are not enabled"
.into(),
));
}
("mode low input", ULTRA_RAW_LEVEL_OFFSET_DB)
}
};
Ok(AcquisitionPlan {
model: self,
input_command,
native_zero_offset_db,
enable_ultra_mode: false,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn request(start_hz: u64, stop_hz: u64) -> ScanRequest {
ScanRequest {
start_hz,
stop_hz,
points: 101,
repeat: 1,
}
}
#[test]
fn identity_requires_unambiguous_family_evidence() {
assert_eq!(
DeviceIdentity::detect("tinySA_v1.4-175-gabc".into(), "tinySA".into())
.unwrap()
.model,
DeviceModel::Basic
);
assert_eq!(
DeviceIdentity::detect(
"tinySA4_v1.4-200-gabc\r\nHW Version:V0.4.6".into(),
"tinySA Ultra+ ZS406".into()
)
.unwrap()
.model,
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!(
DeviceIdentity::detect("version unknown".into(), "instrument".into()),
Err(DeviceError::Unknown)
);
assert_eq!(
DeviceIdentity::detect("tinySA_v1".into(), "tinySA Ultra".into()),
Err(DeviceError::Conflicting)
);
}
#[test]
fn model_plans_enforce_paths_ranges_and_native_offsets() {
let low = DeviceModel::Basic.plan(&request(0, 349_999_999)).unwrap();
assert_eq!(low.input_command, "mode low input");
assert_eq!(low.native_zero_offset_db, 128);
let high = DeviceModel::Basic
.plan(&request(240_000_000, 960_000_000))
.unwrap();
assert_eq!(high.input_command, "mode high input");
assert!(DeviceModel::Basic.plan(&request(0, 350_000_000)).is_err());
let ultra = DeviceModel::Ultra
.plan(&request(ULTRA_MIN_HZ, ULTRA_NORMAL_MAX_HZ))
.unwrap();
assert_eq!(ultra.input_command, "mode low input");
assert_eq!(ultra.native_zero_offset_db, 174);
assert!(DeviceModel::Ultra.plan(&request(0, 800_000_000)).is_err());
assert!(DeviceModel::Ultra
.plan(&request(100_000, 800_000_001))
.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());
}
}

61
src/error.rs Normal file
View File

@ -0,0 +1,61 @@
//! Application boundary errors; core modules keep their own typed errors.
/// Errors surfaced during startup or acquisition.
#[derive(Debug, thiserror::Error)]
pub(crate) enum AppError {
/// Command-line arguments do not select a supported startup mode.
#[error("{0}")]
Usage(String),
/// Configuration read, validation or persistence failed.
#[error(transparent)]
Config(#[from] tiny_wb::config::ConfigError),
/// Serial enumeration or opening failed.
#[error("serial connection: {0}")]
Port(#[from] serialport::Error),
/// Configured serial/TCP connection failed before acquisition.
#[error(transparent)]
Connection(#[from] tiny_wb::connection::ConnectionError),
/// Filesystem or terminal I/O failed.
#[error("I/O: {0}")]
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.
#[error(transparent)]
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.
#[error("logging: {0}")]
Logger(#[from] flexi_logger::FlexiLoggerError),
/// Error reporting or the terminal event loop failed.
#[error("terminal: {0}")]
Terminal(#[from] color_eyre::Report),
}
/// Errors from UI selection and transitions; rendering displays their context.
#[derive(Debug, thiserror::Error)]
pub(crate) enum UiError {
/// A selection index no longer belongs to its list.
#[error("selected menu item is unavailable")]
MenuSelection,
/// An internal widget was used before initialization.
#[error("widget {0} is not initialized ({2}:{1})")]
UninitializedItemList(&'static str, u32, &'static str),
/// No serial device is available or selected.
#[error("no serial port is selected; connect the instrument and restart")]
NoPortSelected,
/// Configuration or acquisition preparation failed.
#[error(transparent)]
Application(#[from] AppError),
/// Completed scan data was already consumed or never supplied.
#[error("the completed scan has no available samples")]
NoReturnData,
}

243
src/export.rs Normal file
View File

@ -0,0 +1,243 @@
//! CSV serialization and collision-safe file creation, separate from decoding.
use crate::{config::OutputConfig, protocol::Sample};
use jiff::ZonedDateTime;
use std::{
fs::{self, OpenOptions},
io::{self, BufRead, BufWriter, Write},
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.
///
/// The caller decides when/how to open and flush a file. Every write error is
/// propagated; decimal formatting uses Rust's locale-independent representation.
pub fn write_csv(
mut writer: impl Write,
samples: &[Sample],
include_header: bool,
) -> io::Result<()> {
if include_header {
writeln!(writer, "frequency_MHz,level_dBm")?;
}
for sample in samples {
writeln!(writer, "{},{}", sample.frequency_mhz, sample.level_dbm)?;
}
Ok(())
}
/// Save an already validated scan without overwriting any previous acquisition.
///
/// Names use local time plus microseconds and a collision counter. A file is
/// reported only after flushing; failed writes remove the incomplete file.
/// 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> {
fs::create_dir_all(&settings.directory)?;
let stamp = filename_stamp(&ZonedDateTime::now());
for suffix in 0..100 {
let path = settings
.directory
.join(format!("{}_{stamp}_{suffix}.csv", settings.filename_prefix));
let file = match OpenOptions::new().write(true).create_new(true).open(&path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
};
let mut writer = BufWriter::new(file);
let result = write_csv(&mut writer, samples, settings.include_header)
.and_then(|()| writer.flush())
.and_then(|()| writer.get_ref().sync_all());
drop(writer);
if let Err(error) = result {
let _ = fs::remove_file(&path);
return Err(error);
}
return Ok(path);
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"could not allocate a unique scan filename",
))
}
/// 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)]
mod tests {
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]
fn csv_has_explicit_units_only_when_requested() {
let samples = [Sample {
frequency_mhz: 240.5,
level_dbm: -64.25,
}];
let mut bytes = Vec::new();
write_csv(&mut bytes, &samples, false).unwrap();
assert_eq!(bytes, b"240.5,-64.25\n");
bytes.clear();
write_csv(&mut bytes, &samples, true).unwrap();
assert_eq!(bytes, b"frequency_MHz,level_dBm\n240.5,-64.25\n");
}
#[test]
fn write_errors_are_propagated() {
struct Broken;
impl Write for Broken {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Err(io::ErrorKind::BrokenPipe.into())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
assert_eq!(
write_csv(Broken, &[], true).unwrap_err().kind(),
io::ErrorKind::BrokenPipe
);
}
#[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]
fn scans_do_not_overwrite_each_other() {
let directory = std::env::temp_dir().join(format!("tiny-wb-export-{}", std::process::id()));
let settings = OutputConfig {
directory: directory.clone(),
filename_prefix: "test".into(),
include_header: false,
};
let samples = [Sample {
frequency_mhz: 1.0,
level_dbm: -1.0,
}];
let first = save_csv(&samples, &settings).unwrap();
let second = save_csv(&samples, &settings).unwrap();
assert_ne!(first, second);
assert_eq!(fs::read_to_string(first).unwrap(), "1,-1\n");
assert_eq!(fs::read_to_string(second).unwrap(), "1,-1\n");
fs::remove_dir_all(directory).unwrap();
}
}

36
src/lib.rs Normal file
View File

@ -0,0 +1,36 @@
//! Reusable configuration and acquisition building blocks for tiny-wb.
//!
//! The core does not depend on terminal state. Parsers and writers accept data
//! or I/O interfaces so callers can test them without a connected instrument.
//!
//! Disable default features for a library without terminal or native serial
//! dependencies. Enable `serial` for USB access or `mock` for deterministic
//! simulation. The application uses `tui` and `serial` by default.
//!
//! # Decode and export a recorded frame
//!
//! ```
//! use tiny_wb::{config::FrequencyAxis, export::write_csv, protocol::{decode_frame, ScanRequest}};
//!
//! let request = ScanRequest { start_hz: 240_000_000, stop_hz: 960_000_000, points: 2, repeat: 1 };
//! let samples = decode_frame(b"{x\x00\x08x\x00\x10}", &request, 128, FrequencyAxis::Firmware)?;
//! let mut csv = Vec::new();
//! write_csv(&mut csv, &samples, true)?;
//! assert_eq!(String::from_utf8(csv)?, "frequency_MHz,level_dBm\n240,-64\n600,0\n");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
#![warn(missing_docs)]
pub mod acquisition;
pub mod config;
pub mod connection;
pub mod device;
pub mod export;
pub mod live;
/// Opt-in deterministic simulator and TCP server support.
#[cfg(feature = "mock")]
pub mod mock;
pub mod protocol;
mod storage;
pub mod transport;

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

@ -1,38 +1,144 @@
//! A (rather) simple crate to interface with a tinySA
//!
//! As of now this crate is not written as a lib/tui
//! and will not offer any scripting capabilities
//! Startup wiring for the interactive tinySA acquisition application.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
// #![allow(dead_code)]
mod error;
mod scan;
mod structs;
mod ui;
mod ui_struct;
use color_eyre::Result;
// use human_panic::setup_panic;
use structs::TinyError;
use ui_struct::AppInfo;
use error::AppError;
use flexi_logger::{FileSpec, Logger, WriteMode};
use log;
use std::{ffi::OsString, fs::File, io::BufReader, path::PathBuf};
use tiny_wb::config::{Backend, Config};
fn main() -> Result<(), TinyError> {
let _logger = Logger::try_with_str("info, my::critical::module=trace")
.unwrap()
.log_to_file(FileSpec::default())
/// 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.
struct TerminalSession;
impl Drop for TerminalSession {
fn drop(&mut self) {
ratatui::restore();
}
}
/// Load and validate settings before taking ownership of the user's terminal.
fn main() -> Result<(), AppError> {
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")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("config.toml"));
let config = Config::load(&config_path).map_err(|error| {
eprintln!("Cannot load {}: {error}", config_path.display());
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)?
.log_to_file(FileSpec::default().directory(&config.logging.directory))
.write_mode(WriteMode::BufferAndFlush)
.start()?;
log::info!(target:"info","Logging started");
color_eyre::install()?;
let terminal = ratatui::init();
// setup_panic!();
let ports = serialport::available_ports()?;
let app_r = AppInfo::new(ports).run(terminal);
ratatui::restore();
app_r.map_err(TinyError::TUIRuntimeError)
let live_mode = mode == StartMode::Live;
let mut app = match mode {
StartMode::Acquire | StartMode::Live => {
let ports = match config.connection.backend {
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 terminal = ratatui::try_init()?;
app.run(terminal)?;
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());
}
}

506
src/mock/device.rs Normal file
View File

@ -0,0 +1,506 @@
//! Bounded, stateful console simulation and an in-memory duplex stream.
use crate::protocol::{
firmware_frequency_hz, ScanRequest, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB,
};
use serde::{Deserialize, Serialize};
use std::{
collections::VecDeque,
io::{self, Read, Write},
};
/// Synthetic identity and command differences, not hardware certification.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MockModel {
/// Basic low/high input syntax; initial raw offset 128 dB.
Basic,
/// Ultra input syntax, LNA/Ultra toggles; initial raw offset 174 dB.
Ultra,
}
/// One-shot fault applied to the first matching command in each new session.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MockFault {
/// Normal behavior.
#[default]
None,
/// Reject the command without changing device state.
Reject,
/// Drop the command and its response, making the next empty read time out.
Timeout,
/// Close the stream immediately without processing the command.
Disconnect,
/// Omit the trailing prompt after executing the command.
MissingPrompt,
/// Remove the end of a scanraw frame and its prompt.
TruncatedFrame,
/// Replace the first scanraw record's alignment byte.
BadAlignment,
}
/// Simulator policy, loadable from TOML independently of application settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct MockConfig {
/// Synthetic device identity.
pub model: MockModel,
/// Echo complete commands before responding.
pub echo: bool,
/// Maximum bytes returned per in-memory read (also server write chunk size).
pub read_chunk_bytes: usize,
/// Maximum bytes accepted per in-memory write, exercising complete writes.
pub write_chunk_bytes: usize,
/// TCP example read/write timeout, in milliseconds (1 through 600,000).
pub session_timeout_ms: u64,
/// Maximum command line size, before a terminator.
pub command_limit_bytes: usize,
/// Maximum requested scan points, bounding frame allocation.
pub max_points: usize,
/// Synthetic Ultra ceiling in Hz; not a hardware capability claim.
pub ultra_max_hz: u64,
/// Deterministic spectrum floor, in dBm.
pub floor_dbm: f64,
/// Triangular peak level, in dBm.
pub peak_dbm: f64,
/// Synthetic carrier center, in Hz.
pub peak_frequency_hz: u64,
/// Half-width of the triangular peak, in Hz.
pub peak_width_hz: u64,
/// One-shot response fault.
pub fault: MockFault,
/// Command verb on which to inject the fault, for example `scanraw`.
pub fault_command: String,
}
impl Default for MockConfig {
fn default() -> Self {
Self {
model: MockModel::Basic,
echo: true,
read_chunk_bytes: 4096,
write_chunk_bytes: 4096,
session_timeout_ms: 30_000,
command_limit_bytes: 256,
max_points: 10001,
ultra_max_hz: 6_000_000_000,
floor_dbm: -96.0,
peak_dbm: -32.0,
peak_frequency_hz: 300_000_000,
peak_width_hz: 10_000_000,
fault: MockFault::None,
fault_command: "scanraw".into(),
}
}
}
impl MockConfig {
/// Reject unbounded allocations, non-finite signal values and invalid fault settings.
pub fn validate(&self) -> io::Result<()> {
let valid = (1..=600_000).contains(&self.session_timeout_ms)
&& (1..=65536).contains(&self.read_chunk_bytes)
&& (1..=65536).contains(&self.write_chunk_bytes)
&& (16..=4096).contains(&self.command_limit_bytes)
&& (2..=1_000_001).contains(&self.max_points)
&& (960_000_000..=12_000_000_000).contains(&self.ultra_max_hz)
&& self.floor_dbm.is_finite()
&& self.peak_dbm.is_finite()
&& (-174.0..=100.0).contains(&self.floor_dbm)
&& (self.floor_dbm..=100.0).contains(&self.peak_dbm)
&& self.peak_frequency_hz <= 12_000_000_000
&& (1..=12_000_000_000).contains(&self.peak_width_hz)
&& !self.fault_command.is_empty()
&& self
.fault_command
.bytes()
.all(|b| b.is_ascii_lowercase() || b == b'_')
&& (!matches!(
self.fault,
MockFault::TruncatedFrame | MockFault::BadAlignment
) || self.fault_command == "scanraw");
if valid {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid mock configuration bounds or fault/command combination",
))
}
}
}
/// Observable simulated state. No field represents a physical measurement.
#[derive(Debug, Clone, PartialEq)]
pub struct MockState {
/// Synthetic model.
pub model: MockModel,
/// Whether normal sweeping is paused.
pub paused: bool,
/// Last selected input keyword (`low`, `high`, or `input`).
pub input: String,
/// Display sweep start, in Hz.
pub start_hz: u64,
/// Display sweep stop, in Hz.
pub stop_hz: u64,
/// Last requested raw scan sample count.
pub points: usize,
/// Measurement repeat count.
pub repeat: usize,
/// Offset used by raw fixed-point encoding, in dB.
pub zero_offset: u16,
/// Simulated LNA state (Ultra only; no RF effect).
pub lna: bool,
/// Simulated Ultra state (no RF effect).
pub ultra: bool,
/// Last 1,024 complete commands, oldest first; excludes overlong lines.
pub commands: VecDeque<String>,
}
/// A deterministic `Read + Write` fake instrument with partial I/O support.
///
/// Empty reads return `TimedOut`, not EOF; a disconnect fault returns EOF and
/// rejects later writes. Responses are generated only when commands arrive.
/// Use `Shell::new(&mut mock, limit)` to inspect state after dropping the shell.
pub struct MockStream {
config: MockConfig,
state: MockState,
input: Vec<u8>,
output: VecDeque<u8>,
discarding: bool,
connected: bool,
fault_used: bool,
}
impl MockStream {
/// Construct a fresh session with an initial shell prompt.
pub fn new(config: MockConfig) -> io::Result<Self> {
config.validate()?;
let state = MockState {
model: config.model,
paused: false,
input: if config.model == MockModel::Basic {
"low"
} else {
"input"
}
.into(),
start_hz: 240_000_000,
stop_hz: 960_000_000,
points: 101.min(config.max_points),
repeat: 1,
zero_offset: if config.model == MockModel::Basic {
BASIC_RAW_LEVEL_OFFSET_DB
} else {
ULTRA_RAW_LEVEL_OFFSET_DB
},
lna: false,
ultra: false,
commands: VecDeque::new(),
};
Ok(Self {
config,
state,
input: Vec::new(),
output: VecDeque::from(b"ch>".to_vec()),
discarding: false,
connected: true,
fault_used: false,
})
}
/// Read-only state and bounded command history, for assertions.
pub fn state(&self) -> &MockState {
&self.state
}
/// Whether a disconnect fault closed the simulated connection.
pub fn is_connected(&self) -> bool {
self.connected
}
/// Number of currently queued response bytes; used by the TCP adapter.
pub fn pending_bytes(&self) -> usize {
self.output.len()
}
/// Bound pipelined responses as well as individual scan allocations.
fn enqueue(&mut self, bytes: &[u8]) -> io::Result<()> {
let limit = self.config.max_points * 3 + self.config.command_limit_bytes + 65536;
if self.output.len().saturating_add(bytes.len()) > limit {
return Err(io::Error::new(
io::ErrorKind::OutOfMemory,
"mock response queue limit exceeded; read responses before pipelining commands",
));
}
self.output.extend(bytes);
Ok(())
}
fn execute(&mut self, command: &str) -> io::Result<()> {
if self.state.commands.len() == 1024 {
self.state.commands.pop_front();
}
self.state.commands.push_back(command.into());
let verb = command.split_whitespace().next().unwrap_or("");
let fault = if !self.fault_used && verb == self.config.fault_command {
self.fault_used = true;
self.config.fault
} else {
MockFault::None
};
match fault {
MockFault::Timeout => return Ok(()),
MockFault::Disconnect => {
self.connected = false;
self.output.clear();
return Ok(());
}
_ => {}
}
let mut response = if self.config.echo {
format!("{command}\r\n").into_bytes()
} else {
Vec::new()
};
let mut body = if fault == MockFault::Reject {
b"error: injected rejection\r\n".to_vec()
} else {
self.respond(command)
};
if fault == MockFault::BadAlignment && body.first() == Some(&b'{') {
body[1] = b'!';
}
if fault == MockFault::TruncatedFrame && body.first() == Some(&b'{') {
body.truncate(body.len().saturating_sub(4));
}
response.extend(body);
if !matches!(fault, MockFault::MissingPrompt | MockFault::TruncatedFrame) {
response.extend_from_slice(b"ch>");
}
self.enqueue(&response)
}
/// Unsupported commands fail explicitly rather than inventing successful firmware behavior.
fn respond(&mut self, command: &str) -> Vec<u8> {
let fields: Vec<_> = command.split_whitespace().collect();
let ok = b"".to_vec();
let invalid = || b"error: unsupported command or invalid arguments in mock\r\n".to_vec();
match fields.as_slice() {
[] => ok,
["version"] => match self.state.model {
MockModel::Basic => b"tinySA_v1.4-mock (synthetic)\r\n".to_vec(),
MockModel::Ultra => b"tinySA4_v1.4-mock (synthetic)\r\n".to_vec(),
},
["info"] => match self.state.model {
MockModel::Basic => b"tinySA\nmock; not real firmware\r\n".to_vec(),
MockModel::Ultra => b"tinySA Ultra mock; not real firmware\r\n".to_vec(),
},
["help"] => {
let extra = if self.state.model == MockModel::Ultra {
" lna ultra"
} else {
""
};
format!("Commands: version info help pause resume mode repeat zero sweep scan scanraw leveloffset vbat usart_cfg threads marker{extra}\r\n").into_bytes()
}
["pause"] => {
self.state.paused = true;
ok
}
["resume"] => {
self.state.paused = false;
ok
}
["mode", "low" | "high", "input"] if self.state.model == MockModel::Basic => {
self.state.input = fields[1].into();
ok
}
["mode", "input"] | ["mode", "low", "input"]
if self.state.model == MockModel::Ultra =>
{
self.state.input = "input".into();
ok
}
["lna", value] | ["ultra", value]
if self.state.model == MockModel::Ultra && matches!(*value, "on" | "off") =>
{
if fields[0] == "lna" {
self.state.lna = *value == "on";
} else {
self.state.ultra = *value == "on";
}
ok
}
["repeat", value] => match value.parse::<usize>() {
Ok(value) if (1..=1000).contains(&value) => {
self.state.repeat = value;
ok
}
_ => invalid(),
},
["zero", value] => match value.parse::<u16>() {
Ok(value) if value <= 2047 => {
self.state.zero_offset = value;
ok
}
_ => invalid(),
},
["zero"] => {
format!("usage: zero {{level}}\r\n{}dBm\r\n", self.state.zero_offset).into_bytes()
}
["sweep", "start" | "stop", value] => match value.parse::<u64>() {
Ok(value) if value <= self.max_hz() => {
if fields[1] == "start" {
self.state.start_hz = value;
} else {
self.state.stop_hz = value;
}
ok
}
_ => invalid(),
},
["sweep"] => format!(
"{} {} {}\r\n",
self.state.start_hz, self.state.stop_hz, self.state.points
)
.into_bytes(),
["scanraw", start, stop, points] => {
if let Some((start, stop, points)) = self.scan_arguments(start, stop, points) {
self.state.points = points;
let mut frame = Vec::with_capacity(points * 3 + 4);
frame.push(b'{');
let request = ScanRequest {
start_hz: start,
stop_hz: stop,
points,
repeat: self.state.repeat,
};
for index in 0..points {
let frequency = firmware_frequency_hz(&request, index) as f64;
let strength = (1.0
- (frequency - self.config.peak_frequency_hz as f64).abs()
/ self.config.peak_width_hz as f64)
.clamp(0.0, 1.0);
let level = self.config.floor_dbm
+ strength * (self.config.peak_dbm - self.config.floor_dbm);
let raw = ((level + f64::from(self.state.zero_offset)) * 32.0)
.round()
.clamp(0.0, 65535.0) as u16;
frame.push(b'x');
frame.extend(raw.to_le_bytes());
}
frame.extend_from_slice(b"}\r\n");
frame
} else {
invalid()
}
}
// Compatibility-only preparation used by the current application. No trace is returned.
["scan", start, stop, "290", "101"]
if self.scan_arguments(start, stop, "2").is_some() =>
{
ok
}
["leveloffset"] => b"leveloffset mock 0\r\n".to_vec(),
["vbat"] => b"4000 mV (mock)\r\n".to_vec(),
["usart_cfg"] => b"115200 (mock)\r\n".to_vec(),
["threads"] => b"mock: synchronous\r\n".to_vec(),
["marker"] => b"1 0 300000000 -32 (mock)\r\n".to_vec(),
_ => invalid(),
}
}
fn max_hz(&self) -> u64 {
if self.state.model == MockModel::Basic {
960_000_000
} else {
self.config.ultra_max_hz
}
}
fn scan_arguments(&self, start: &str, stop: &str, points: &str) -> Option<(u64, u64, usize)> {
let (start, stop, points) = (
start.parse::<u64>().ok()?,
stop.parse::<u64>().ok()?,
points.parse::<usize>().ok()?,
);
if start > stop || stop > self.max_hz() || !(2..=self.config.max_points).contains(&points) {
return None;
}
if self.state.model == MockModel::Basic {
let valid = match self.state.input.as_str() {
"low" => stop < 350_000_000,
"high" => start >= 240_000_000,
_ => false,
};
if !valid {
return None;
}
}
Some((start, stop, points))
}
}
impl Read for MockStream {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if buffer.is_empty() {
return Ok(0);
}
if self.output.is_empty() {
return if self.connected {
Err(io::ErrorKind::TimedOut.into())
} else {
Ok(0)
};
}
let count = buffer
.len()
.min(self.config.read_chunk_bytes)
.min(self.output.len());
for byte in &mut buffer[..count] {
*byte = self.output.pop_front().expect("queue length checked");
}
Ok(count)
}
}
impl Write for MockStream {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if bytes.is_empty() {
return Ok(0);
}
if !self.connected {
return Err(io::ErrorKind::BrokenPipe.into());
}
let count = bytes.len().min(self.config.write_chunk_bytes);
for (index, &byte) in bytes[..count].iter().enumerate() {
if matches!(byte, b'\r' | b'\n') {
if self.discarding {
self.discarding = false;
self.enqueue(b"error: command too long\r\nch>")?;
} else if !self.input.is_empty() {
let input = std::mem::take(&mut self.input);
match String::from_utf8(input) {
Ok(command) if command.bytes().all(|c| (b' '..=b'~').contains(&c)) => {
self.execute(&command)?
}
_ => self.enqueue(b"error: command must be printable ASCII\r\nch>")?,
}
}
} else if !self.discarding {
if self.input.len() == self.config.command_limit_bytes {
self.input.clear();
self.discarding = true;
} else {
self.input.push(byte);
}
}
if !self.connected {
return Ok(index + 1);
}
}
Ok(count)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}

26
src/mock/mod.rs Normal file
View File

@ -0,0 +1,26 @@
//! Deterministic tinySA console simulation for tests and local integrations.
//!
//! Enable the `mock` feature. This is a command/state simulator, not an RF model
//! or an emulator of a specific firmware release. [`crate::mock::MockStream`] and the TCP
//! server share the same parser and device state; neither needs serial drivers.
//! # Inspect state after a command
//!
//! ```
//! use tiny_wb::{mock::{MockConfig, MockStream}, transport::Shell};
//! use std::time::Duration;
//! let mut device = MockStream::new(MockConfig::default())?;
//! {
//! let mut shell = Shell::new(&mut device, 65_536);
//! shell.synchronize()?;
//! shell.command_checked("pause", Duration::ZERO, Duration::ZERO)?;
//! }
//! assert!(device.state().paused);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
mod device;
mod server;
pub use device::{MockConfig, MockFault, MockModel, MockState, MockStream};
pub use server::serve_connection;

40
src/mock/server.rs Normal file
View File

@ -0,0 +1,40 @@
//! Stream server adapter; all command behavior comes from MockStream.
use super::{MockConfig, MockState, MockStream};
use std::io::{self, Read, Write};
/// Serve one connection until EOF or a configured disconnect fault.
///
/// The caller controls transport timeouts, listener lifecycle and concurrency.
/// Each call creates a fresh device. Response fragmentation follows mock read
/// chunk size, although TCP may coalesce writes on the network.
///
/// Returns final device state for assertions; I/O errors are propagated.
pub fn serve_connection(
mut stream: impl Read + Write,
config: MockConfig,
) -> io::Result<MockState> {
let mut device = MockStream::new(config)?;
let mut bytes = [0; 4096];
loop {
while device.pending_bytes() != 0 {
let count = device.read(&mut bytes)?;
stream.write_all(&bytes[..count])?;
}
stream.flush()?;
if !device.is_connected() {
return Ok(device.state().clone());
}
let count = match stream.read(&mut bytes) {
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
result => result?,
};
if count == 0 {
return Ok(device.state().clone());
}
let mut consumed = 0;
while consumed < count && device.is_connected() {
consumed += device.write(&bytes[consumed..count])?;
}
}
}

327
src/protocol.rs Normal file
View File

@ -0,0 +1,327 @@
//! Model-independent request validation and length-checked `scanraw` decoding.
//!
//! Wire invariants live here: delimiters, little-endian 16-bit samples and
//! 1/32 dB scaling. No serial port, clock, file or terminal is accessed.
use crate::config::FrequencyAxis;
/// Highest supported Basic frequency, in Hz.
pub const BASIC_MAX_HZ: u64 = 960_000_000;
/// Native `scanraw` level bias used by tinySA Basic firmware, in dB.
pub const BASIC_RAW_LEVEL_OFFSET_DB: u16 = 128;
/// Native `scanraw` level bias used by tinySA Ultra firmware, in dB.
pub const ULTRA_RAW_LEVEL_OFFSET_DB: u16 = 174;
/// Host allocation limit retained from the original UI.
pub const MAX_POINTS: usize = 1_000_001;
/// One decoded observation; CSV and UI both consume these physical units.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Sample {
/// Frequency assigned by the selected host labeling convention, in MHz.
pub frequency_mhz: f64,
/// Level after subtracting the configured raw offset, in dBm.
pub level_dbm: f64,
}
/// Validatable acquisition parameters, independent of UI widgets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScanRequest {
/// First requested frequency, in Hz.
pub start_hz: u64,
/// Requested upper boundary, in Hz.
pub stop_hz: u64,
/// Number of raw sample records.
pub points: usize,
/// Measurements per frequency (1–1,000).
pub repeat: usize,
}
/// Legacy Basic input-path selection; use `DeviceModel::plan` for automatic models.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
/// Basic low input.
Low,
/// Basic high input.
High,
}
impl InputMode {
/// Console keyword identifying the Basic input path.
pub fn as_str(self) -> &'static str {
match self {
Self::Low => "low",
Self::High => "high",
}
}
}
/// Validation and frame errors, with bounded diagnostics rather than raw dumps.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ProtocolError {
/// Invalid acquisition parameters or unsupported input span.
#[error("invalid scan request: {0}")]
InvalidRequest(String),
/// The supplied frame does not begin with `{`.
#[error("raw scan is missing its opening brace")]
MissingStart,
/// The frame length differs from the requested number of records.
#[error("raw frame has {actual} bytes; expected {expected}")]
Length {
/// Expected body length, including braces.
expected: usize,
/// Actual body length, including braces.
actual: usize,
},
/// A record does not begin with the alignment byte `x`.
#[error("sample {index} has alignment byte 0x{found:02x}; expected 0x78")]
Alignment {
/// Zero-based sample index.
index: usize,
/// Received alignment byte.
found: u8,
},
/// No closing brace occurs at the exact end of the requested records.
#[error("raw scan is missing its closing brace")]
MissingEnd,
}
impl ScanRequest {
/// Validate this request using the legacy Basic profile.
/// Ultra callers should use `DeviceModel::Ultra.plan` instead.
pub fn input_mode(&self) -> Result<InputMode, ProtocolError> {
let plan = crate::device::DeviceModel::Basic.plan(self)?;
Ok(if plan.input_command == "mode high input" {
InputMode::High
} else {
InputMode::Low
})
}
/// Validate model-independent ordering and point/repeat bounds.
pub fn validate(&self) -> Result<(), ProtocolError> {
if !(2..=MAX_POINTS).contains(&self.points) || !(1..=1000).contains(&self.repeat) {
return Err(ProtocolError::InvalidRequest(
"points must be 2..=1000001 and repeat 1..=1000".into(),
));
}
if self.start_hz > self.stop_hz {
return Err(ProtocolError::InvalidRequest(
"start frequency must not exceed stop frequency".into(),
));
}
Ok(())
}
/// Exact framed byte count; validation happens before multiplication/allocation.
pub fn frame_len(&self) -> Result<usize, ProtocolError> {
self.validate()?;
Ok(self.points * 3 + 2)
}
}
/// Decode exactly one raw body, including braces and excluding echo/prompt.
///
/// `zero_offset` must match the `zero` command sent to the device. Frequency
/// labeling is explicit because legacy tiny-wb output and `scanraw` use
/// different arithmetic. Malformed/short/extra records are rejected before
/// callers can export a completed scan.
pub fn decode_frame(
frame: &[u8],
request: &ScanRequest,
zero_offset: u16,
axis: FrequencyAxis,
) -> Result<Vec<Sample>, ProtocolError> {
let expected = request.frame_len()?;
if zero_offset > 2047 {
return Err(ProtocolError::InvalidRequest(
"zero offset must be 0..=2047".into(),
));
}
if frame.first() != Some(&b'{') {
return Err(ProtocolError::MissingStart);
}
if frame.len() != expected {
return Err(ProtocolError::Length {
expected,
actual: frame.len(),
});
}
if frame.last() != Some(&b'}') {
return Err(ProtocolError::MissingEnd);
}
// The exact frame length checked above guarantees no partial record remains.
frame[1..frame.len() - 1]
.as_chunks::<3>()
.0
.iter()
.enumerate()
.map(|(index, record)| {
if record[0] != b'x' {
return Err(ProtocolError::Alignment {
index,
found: record[0],
});
}
Ok(Sample {
frequency_mhz: match axis {
FrequencyAxis::Inclusive => {
let intervals = request.points - 1;
(request.start_hz as f64
+ index as f64 * (request.stop_hz - request.start_hz) as f64
/ intervals as f64)
/ 1_000_000.0
}
FrequencyAxis::Firmware => {
firmware_frequency_hz(request, index) as f64 / 1_000_000.0
}
},
level_dbm: f64::from(u16::from_le_bytes([record[1], record[2]])) / 32.0
- f64::from(zero_offset),
})
})
.collect()
}
/// Reproduce the reviewed firmware's `scanraw` frequency expression.
///
/// The C implementation first performs integer division, converts that result
/// to a 32-bit `float`, multiplies it by the point index, then truncates the
/// product back to `freq_t` before adding `start`.
pub(crate) fn firmware_frequency_hz(request: &ScanRequest, index: usize) -> u64 {
debug_assert!(index < request.points);
let integer_step_hz = (request.stop_hz - request.start_hz) / request.points as u64;
let firmware_step_hz = integer_step_hz as f32;
request.start_hz + (firmware_step_hz * index as f32) as u64
}
#[cfg(test)]
mod tests {
use super::*;
fn request() -> ScanRequest {
ScanRequest {
start_hz: 240_000_000,
stop_hz: 960_000_000,
points: 2,
repeat: 1,
}
}
#[test]
fn structural_request_boundaries_are_model_independent() {
assert!(ScanRequest {
start_hz: 100,
stop_hz: 99,
..request()
}
.validate()
.is_err());
assert!(ScanRequest {
start_hz: 0,
stop_hz: u64::MAX,
..request()
}
.validate()
.is_ok());
for points in [0, 1, MAX_POINTS + 1, usize::MAX] {
assert!(ScanRequest {
points,
..request()
}
.frame_len()
.is_err());
}
assert!(ScanRequest {
repeat: 0,
..request()
}
.validate()
.is_err());
assert!(ScanRequest {
repeat: 1001,
..request()
}
.validate()
.is_err());
}
#[test]
fn little_endian_levels_offsets_and_both_axes() {
let frame = b"{x\x00\x08x\x00\x10}";
let inclusive = decode_frame(frame, &request(), 128, FrequencyAxis::Inclusive).unwrap();
assert_eq!(
inclusive,
vec![
Sample {
frequency_mhz: 240.0,
level_dbm: -64.0
},
Sample {
frequency_mhz: 960.0,
level_dbm: 0.0
}
]
);
let firmware = decode_frame(frame, &request(), 174, FrequencyAxis::Firmware).unwrap();
assert_eq!(
firmware[1],
Sample {
frequency_mhz: 600.0,
level_dbm: -46.0
}
);
}
#[test]
fn firmware_axis_reproduces_integer_step_and_float_rounding() {
let request = ScanRequest {
start_hz: 0,
stop_hz: 10,
points: 3,
repeat: 1,
};
let samples =
decode_frame(b"{x\0\0x\0\0x\0\0}", &request, 0, FrequencyAxis::Firmware).unwrap();
assert_eq!(
samples
.iter()
.map(|sample| sample.frequency_mhz * 1_000_000.0)
.collect::<Vec<_>>(),
vec![0.0, 3.0, 6.0]
);
let request = ScanRequest {
start_hz: 0,
stop_hz: 100_000_002,
points: 2,
repeat: 1,
};
assert_eq!(firmware_frequency_hz(&request, 1), 50_000_000);
}
#[test]
fn truncated_extra_and_misaligned_frames_are_rejected_without_panics() {
let frame = b"{x\x00\x08x\x00\x10}";
for length in 0..frame.len() {
assert!(
decode_frame(&frame[..length], &request(), 128, FrequencyAxis::Inclusive).is_err()
);
}
for frame in [
b"{x\x00\x08x\x00\x10}extra".as_slice(),
b"{y\x00\x08x\x00\x10}",
b"{x\x00\x08x\x00\x10!",
b"{x\x00\x08} ",
] {
assert!(decode_frame(frame, &request(), 128, FrequencyAxis::Inclusive).is_err());
}
}
#[test]
fn binary_delimiters_are_sample_data() {
let samples = decode_frame(b"{x{}xch}", &request(), 128, FrequencyAxis::Inclusive).unwrap();
assert_eq!(samples.len(), 2);
assert_eq!(
samples[0].level_dbm,
f64::from(u16::from_le_bytes(*b"{}")) / 32.0 - 128.0
);
}
}

File diff suppressed because it is too large Load Diff

58
src/storage.rs Normal file
View File

@ -0,0 +1,58 @@
//! Same-directory replacement for configuration files.
use std::{
fs::{self, OpenOptions},
io::{self, Write},
path::{Path, PathBuf},
sync::atomic::{AtomicU64, Ordering},
};
/// Distinguish writes in one process, including concurrent callers.
static NEXT_FILE: AtomicU64 = AtomicU64::new(0);
/// Remove an incomplete temporary file on errors and unwinding.
struct TemporaryFile(PathBuf);
impl Drop for TemporaryFile {
fn drop(&mut self) {
let _ = fs::remove_file(&self.0);
}
}
/// Replace a file only after its complete new contents have been flushed.
pub(crate) fn replace(path: &Path, contents: &[u8]) -> io::Result<()> {
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let name = path
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "missing file name"))?;
for _ in 0..100 {
let temporary = parent.join(format!(
".{}.{}.{}.tmp",
name.to_string_lossy(),
std::process::id(),
NEXT_FILE.fetch_add(1, Ordering::Relaxed)
));
let mut file = match OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)
{
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
};
let guard = TemporaryFile(temporary);
file.write_all(contents)?;
file.sync_all()?;
drop(file);
fs::rename(&guard.0, path)?;
return Ok(());
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"could not allocate a configuration temporary file",
))
}

View File

@ -1,324 +0,0 @@
//! All the structs used internally
use std::{
fs::File,
io::{Read, Write},
sync::{Arc, Mutex},
};
use flexi_logger::FlexiLoggerError;
use log;
use serde;
use thiserror;
use crate::ui_struct::AppInfo;
/// The most common error, exposed to the lib user and end used
#[derive(thiserror::Error, Debug)]
pub enum TinyError {
/// An error occured while receiving the raw data and '{' couldn't be found
#[error("Couldn't parse the beggining of the data ({0})")]
ParseBeggining(String),
/// An error occured while receiving the raw data and '}' couldn't be found
#[error("Couldn't parse the end of the data ({0})")]
ParseEnd(String),
/// The given serial port couldn't be opened
#[error("Couldn't connect to the given port")]
PortConnection(#[from] serialport::Error),
/// The given file could't be exported
#[error("Couldn't open the given file")]
OpenOutput(#[from] std::io::Error),
/// Generic TUI initialization error
#[error("An error occured while creating the TUI")]
TUIInitialization(#[from] color_eyre::Report),
/// A runtime error occured
#[error("A runtime error occured :\n{0}")]
TUIRuntimeError(color_eyre::eyre::Error),
/// An error occured while trying to parse the result
#[error("An error occured while trying to parse the result")]
TUIPackingError(#[from] packed_struct::PackingError),
/// The config file couldn't be opened
#[error("The config file couldn't be opened")]
ConfigNotFound,
/// The config file couldn't be parsed as a valid toml
#[error("The config config.toml couldn't be read")]
InvalidConfig(#[from] toml::de::Error),
/// The config file couldn't be parsed as a valid toml
#[error("The config config.toml couldn't be written")]
InvalidDataForConfig(#[from] toml::ser::Error),
/// The version couldn't be acquired, likely a bogus connection
#[error("Couldn't acquire the version of the device connected to the specified port")]
NoVersionFound,
/// The given scan frequencies are incorrect
#[error("The given scan frequencies are inccorect ({0})")]
BadScanFrequencies(String),
/// Couldn't initialize the logging modure
#[error("Couldn't initialize the logging modure")]
LoggerError(#[from] FlexiLoggerError),
/// Couldn't send data
#[error("Couldn't write to the TinySA, connection lost")]
SendError(std::io::Error),
}
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
/// The direction the input was received, usefull for menu where R/L U/D give similar results and implementation
pub(crate) enum InputDirection {
Up,
Down,
Right,
Left,
}
/// All implementation of errors happening while in the UI
#[derive(thiserror::Error, Debug)]
pub enum TinyUIError {
/// An error due to bad menuing implementation
#[error("An error occured while selecting a menu item")]
MenuSelectionError,
/// An error due to bad initialization
#[error("The item list ({0}) wasn't initialyzed ({2}:{1})")]
UninitializedItemList(&'static str, u32, &'static str),
/// An error occured while proccesing the key events
#[error("An error occured while proccesing the key events")]
KeyPress(#[from] std::io::Error),
/// Couldn't get a port from the selection
#[error("No port was selected")]
NoPortSelected,
/// Any Scan Error
#[error("An error occured while trying to scan: \n => {0}")]
ScanError(#[from] TinyError),
/// No connection object was created
#[error("An error occured while trying to acquire the connection info structure")]
NoConnectionInfoCreated,
/// No return data was created or initialized
#[error("An error occured while trying to acquire the return data")]
NoReturnData,
/// No error was generated, this error is a meta error
#[error("An unspecified error occured")]
NoErrorSpecified,
/// Error occured while tring to serialize the config to file
#[error("Couldn't serialize the error to file")]
SerializeError(#[from] toml::ser::Error),
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub(crate) struct SavedConfig {
/// The default com port
pub(crate) port: String,
/// The default baudrate
pub(crate) baudrate: u32,
/// The default start frequency
pub(crate) start_frequency: usize,
/// The default stop frequency
pub(crate) stop_frequency: usize,
/// The default number of points
pub(crate) points: usize,
/// The default number of repeat per point
pub(crate) repeat: usize,
}
impl SavedConfig {
/// Create a config from file or returns an error
pub(crate) fn new() -> Result<Self, TinyError> {
if let Ok(mut f) = File::open("config.toml") {
let mut s = String::new();
f.read_to_string(&mut s)?;
let c = toml::from_str(&s)?;
Ok(c)
} else {
Err(TinyError::ConfigNotFound)
}
}
/// Save the config with all runtime parameters
pub(crate) fn save(arg: &AppInfo) -> Result<(), TinyUIError> {
let mut f = File::create("config.toml")?;
f.write_all(
toml::to_string(&Self {
port: arg.port_list.selected_port()?,
baudrate: arg.baudrate.selected_baudrate()?,
start_frequency: arg.start_frequency.int_to_usize(),
stop_frequency: arg.stop_frequency.int_to_usize(),
points: arg.points.int_to_usize(),
repeat: arg.repeat.int_to_usize(),
})?
.as_bytes(),
)?;
Ok(())
}
}
/// The various status the connection can take
#[derive(Debug, Clone, Copy)]
pub(crate) enum ConnectionStatus {
/// The connection was created with no initialisation data
Uninitialised,
/// The connection has initialisation data but wasn't established
Initialised,
/// The connection was established
Connected,
/// The connection coudn't be done, with a string explaining the error
ConnectionFailure,
/// The connection is closed and the connection was a succes
ClosedWithSuccess,
ScanStarted,
}
type ScanData = Vec<(f64, f64)>;
#[derive(Debug, Clone)]
/// All data needed to handle a connection to the TinySA
pub(crate) struct ConnectionInfo {
/// The number of points to scan
pub(crate) points: usize,
/// The baudrate of the connection
pub(crate) baudrate: u32,
/// The Serial port to open for connection
pub(crate) port: String,
/// A mutex to share the progression (over 100)
progress: Arc<Mutex<usize>>,
/// The number of times to repeate a mesurement of a point
pub(crate) repeat: usize,
/// A mutex to the result of the scan
return_data: Arc<Mutex<Option<ScanData>>>,
/// The information of the TinySA
scan_info: Arc<Mutex<String>>,
/// The last scan message (what's happening as the scan goes)
scan_message: Arc<Mutex<String>>,
/// The value to start at (in Hz)
pub(crate) start: usize,
/// The value to stop at (in Hz)
pub(crate) stop: usize,
/// The file name to store all data
file_name: Arc<Mutex<String>>,
/// The connection status
connection_status: Arc<Mutex<ConnectionStatus>>,
/// The last error raised
pub(crate) error_raised: Arc<Mutex<Option<TinyUIError>>>,
}
impl ConnectionInfo {
/// Create the initial connection containing only the initial mutex for error collection
pub(crate) fn new() -> Self {
Self::default()
}
/// Updates the connection with the given data
pub(crate) fn fill(
&mut self,
port: String,
baudrate: u32,
start: usize,
stop: usize,
points: usize,
repeat: usize,
) {
self.port = port;
self.baudrate = baudrate;
self.start = start;
self.stop = stop;
self.points = points;
self.repeat = repeat;
}
/// Updates the generic scan message
pub(crate) fn update_message(&self, message: &'static str) {
log::trace!("Message: {message}");
*self.scan_message.lock().unwrap() = message.to_string();
}
/// Updates the scan progress
pub(crate) fn update_progress(&self, progress: usize) {
log::trace!("Progress: {progress}");
*self.progress.lock().unwrap() = progress;
}
/// Update the information of the TinySA
pub(crate) fn update_info(&self, message: String) {
log::info!("Info: {message}");
*self.scan_info.lock().unwrap() = message.to_string();
}
/// A clone of the mutex to keep it updated
pub(crate) fn mutex_progress(&self) -> Arc<Mutex<usize>> {
self.progress.clone()
}
/// Update the return data with the new points
pub(crate) fn update_return_data(&self, return_data: Vec<(f64, f64)>) {
*self.return_data.lock().unwrap() = Some(return_data);
}
/// Update the filename with the one choosen by the save method
pub(crate) fn update_filename(&self, name: String) {
*self.file_name.lock().unwrap() = name;
}
/// Get the current progression level
pub(crate) fn get_progress(&self) -> usize {
*self.progress.lock().unwrap()
}
/// Get the latest scan message
pub(crate) fn get_scan_message(&self) -> String {
(*self.scan_message.lock().unwrap()).to_string()
}
/// Get the latest tinySA information (There is no guaranty it is initialised or valid)
pub(crate) fn get_scan_info(&self) -> String {
(*self.scan_info.lock().unwrap()).to_string()
}
/// Get the latest connection status
pub(crate) fn get_connection_status(&self) -> ConnectionStatus {
*self.connection_status.lock().unwrap()
}
/// Take the return data and leave none in place
pub(crate) fn get_return_data(&self) -> Result<Vec<(f64, f64)>, TinyUIError> {
self.return_data
.lock()
.unwrap()
.take()
.ok_or(TinyUIError::NoReturnData)
}
/// Set an error
pub(crate) fn set_error(&self, e: Option<TinyUIError>) {
log::error!("Error: {e:?}");
*self.error_raised.lock().unwrap() = e;
}
/// Wether an error has been raised
pub(crate) fn has_error(&self) -> bool {
self.error_raised.lock().unwrap().is_some()
}
/// Manually sets the connections status
pub(crate) fn set_connection_status(&self, status: ConnectionStatus) {
log::info!("Status: {status:?}");
*self.connection_status.lock().unwrap() = status;
}
// pub(crate) fn get_error(&self) -> &Option<TinyError> {
// self.error_raised.lock().as_ref().unwrap()
// }
}
impl Default for ConnectionInfo {
fn default() -> Self {
Self {
points: 11,
baudrate: 115_200,
port: String::new(),
progress: Arc::new(Mutex::new(0)),
repeat: 1,
return_data: Arc::new(Mutex::new(None)),
scan_info: Arc::new(Mutex::new(String::new())),
scan_message: Arc::new(Mutex::new(String::new())),
start: 240,
stop: 960,
file_name: Arc::new(Mutex::new(String::new())),
connection_status: Arc::new(Mutex::new(ConnectionStatus::Uninitialised)),
error_raised: Arc::new(Mutex::new(None)),
}
}
}

305
src/transport.rs Normal file
View File

@ -0,0 +1,305 @@
//! Buffered mixed text/binary shell transport over any `Read + Write` stream.
//!
//! Prompt matching spans reads and retains bytes after the prompt. Raw frames
//! are consumed by exact record count before text prompt matching resumes.
//! Read timeouts are supplied by the underlying stream and remain errors.
use crate::protocol::{ProtocolError, ScanRequest};
use std::{
io::{self, BufReader, Read, Write},
thread,
time::Duration,
};
/// Console prompt outside binary frames.
const PROMPT: &[u8] = b"ch>";
/// Transport errors preserve their I/O or protocol source.
#[derive(Debug, thiserror::Error)]
pub enum TransportError {
/// Read/write/flush failed, including timeout or disconnect.
#[error("serial transport: {0}")]
Io(#[from] io::Error),
/// A response exceeded its configured memory bound.
#[error("serial response exceeds {0} bytes")]
ResponseTooLong(usize),
/// A command contains a terminator or is empty/non-ASCII.
#[error("a shell command must be one nonempty printable ASCII line")]
InvalidCommand,
/// A checked command returned a recognizable rejection or usage response.
#[error("device rejected {command:?}: {response}")]
CommandRejected {
/// Command that was sent.
command: String,
/// Bounded text response from the device.
response: String,
},
/// An invalid scan request was rejected before reading.
#[error(transparent)]
Protocol(#[from] ProtocolError),
}
/// A single buffered connection; do not bypass it to read from the same stream.
pub struct Shell<T> {
/// Persistent buffering retains bytes beyond a prompt or raw frame.
stream: BufReader<T>,
/// Upper bound for text and pre-frame echo, independent of raw sample size.
max_response_bytes: usize,
}
impl<T: Read + Write> Shell<T> {
/// Wrap a serial stream or a deterministic in-memory transcript.
pub fn new(stream: T, max_response_bytes: usize) -> Self {
Self {
stream: BufReader::new(stream),
max_response_bytes,
}
}
/// Write a complete shell command and carriage return, including partial writes.
pub fn send(&mut self, command: &str) -> Result<(), TransportError> {
if command.is_empty() || !command.bytes().all(|b| (b' '..=b'~').contains(&b)) {
return Err(TransportError::InvalidCommand);
}
self.stream.get_mut().write_all(command.as_bytes())?;
self.stream.get_mut().write_all(b"\r")?;
self.stream.get_mut().flush()?;
Ok(())
}
/// Read one prompt-terminated text response, excluding the prompt itself.
///
/// A timeout or EOF before the complete prompt is an error, never success
/// with partial text. Bytes after the prompt remain buffered for the next call.
pub fn read_text(&mut self) -> Result<Vec<u8>, TransportError> {
let mut response = Vec::new();
loop {
let mut byte = [0];
self.stream.read_exact(&mut byte)?;
response.push(byte[0]);
if response.ends_with(PROMPT) {
response.truncate(response.len() - PROMPT.len());
return Ok(response);
}
if response.len() >= self.max_response_bytes {
return Err(TransportError::ResponseTooLong(self.max_response_bytes));
}
}
}
/// Drain an optional stale response before the first request.
///
/// Idle timeout is expected here only. Disconnects and oversized responses
/// remain errors. No subsequent command uses this relaxed timeout behavior.
pub fn synchronize(&mut self) -> Result<(), TransportError> {
match self.read_text() {
Ok(_) => Ok(()),
Err(TransportError::Io(error))
if matches!(
error.kind(),
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
) =>
{
Ok(())
}
Err(error) => Err(error),
}
}
/// Send and consume one text command with configurable compatibility delays.
pub fn command(
&mut self,
command: &str,
delay: Duration,
settle: Duration,
) -> Result<String, TransportError> {
self.send(command)?;
thread::sleep(delay);
let response = self.read_text()?;
thread::sleep(settle);
Ok(String::from_utf8_lossy(&response).into_owned())
}
/// Send a mutating command, rejecting recognizable error/usage responses.
///
/// This handles common shell responses, not every firmware-specific status.
/// Use `command` for informational queries that intentionally return usage.
pub fn command_checked(
&mut self,
command: &str,
delay: Duration,
settle: Duration,
) -> Result<String, TransportError> {
let response = self.command(command, delay, settle)?;
if response.lines().any(|line| {
let line = line.trim_start().to_ascii_lowercase();
line.starts_with("error:")
|| line.starts_with("usage:")
|| line.starts_with("unknown command")
}) {
return Err(TransportError::CommandRejected {
command: command.into(),
response,
});
}
Ok(response)
}
/// Consume echo, an exact raw body, then its trailing shell prompt.
///
/// Progress receives `(received_body_bytes, expected_body_bytes)`. A short
/// frame, missing closing brace or absent prompt fails rather than returning
/// a successful partial acquisition. No text token is searched inside samples.
pub fn read_frame(
&mut self,
request: &ScanRequest,
mut progress: impl FnMut(usize, usize),
) -> Result<Vec<u8>, TransportError> {
let expected = request.frame_len()?;
let mut byte = [0];
let mut prefix_len = 0;
loop {
self.stream.read_exact(&mut byte)?;
if byte[0] == b'{' {
break;
}
prefix_len += 1;
if prefix_len >= self.max_response_bytes {
return Err(TransportError::ResponseTooLong(self.max_response_bytes));
}
}
let mut frame = vec![0; expected];
frame[0] = b'{';
let mut received = 1;
for chunk in frame[1..].chunks_mut(4096) {
self.stream.read_exact(chunk)?;
received += chunk.len();
progress(received, expected);
}
if frame.last() != Some(&b'}') {
return Err(ProtocolError::MissingEnd.into());
}
self.read_text()?;
Ok(frame)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
/// Simulate arbitrary read fragmentation and short writes without hardware.
struct Duplex {
input: Cursor<Vec<u8>>,
written: Vec<u8>,
chunk: usize,
}
impl Read for Duplex {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
let limit = buffer.len().min(self.chunk);
self.input.read(&mut buffer[..limit])
}
}
impl Write for Duplex {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
let count = bytes.len().min(2);
self.written.extend_from_slice(&bytes[..count]);
Ok(count)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn shell(bytes: &[u8], chunk: usize) -> Shell<Duplex> {
Shell::new(
Duplex {
input: Cursor::new(bytes.to_vec()),
written: Vec::new(),
chunk,
},
256,
)
}
#[test]
fn prompts_span_reads_and_preserve_following_bytes() {
for chunk in 1..=20 {
let mut shell = shell(b"firstch>secondch>", chunk);
assert_eq!(shell.read_text().unwrap(), b"first");
assert_eq!(shell.read_text().unwrap(), b"second");
}
}
#[test]
fn commands_use_complete_writes_and_reject_injected_lines() {
let mut shell = shell(b"replych>", 1);
assert_eq!(
shell
.command("version", Duration::ZERO, Duration::ZERO)
.unwrap(),
"reply"
);
assert_eq!(shell.stream.get_ref().written, b"version\r");
for command in ["", "scan\rresume", "scan\n", "\0"] {
assert!(shell.send(command).is_err());
}
assert_eq!(shell.stream.get_ref().written, b"version\r");
}
#[test]
fn frame_is_length_delimited_and_next_response_is_retained() {
let request = ScanRequest {
start_hz: 0,
stop_hz: 10,
points: 2,
repeat: 1,
};
for chunk in 1..=32 {
let mut shell = shell(b"scanraw echo\r\n{x{}xch}\r\nch>nextch>", chunk);
let mut last = (0, 0);
let frame = shell
.read_frame(&request, |received, total| last = (received, total))
.unwrap();
assert_eq!(frame, b"{x{}xch}");
assert_eq!(last, (8, 8));
assert_eq!(shell.read_text().unwrap(), b"next");
}
}
#[test]
fn eof_truncation_and_size_limits_are_errors() {
assert!(shell(b"missing prompt", 5).read_text().is_err());
assert!(shell(&[b'a'; 257], 32).read_text().is_err());
let request = ScanRequest {
start_hz: 0,
stop_hz: 10,
points: 2,
repeat: 1,
};
for input in [b"{x12}".as_slice(), b"{x12x34}", b"{x12x34!ch>"] {
assert!(shell(input, 1).read_frame(&request, |_, _| {}).is_err());
}
}
#[test]
fn timeout_is_only_tolerated_during_initial_synchronization() {
struct Timeout;
impl Read for Timeout {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Err(io::ErrorKind::TimedOut.into())
}
}
impl Write for Timeout {
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
Ok(b.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let mut shell = Shell::new(Timeout, 256);
assert!(shell.synchronize().is_ok());
assert!(shell.read_text().is_err());
}
}

671
src/ui.rs
View File

@ -1,671 +0,0 @@
//! The (minimal) user interface to control the program
#![allow(unused_imports)]
use clap::builder::Resettable;
use color_eyre::{eyre::Context, owo_colors::OwoColorize, Section};
use core::{panic, time};
use log::info;
use ratatui::{
buffer::Buffer,
crossterm::{
event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
style::Print,
},
layout::{Alignment, Constraint, Direction, Layout, Rect},
prelude::BlockExt,
style::{
palette::tailwind::{BLUE, GREEN, SLATE},
Color, Modifier, Style, Styled, Stylize,
},
symbols::{self, Marker},
text::Line,
widgets::{
block::Title, Axis, Block, Borders, Chart, Dataset, GraphType, HighlightSpacing, LineGauge,
List, ListDirection, ListItem, ListState, Padding, Paragraph, ScrollDirection,
StatefulWidget, Widget, Wrap,
},
DefaultTerminal, Frame,
};
use serialport::SerialPortInfo;
use std::{
borrow::{Borrow, BorrowMut},
cmp::min,
fmt::Pointer,
iter::Iterator,
sync::{Arc, Mutex},
thread,
time::{Duration, Instant},
};
use strum::{EnumCount, EnumIter, EnumProperty};
use strum::{FromRepr, IntoEnumIterator};
use tui_textarea::{Input, Key, TextArea};
use crate::{
mleft, mright, scan,
structs::{
ConnectionInfo, ConnectionStatus, InputDirection, SavedConfig, TinyError, TinyUIError,
},
ui_struct::{
AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig,
UIUsize, SELECTED_COLOR, UNSELECTED_COLOR,
},
};
impl<'a> AppInfo<'a> {
/// Create a new app with the port info available
pub(crate) fn new(info: Vec<SerialPortInfo>) -> Self {
let loaded_conf = SavedConfig::new();
let (start_frequency, stop_frequency, points, repeat) = {
if let Ok(c) = &loaded_conf {
(
UIUsize::new(c.start_frequency, 10, 0, 960),
UIUsize::new(c.stop_frequency, 10, 10, 960),
UIUsize::new(c.points, 100, 101, 1000001),
UIUsize::new(c.repeat, 1, 1, 1000),
)
} else {
(
UIUsize::new(240, 10, 0, 960),
UIUsize::new(960, 10, 10, 960),
UIUsize::new(10001, 100, 101, 1000001),
UIUsize::new(1, 1, 1, 1000),
)
}
};
Self {
should_quit: false,
baudrate: BaudRateList::from_conf(&loaded_conf),
port_list: PortList::from_serial(info, &loaded_conf),
flow_state: AppState::default(),
status_message: String::new(),
menu_items: MenuItems::default(),
start_frequency,
stop_frequency,
points,
repeat,
connection_info: None,
return_data: Vec::new(),
logged_message: false,
}
}
/// Contains the main loop for running the app
pub(crate) fn run(
&mut self,
mut terminal: DefaultTerminal,
) -> Result<(), color_eyre::eyre::Error> {
self.init_config()?;
loop {
terminal.draw(|v| self.draw(v).inspect_err(|e| panic!("{}", e)).unwrap())?;
let timeout = Duration::from_millis(16);
if event::poll(timeout)? {
if let Event::Key(key) = event::read()? {
if let Err(e) = self.handle_start_keys(key) {
self.get_connection_info()?.set_error(Some(e));
self.flow_state = AppState::Error;
};
};
if self.should_quit {
break;
}
}
}
Ok(())
}
/// Generic draw loop method
fn draw(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> {
let r = match self.flow_state {
AppState::InitialConfig(_) => self.draw_config(frame),
AppState::FinalConfig(_) => self.draw_final_config(frame),
AppState::Finished => self.draw_progress(frame),
AppState::EndWindow => self.draw_end_window(frame),
AppState::Error => self.draw_error(frame),
};
if let Err(e) = r {
self.get_connection_info()?.set_error(Some(e));
self.flow_state = AppState::Error;
}
Ok(())
}
/// Initialisation of the config window
fn init_config(&mut self) -> Result<(), TinyUIError> {
self.connection_info = Some(ConnectionInfo::new());
self.menu_items.portlist = Some(
List::new(self.port_list.to_vecstr())
.block(Block::bordered().title("COM Ports"))
.highlight_style(
Style::default()
.add_modifier(Modifier::ITALIC)
.bg(Color::Blue),
)
.repeat_highlight_symbol(true),
);
self.menu_items.baudlist = Some(
List::new(self.baudrate.to_vecstr())
.block(Block::bordered().title("Baudrates"))
.highlight_style(
Style::default()
.add_modifier(Modifier::ITALIC)
.bg(Color::Blue),
)
.repeat_highlight_symbol(true),
);
self.update_color()
}
/// Initialisation of all the ui element for the final configuration elements
fn init_final_config(&mut self) -> Result<(), TinyUIError> {
self.menu_items.textboxes = vec![Paragraph::new("")];
self.update_color()
}
/// Initialisation of all the final ui elements
pub(crate) fn init_end(&self) -> Result<(), TinyUIError> {
Ok(())
}
/// Draw the final configuration labels
fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> {
let [title_area, main_area, _, status_area] = Layout::vertical([
Constraint::Length(2),
Constraint::Length(3),
Constraint::Min(0),
Constraint::Length(1),
])
.areas(frame.area());
let [_, area_minf, area_maxf, area_points, repeat, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Min(7),
])
.areas(main_area);
// TODO: Move this in the color update
let (mif_color, maf_color, poi_color, rpt_color) = match self.flow_state {
AppState::FinalConfig(SelectedFinalConfig::StartFreq) => (
SELECTED_COLOR,
UNSELECTED_COLOR,
UNSELECTED_COLOR,
UNSELECTED_COLOR,
),
AppState::FinalConfig(SelectedFinalConfig::FinalFreq) => (
UNSELECTED_COLOR,
SELECTED_COLOR,
UNSELECTED_COLOR,
UNSELECTED_COLOR,
),
AppState::FinalConfig(SelectedFinalConfig::Points) => (
UNSELECTED_COLOR,
UNSELECTED_COLOR,
SELECTED_COLOR,
UNSELECTED_COLOR,
),
AppState::FinalConfig(SelectedFinalConfig::Repeat) => (
UNSELECTED_COLOR,
UNSELECTED_COLOR,
UNSELECTED_COLOR,
SELECTED_COLOR,
),
_ => unreachable!(),
};
// self.status_message = format!("{:?} ", self.flow_state);
frame.render_widget(
Paragraph::new(self.start_frequency.int_to_string())
.block(Block::bordered().title("Start Frequency"))
.style(mif_color),
area_minf,
);
frame.render_widget(
Paragraph::new(self.stop_frequency.int_to_string())
.block(Block::bordered().title("Stop Frequency"))
.style(maf_color),
area_maxf,
);
frame.render_widget(
Paragraph::new(self.points.int_to_string())
.block(Block::bordered().title("Points"))
.style(poi_color),
area_points,
);
frame.render_widget(
Paragraph::new(self.repeat.int_to_string())
.block(Block::bordered().title("Repeat"))
.style(rpt_color),
repeat,
);
self.update_color()?;
frame.render_widget(Paragraph::new(self.status_message.clone()), title_area);
self.render_footer(frame, status_area);
Ok(())
}
/// Render the selection footer
fn render_footer(&self, frame: &mut Frame, area: Rect) {
frame.render_widget(
Paragraph::new(
"Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.",
)
.centered(),
area,
);
}
/// Initialize the progress window
fn init_progress(&mut self) -> Result<(), TinyUIError> {
self.menu_items.progress_bar = Some(
LineGauge::default()
.filled_style(Style::default().fg(Color::Blue))
.unfilled_style(Style::default().fg(Color::Red))
.label("Progress:"),
);
Ok(())
}
/// Draw the config info
fn draw_config(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> {
let [title_area, main_area, status_area] = Layout::vertical([
Constraint::Length(2),
Constraint::Min(10),
Constraint::Length(1),
])
.areas(frame.area());
let [_, area_ports, area_baud, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(50),
Constraint::Percentage(50),
Constraint::Min(7),
])
.areas(main_area);
let list_ports = self
.menu_items
.portlist
.as_ref()
.ok_or(TinyUIError::UninitializedItemList("Port", line!(), file!()))?;
let list_baudrates = self
.menu_items
.baudlist
.as_ref()
.ok_or(TinyUIError::UninitializedItemList("Baud", line!(), file!()))?;
// self.status_message = format!("{:?} ", self.flow_state);
frame.render_stateful_widget(list_ports, area_ports, &mut self.port_list.state);
frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state);
frame.render_widget(Paragraph::new(self.status_message.clone()), title_area);
self.render_footer(frame, status_area);
Ok(())
}
/// Draw the progress, updates as the progress is being done
fn draw_progress(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> {
if !self.logged_message {
info!(
"First pass of the draw process {:#?}",
self.get_connection_info()?
);
self.logged_message = true;
}
let [_, main_s, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(90),
Constraint::Min(7),
])
.areas(frame.area());
let [title_area, progress_area, main_area, _, _] = Layout::vertical([
Constraint::Length(3),
Constraint::Length(1),
Constraint::Min(10),
Constraint::Length(1),
Constraint::Length(1),
])
.areas(main_s);
let (pb, status, message) = {
let status = self.get_connection_info()?.get_scan_message();
let status = Paragraph::new(status.clone())
.block(Block::bordered().title("Operation"))
.style(SELECTED_COLOR);
let message = self.get_connection_info()?.get_scan_info();
let message = Paragraph::new(message.clone())
.block(Block::bordered().title("TinySA Info"))
.style(SELECTED_COLOR);
let pb = self
.menu_items
.progress_bar
.take()
.ok_or(TinyUIError::UninitializedItemList(
"ProgressBar",
line!(),
file!(),
))?
.ratio(self.get_connection_info()?.get_progress() as f64 / 100.);
(pb, status, message)
};
frame.render_widget(pb.clone(), progress_area);
frame.render_widget(status, title_area);
frame.render_widget(message, main_area);
self.menu_items.progress_bar = Some(pb);
let st = self.get_connection_info()?.get_connection_status();
// Change color or some logo ?
match st {
ConnectionStatus::ConnectionFailure => self.next_step()?,
ConnectionStatus::Uninitialised
| ConnectionStatus::ScanStarted
| ConnectionStatus::Initialised
| ConnectionStatus::Connected => (),
ConnectionStatus::ClosedWithSuccess => {
self.return_data = self.get_connection_info()?.get_return_data()?;
self.next_step()?;
}
}
Ok(())
}
/// Get a reference to the connection info if it exists
fn get_connection_info(&self) -> Result<&ConnectionInfo, TinyUIError> {
self.connection_info
.as_ref()
.ok_or(TinyUIError::NoConnectionInfoCreated)
}
/// Draw the last confirmation window
fn draw_error(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> {
let [_, main_s, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(90),
Constraint::Min(7),
])
.areas(frame.area());
let [_, title_area, _main_area, message_area, _, footer_area] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(3),
Constraint::Length(1),
Constraint::Min(10),
Constraint::Length(1),
Constraint::Length(1),
])
.areas(main_s);
let conn_status = self.get_connection_info()?.get_connection_status();
let status_message = self.error_message_from_current_error()?;
let status = Paragraph::new(status_message)
.block(Block::bordered().title("Status"))
.style(Color::Red);
let mut additional = String::new();
if let Some(m) = &self
.get_connection_info()?
.error_raised
.lock()
.unwrap()
.as_ref()
{
additional.push_str(&format!("Error: {:?} \n => {}\n", m, m));
}
let error = Paragraph::new(format!(
"Last status: {:?}\nLast message: {}\n{}",
conn_status,
self.get_connection_info()?.get_scan_message(),
additional
))
.block(Block::bordered().title("Status"));
let footer = Paragraph::new("Press ↲ or q to exit".to_string()).centered();
frame.render_widget(status, title_area);
frame.render_widget(error, message_area);
frame.render_widget(footer, footer_area);
Ok(())
}
/// Extract a user explaination for an error message
fn error_message_from_current_error(&self) -> Result<String, TinyUIError> {
let status_message = match self
.get_connection_info()?
.error_raised
.lock()
.unwrap()
.as_ref()
.unwrap_or(&TinyUIError::NoErrorSpecified)
{
TinyUIError::MenuSelectionError => "An error occured while trying to select a menu item",
TinyUIError::UninitializedItemList(i, _l, _ff) => &format!("The item {i} was left uninitialized"),
TinyUIError::KeyPress(_) => "An error occured while processing key events",
TinyUIError::NoPortSelected => "No connection port was selected",
TinyUIError::NoConnectionInfoCreated => {
"An error occured when tring to acquire connection info with the TinySA"
}
TinyUIError::NoReturnData => "An error occured when trying to acquire the return data with the TinySA",
TinyUIError::NoErrorSpecified => "An unspecified error occured",
TinyUIError::ScanError(TinyError::ParseBeggining(_)) => {
"An error occured while receiving data, the scan never sent back any valid data"
}
TinyUIError::ScanError(TinyError::ParseEnd(_)) => {
"An error occured while receiving data, scan was interupted before ending properly"
}
TinyUIError::ScanError(TinyError::PortConnection(_)) => {
"An error occured while trying to connect, check the selected port and baudrate"
}
TinyUIError::ScanError(TinyError::NoVersionFound) => {
"An error forbid the gathering of the version, check your TinySA is connected and powered on"
}
TinyUIError::ScanError(TinyError::BadScanFrequencies(_)) => {
"An error occured because the scan frequencies weren't set correctly"
}
TinyUIError::ScanError(TinyError::OpenOutput(_)) => "An error occured while trying to export the scan",
TinyUIError::ScanError(TinyError::TUIInitialization(_)) => {
"An error occured while trying to create the TUI"
}
TinyUIError::ScanError(TinyError::TUIRuntimeError(_)) => "An error occured during runtime",
TinyUIError::ScanError(TinyError::TUIPackingError(_)) => {
"An error occured while trying to parse the data points"
}
TinyUIError::ScanError(TinyError::ConfigNotFound) => {
"An error occured while trying to open the config file"
}
TinyUIError::ScanError(TinyError::InvalidConfig(_)) => {
"An error forbid to read the config as it seems invalid, please delete config.toml and retry"
}
TinyUIError::ScanError(TinyError::InvalidDataForConfig(_)) => "An error forbit to write the config",
TinyUIError::ScanError(TinyError::LoggerError(_))=> "Couldn't initialize the error logger",
TinyUIError::ScanError(TinyError::SendError(_))=> "Couldn't finish sending data to TinySA",
TinyUIError::SerializeError(_) => "An error occured while tring to save the current config",
};
Ok(status_message.to_owned())
}
/// Draw the last confirmation window
fn draw_end_window(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> {
let [_, main_s, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(90),
Constraint::Min(7),
])
.areas(frame.area());
let [title_area, _main_area, graph_area, _, footer_area] = Layout::vertical([
Constraint::Length(3),
Constraint::Length(1),
Constraint::Min(10),
Constraint::Length(1),
Constraint::Length(1),
])
.areas(main_s);
let status = self.get_connection_info()?.get_connection_status();
match status {
ConnectionStatus::ConnectionFailure => {
self.flow_state = AppState::Error;
}
_ => {
let status = Paragraph::new(format!(
"The scan of {} points in the range ({}Mhz - {}Mhz) finished sucessfuly",
self.points.int_to_usize(),
self.start_frequency.int_to_usize(),
self.stop_frequency.int_to_usize(),
))
.block(Block::bordered().title("Status"))
.style(SELECTED_COLOR);
let datasets = vec![Dataset::default()
.marker(Marker::Dot)
.graph_type(GraphType::Scatter)
.style(Style::new().yellow())
.data(&self.return_data)];
let chart =
Chart::new(datasets)
.x_axis(
Axis::default()
.bounds([
self.start_frequency.int_to_usize() as f64,
self.stop_frequency.int_to_usize() as f64,
])
.style(Style::default().fg(Color::Gray))
.labels([
format!("{}MHz", self.start_frequency.int_to_string()),
format!(
"{}MHz",
self.start_frequency.int_to_usize()
+ (self.stop_frequency.int_to_usize().saturating_sub(
self.start_frequency.int_to_usize()
)) / 2
),
format!("{}MHz", self.stop_frequency.int_to_string()),
]),
)
.y_axis(
Axis::default()
.bounds([-128., 0.])
.style(Style::default().fg(Color::Gray))
.labels(["-128dbm", "-64dbm", "0dbm"]),
);
frame.render_widget(chart, graph_area);
let footer = Paragraph::new(format!(
"{}, press ↲ or q to exit",
self.get_connection_info()?.get_scan_message(),
))
.centered();
frame.render_widget(status, title_area);
frame.render_widget(footer, footer_area);
}
}
Ok(())
}
/// Handle keys while in the first menu
fn handle_start_keys(&mut self, key: KeyEvent) -> Result<(), TinyUIError> {
if key.kind != KeyEventKind::Press {
return Ok(());
}
match key.code {
KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down),
KeyCode::Char('k') | KeyCode::Up => self.change_cursor_position(InputDirection::Up),
KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left)?,
KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right)?,
KeyCode::Enter => match self.flow_state {
AppState::Finished => (),
_ => self.next_step()?,
},
_ => {}
}
Ok(())
}
/// A directionnal input was received
fn change_cursor_position(&mut self, direction: InputDirection) {
match self.flow_state {
AppState::InitialConfig(ref selected_menu) => match selected_menu {
SelectedConfig::Baudrate => self.baudrate.change_cursor(direction),
SelectedConfig::Port => self.port_list.change_cursor(direction),
},
AppState::FinalConfig(ref selected_menu) => match selected_menu {
SelectedFinalConfig::StartFreq => self.start_frequency.change_value(direction),
SelectedFinalConfig::FinalFreq => self.stop_frequency.change_value(direction),
SelectedFinalConfig::Points => self.points.change_value(direction),
SelectedFinalConfig::Repeat => self.repeat.change_value(direction),
},
AppState::EndWindow => (),
AppState::Finished => (),
AppState::Error => (),
}
}
/// Goes to the next menu depending on the position in the program
fn next_menu(&mut self, direction: InputDirection) -> Result<(), TinyUIError> {
if let Some(s) = match self.flow_state {
AppState::InitialConfig(ref r) => {
let v = *r as usize;
match direction {
InputDirection::Right => mright!(v, InitialConfig, SelectedConfig),
InputDirection::Left => mleft!(v, InitialConfig, SelectedConfig),
_ => None,
}
}
AppState::FinalConfig(ref r) => {
let v = *r as usize;
match direction {
InputDirection::Right => mright!(v, FinalConfig, SelectedFinalConfig),
InputDirection::Left => mleft!(v, FinalConfig, SelectedFinalConfig),
_ => None,
}
}
AppState::EndWindow => None,
AppState::Finished => None,
AppState::Error => None,
} {
self.flow_state = s;
}
self.update_color()?;
Ok(())
}
/// Progress in the flow of the program
fn next_step(&mut self) -> Result<(), TinyUIError> {
match self.flow_state {
AppState::InitialConfig(_) => {
self.flow_state = AppState::FinalConfig(SelectedFinalConfig::default());
self.init_final_config()?;
}
AppState::FinalConfig(_) => {
self.flow_state = AppState::Finished;
self.init_progress()?;
let mut co = self.connection_info.take();
co.as_mut()
.ok_or(TinyUIError::NoConnectionInfoCreated)?
.fill(
self.port_list.selected_port()?,
self.baudrate.selected_baudrate()?,
self.start_frequency.mhz_to_usize(),
self.stop_frequency.mhz_to_usize(),
self.points.int_to_usize(),
self.repeat.int_to_usize(),
);
self.connection_info = co.clone();
let co = co.unwrap();
let connection = self.get_connection_info()?.clone();
self.save_config()?;
thread::spawn(move || {
if let Err(status) = scan::scan_with_progress(co) {
log::error!("An error occured during thread exec: {status}");
if !connection.has_error() {
connection.set_error(Some(status.into()));
}
connection.set_connection_status(ConnectionStatus::ConnectionFailure);
}
});
}
AppState::EndWindow => {
self.should_quit = true;
}
AppState::Finished => {
self.flow_state = AppState::EndWindow;
self.init_end()?;
}
AppState::Error => {
self.should_quit = true;
}
}
Ok(())
}
}

786
src/ui/mod.rs Normal file
View File

@ -0,0 +1,786 @@
//! Terminal control flow: initialize widgets, handle input and start workers.
mod state;
mod view;
use crate::{
error::{AppError, UiError},
scan::{self, ScanState, ScanStatus},
};
use ratatui::{
crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
style::{Color, Modifier, Style},
widgets::{Block, LineGauge, List},
DefaultTerminal,
};
use serialport::SerialPortInfo;
pub(crate) use state::App;
use state::{
AppState, BaudRateList, InputDirection, MenuItems, NumericInput, Plot, PortList,
SelectedConnection, SelectedScan,
};
use std::{path::PathBuf, thread, time::Duration};
use strum::EnumCount;
use tiny_wb::{config::Config, live::TraceMode, protocol::ScanRequest};
impl App {
/// Construct UI state from already validated settings; no file I/O here.
pub(crate) fn new(info: Vec<SerialPortInfo>, config: Config, config_path: PathBuf) -> Self {
Self {
should_quit: false,
baudrate: BaudRateList::new(&config),
port_list: PortList::from_serial(info, &config),
flow_state: AppState::default(),
status_message: String::new(),
menu_items: MenuItems::default(),
start_frequency: NumericInput::new(
config.start_frequency,
config.scan.frequency_step_mhz,
0,
5_400,
),
stop_frequency: NumericInput::new(
config.stop_frequency,
config.scan.frequency_step_mhz,
10,
5_400,
),
points: NumericInput::new(
config.points,
config.scan.points_step,
config.scan.min_points,
config.scan.max_points,
),
repeat: NumericInput::new(config.repeat, 1, 1, config.scan.max_repeat),
scan_state: ScanState::default(),
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_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.
pub(crate) fn run(
&mut self,
mut terminal: DefaultTerminal,
) -> Result<(), color_eyre::eyre::Error> {
self.init_config()?;
loop {
if let Err(error) = self.refresh_scan() {
self.scan_state.fail(error);
self.flow_state = AppState::Error;
}
self.refresh_live();
let mut draw_error = None;
terminal.draw(|frame| {
draw_error = self.draw(frame).err();
})?;
if let Some(error) = draw_error {
return Err(error.into());
}
if self.should_quit {
break;
}
let timeout = Duration::from_millis(self.config.ui.poll_interval_ms);
if event::poll(timeout)? {
if let Event::Key(key) = event::read()? {
if let Err(e) = self.handle_start_keys(key) {
self.scan_state.fail(e);
self.flow_state = AppState::Error;
};
};
}
}
Ok(())
}
/// Initialization of the config window
fn init_config(&mut self) -> Result<(), UiError> {
self.menu_items.portlist = Some(
List::new(self.port_list.to_vecstr())
.block(Block::bordered().title("COM Ports"))
.highlight_style(
Style::default()
.add_modifier(Modifier::ITALIC)
.bg(Color::Blue),
)
.repeat_highlight_symbol(true),
);
self.menu_items.baudlist = Some(
List::new(self.baudrate.to_vecstr())
.block(Block::bordered().title("Baudrates"))
.highlight_style(
Style::default()
.add_modifier(Modifier::ITALIC)
.bg(Color::Blue),
)
.repeat_highlight_symbol(true),
);
self.status_message = format!(
"TinyWB version {}-{}, by the Dandaedre 🄯 2024",
env!("CARGO_PKG_VERSION"),
env!("GIT_HASH")
);
self.update_color()
}
/// Initialize the progress window
fn init_progress(&mut self) -> Result<(), UiError> {
self.menu_items.progress_bar = Some(
LineGauge::default()
.filled_style(Style::default().fg(Color::Blue))
.unfilled_style(Style::default().fg(Color::Red))
.label("Progress:"),
);
Ok(())
}
/// Map press events to navigation; releases and repeats do not mutate state.
fn handle_start_keys(&mut self, key: KeyEvent) -> Result<(), UiError> {
if key.kind != KeyEventKind::Press {
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 {
KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down),
KeyCode::Char('k') | KeyCode::Up => self.change_cursor_position(InputDirection::Up),
KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left)?,
KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right)?,
KeyCode::Enter => match self.flow_state {
AppState::Scanning => (),
_ => self.next_step()?,
},
_ => {}
}
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.
fn change_cursor_position(&mut self, direction: InputDirection) {
match self.flow_state {
AppState::SelectingConnection(ref selected_menu) => match selected_menu {
SelectedConnection::Baudrate => self.baudrate.change_cursor(direction),
SelectedConnection::Port => self.port_list.change_cursor(direction),
},
AppState::SelectingScan(ref selected_menu) => match selected_menu {
SelectedScan::StartFreq => self.start_frequency.change_value(direction),
SelectedScan::FinalFreq => self.stop_frequency.change_value(direction),
SelectedScan::Points => self.points.change_value(direction),
SelectedScan::Repeat => self.repeat.change_value(direction),
},
AppState::Complete => (),
AppState::Scanning => (),
AppState::Live => (),
AppState::Error => (),
}
}
/// Move horizontally within the current screen, clamping at its edges.
fn next_menu(&mut self, direction: InputDirection) -> Result<(), UiError> {
if let Some(s) = match self.flow_state {
AppState::SelectingConnection(ref r) => {
let v = *r as usize;
match direction {
InputDirection::Right => Some(AppState::SelectingConnection(
SelectedConnection::from_repr((v + 1).min(SelectedConnection::COUNT - 1))
.ok_or(UiError::MenuSelection)?,
)),
InputDirection::Left => Some(AppState::SelectingConnection(
SelectedConnection::from_repr(v.saturating_sub(1))
.ok_or(UiError::MenuSelection)?,
)),
_ => None,
}
}
AppState::SelectingScan(ref r) => {
let v = *r as usize;
match direction {
InputDirection::Right => Some(AppState::SelectingScan(
SelectedScan::from_repr((v + 1).min(SelectedScan::COUNT - 1))
.ok_or(UiError::MenuSelection)?,
)),
InputDirection::Left => Some(AppState::SelectingScan(
SelectedScan::from_repr(v.saturating_sub(1))
.ok_or(UiError::MenuSelection)?,
)),
_ => None,
}
}
AppState::Complete => None,
AppState::Scanning => None,
AppState::Live => None,
AppState::Error => None,
} {
self.flow_state = s;
}
self.update_color()?;
Ok(())
}
/// Validate before saving settings or starting the serial worker.
fn next_step(&mut self) -> Result<(), UiError> {
match self.flow_state {
AppState::SelectingConnection(_) => {
self.port_list.selected_port()?;
self.baudrate.selected_baudrate()?;
self.flow_state = AppState::SelectingScan(SelectedScan::default());
}
AppState::SelectingScan(_) => {
self.start_selected_scan()?;
}
AppState::Complete => {
self.should_quit = true;
}
AppState::Scanning => {}
AppState::Live => {}
AppState::Error => {
self.should_quit = true;
}
}
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.
fn refresh_scan(&mut self) -> Result<(), UiError> {
if matches!(self.flow_state, AppState::Scanning) {
match self.scan_state.status() {
ScanStatus::Complete => {
let data = self.scan_state.take_samples()?;
self.plot = Some(Plot::new(self.scan_state.message(), data));
self.flow_state = AppState::Complete;
}
ScanStatus::Failed => self.flow_state = AppState::Error,
ScanStatus::Ready | ScanStatus::Running => {}
}
}
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)]
mod tests {
use super::*;
use ratatui::{backend::TestBackend, crossterm::event::KeyModifiers, Terminal};
fn app() -> App {
App::new(
vec![SerialPortInfo {
port_name: "test-device".into(),
port_type: serialport::SerialPortType::Unknown,
}],
Config::default(),
PathBuf::from("unused-settings.toml"),
)
}
#[test]
fn navigation_preserves_settings_and_ignores_key_releases() {
let mut app = app();
app.init_config().unwrap();
let mut release = KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE);
release.kind = KeyEventKind::Release;
app.handle_start_keys(release).unwrap();
assert!(!app.should_quit);
app.next_step().unwrap();
assert!(matches!(
app.flow_state,
AppState::SelectingScan(SelectedScan::StartFreq)
));
app.change_cursor_position(InputDirection::Up);
assert_eq!(app.start_frequency.value(), 250);
for _ in 0..10 {
app.next_menu(InputDirection::Right).unwrap();
}
assert!(matches!(
app.flow_state,
AppState::SelectingScan(SelectedScan::Repeat)
));
app.config.output.include_header = true;
assert!(app.selected_config().unwrap().output.include_header);
app.handle_start_keys(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))
.unwrap();
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]
fn missing_ports_and_invalid_spans_fail_before_saving_or_scanning() {
let mut app = App::new(
Vec::new(),
Config::default(),
PathBuf::from("unused-settings.toml"),
);
assert!(matches!(app.next_step(), Err(UiError::NoPortSelected)));
let mut app = self::app();
app.next_step().unwrap();
app.start_frequency = NumericInput::new(900, 10, 0, 5_400);
assert!(app.next_step().is_err());
assert_eq!(app.scan_state.status(), ScanStatus::Ready);
}
#[test]
fn completion_moves_samples_once_and_failure_selects_error_screen() {
let mut app = app();
app.flow_state = AppState::Scanning;
app.scan_state
.complete(PathBuf::from("scan.csv"), vec![(240.0, -64.0)]);
app.refresh_scan().unwrap();
assert!(matches!(app.flow_state, AppState::Complete));
assert_eq!(app.plot.as_ref().unwrap().data, vec![(240.0, -64.0)]);
app.refresh_scan().unwrap();
app.flow_state = AppState::Scanning;
app.scan_state.fail("disconnected");
app.refresh_scan().unwrap();
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]
fn every_screen_renders_without_a_physical_terminal() {
for (width, height) in [(120, 40), (40, 10), (1, 1)] {
let mut app = app();
app.init_config().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();
for screen in [
AppState::default(),
AppState::SelectingScan(SelectedScan::StartFreq),
AppState::SelectingScan(SelectedScan::FinalFreq),
AppState::SelectingScan(SelectedScan::Points),
AppState::SelectingScan(SelectedScan::Repeat),
AppState::Scanning,
AppState::Live,
AppState::Complete,
AppState::Error,
] {
app.flow_state = screen;
terminal.draw(|frame| app.draw(frame).unwrap()).unwrap();
}
}
}
#[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"));
}
}

667
src/ui/state.rs Normal file
View File

@ -0,0 +1,667 @@
//! UI state, bounded selections and rendering widget storage.
use color_eyre::Result;
use ratatui::{
style::Color,
widgets::{LineGauge, List, ListState},
};
use serialport::SerialPortInfo;
use std::path::PathBuf;
use strum::EnumCount;
use strum::FromRepr;
use crate::{
error::{AppError, UiError},
scan::{LiveState, ScanState},
};
use tiny_wb::{config::Config, protocol::ScanRequest};
/// Color of a selected border
pub(crate) const SELECTED_COLOR: Color = Color::White;
/// Color of an unselected item
pub(crate) const UNSELECTED_COLOR: Color = Color::DarkGray;
/// This struct holds the current state of the app.
#[derive(Debug)]
pub(crate) struct App {
/// Whether the user requested exit.
pub(crate) should_quit: bool,
/// Selectable baud rates.
pub(crate) baudrate: BaudRateList,
/// Enumerated serial ports.
pub(crate) port_list: PortList,
/// Current screen and focused field.
pub(crate) flow_state: AppState,
/// Cached widgets rebuilt during screen initialization.
pub(crate) menu_items: MenuItems,
/// Application version shown above the controls.
pub(crate) status_message: String,
/// Requested start frequency, in MHz.
pub(crate) start_frequency: NumericInput,
/// Requested stop frequency, in MHz.
pub(crate) stop_frequency: NumericInput,
/// Requested number of samples.
pub(crate) points: NumericInput,
/// Measurements per point.
pub(crate) repeat: NumericInput,
/// Shared acquisition telemetry; request settings are passed separately.
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.
pub(crate) config: Config,
/// Explicit settings path selected at startup.
pub(crate) config_path: PathBuf,
/// Last launched request and settings, retained for one-key repetition.
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)]
/// Numeric input state with bounded keyboard increments.
pub(crate) struct NumericInput {
/// Current bounded value.
value: usize,
/// Keyboard increment.
increment: usize,
/// Inclusive lower bound.
min_clamp: usize,
/// Inclusive upper bound.
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 {
/// Change the value depending on selection
pub(crate) fn change_value(&mut self, direction: InputDirection) {
match direction {
InputDirection::Up => {
self.value = self
.value
.saturating_add(self.increment)
.clamp(self.min_clamp, self.max_clamp)
}
InputDirection::Down => {
self.value = self
.value
.saturating_sub(self.increment)
.clamp(self.min_clamp, self.max_clamp)
}
_ => (),
}
}
/// Create bounded input, clamping a supplied value to validated bounds.
pub(crate) fn new(value: usize, increment: usize, min_clamp: usize, max_clamp: usize) -> Self {
Self {
value: value.clamp(min_clamp, max_clamp),
increment,
max_clamp,
min_clamp,
edit_buffer: None,
invalid_edit: false,
}
}
/// Read the current value.
pub(crate) fn value(&self) -> usize {
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)]
/// The inner state of the app, useful for display and keystrokes
pub(crate) enum AppState {
/// Initial config, baudrate and port
SelectingConnection(SelectedConnection),
/// Final config, frequencies and points
SelectingScan(SelectedScan),
/// The end window for confirmation
Complete,
/// Acquisition and export progress.
Scanning,
/// Repeated complete snapshots displayed while acquisition continues.
Live,
/// Error window
Error,
}
impl Default for AppState {
fn default() -> Self {
Self::SelectingConnection(SelectedConnection::default())
}
}
/// The selected item in the config
#[derive(Debug, Default, EnumCount, FromRepr, Clone, Copy)]
pub(crate) enum SelectedConnection {
/// Selects the ports
#[default]
Port,
/// Selects the baudrate
Baudrate,
}
/// The selected item in the final menu
#[derive(Debug, Default, EnumCount, FromRepr, Copy, Clone)]
pub(crate) enum SelectedScan {
/// Selects the start frequency
#[default]
StartFreq,
/// Selects the final frequency
FinalFreq,
/// Selects the number of points
Points,
/// Selects the repeat
Repeat,
}
/// Configured baud rates and their selected index.
#[derive(Debug)]
pub(crate) struct BaudRateList {
/// Choices loaded from validated settings.
pub(crate) baudrates: Vec<u32>,
/// Selection state used by Ratatui.
pub(crate) state: ListState,
}
impl BaudRateList {
/// Construct choices with the configured rate selected.
pub(crate) fn new(config: &Config) -> Self {
Self {
baudrates: config.serial.baudrates.clone(),
state: ListState::default().with_selected(
config
.serial
.baudrates
.iter()
.position(|rate| *rate == config.baudrate),
),
}
}
/// Format values for the list widget.
pub(crate) fn to_vecstr(&self) -> Vec<String> {
self.baudrates.iter().map(u32::to_string).collect()
}
/// Move without selecting an index beyond the configured choices.
pub(crate) fn change_cursor(&mut self, direction: InputDirection) {
move_list_selection(&mut self.state, self.baudrates.len(), direction);
}
/// Resolve the selected value safely even if the list changed.
pub(crate) fn selected_baudrate(&self) -> Result<u32, UiError> {
self.state
.selected()
.and_then(|index| self.baudrates.get(index))
.copied()
.ok_or(UiError::MenuSelection)
}
}
/// A wrapper over the list of ports
#[derive(Debug)]
pub(crate) struct PortList {
/// The list of found ports
pub(crate) ports: Vec<String>,
/// The inner state of the widget
pub(crate) state: ListState,
}
impl PortList {
/// Make a port list from a serial reading
pub(crate) fn from_serial(info: Vec<SerialPortInfo>, config: &Config) -> Self {
let ports: Vec<String> = info.into_iter().map(|port| port.port_name).collect();
let selected = find_best_port(&ports, config);
Self {
ports,
state: ListState::default().with_selected(selected),
}
}
/// Convert the list of ports
pub(crate) fn to_vecstr(&self) -> Vec<String> {
self.ports.clone()
}
/// Change the selected item
pub(crate) fn change_cursor(&mut self, direction: InputDirection) {
move_list_selection(&mut self.state, self.ports.len(), direction);
}
/// Returns the final selected port
pub(crate) fn selected_port(&self) -> Result<String, UiError> {
self.state
.selected()
.and_then(|index| self.ports.get(index))
.cloned()
.ok_or(UiError::NoPortSelected)
}
}
#[derive(Debug, Default)]
/// Cached widgets; none borrow mutable application data.
pub(crate) struct MenuItems {
/// Cached list widget.
pub(crate) portlist: Option<List<'static>>,
/// Cached list widget.
pub(crate) baudlist: Option<List<'static>>,
/// The progress bar
pub(crate) progress_bar: Option<LineGauge<'static>>,
}
/// Prefer the saved device, then configured candidates, then the first port.
fn find_best_port(ports: &[String], config: &Config) -> Option<usize> {
std::iter::once(&config.port)
.chain(config.serial.preferred_ports.iter())
.find_map(|candidate| ports.iter().position(|port| port == candidate))
.or_else(|| (!ports.is_empty()).then_some(0))
}
/// Keep selection valid without relying on a later draw to clamp its index.
fn move_list_selection(state: &mut ListState, length: usize, direction: InputDirection) {
if length == 0 {
state.select(None);
return;
}
let current = state.selected().unwrap_or(0).min(length - 1);
let next = match direction {
InputDirection::Up => current.saturating_sub(1),
InputDirection::Down => current.saturating_add(1).min(length - 1),
_ => current,
};
state.select(Some(next));
}
impl App {
/// Build validated settings from the current selection, preserving all sections.
pub(crate) fn selected_config(&self) -> Result<Config, UiError> {
let config = Config {
port: self.port_list.selected_port()?,
baudrate: self.baudrate.selected_baudrate()?,
start_frequency: self.start_frequency.value(),
stop_frequency: self.stop_frequency.value(),
points: self.points.value(),
repeat: self.repeat.value(),
..self.config.clone()
};
config.validate().map_err(AppError::from)?;
Ok(config)
}
}
/// Navigation intent independent of terminal key codes.
#[derive(Debug, Clone, Copy)]
pub(crate) enum InputDirection {
/// Increase a numeric value or move toward the first list item.
Up,
/// Increase a list index or decrease a numeric value.
Down,
/// Select the next field.
Right,
/// Select the previous field.
Left,
}
impl std::fmt::Display for NumericInput {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
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)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn numeric_input_clamps_and_saturates_without_overflow() {
let mut field = NumericInput::new(999, 10, 0, 100);
assert_eq!(field.value(), 100);
field.change_value(InputDirection::Up);
assert_eq!(field.value(), 100);
field.change_value(InputDirection::Down);
assert_eq!(field.value(), 90);
let mut field = NumericInput::new(usize::MAX - 1, 10, 0, usize::MAX);
field.change_value(InputDirection::Up);
assert_eq!(field.value(), usize::MAX);
let mut field = NumericInput::new(1, 10, 0, 100);
field.change_value(InputDirection::Down);
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]
fn empty_and_stale_port_selections_return_errors() {
let mut list = PortList::from_serial(Vec::new(), &Config::default());
list.change_cursor(InputDirection::Down);
assert!(list.state.selected().is_none());
assert!(matches!(list.selected_port(), Err(UiError::NoPortSelected)));
list.state.select(Some(100));
assert!(list.selected_port().is_err());
}
#[test]
fn saved_port_precedes_preferences_and_unavailable_ports_fall_back() {
let mut config = Config::default();
let ports = vec!["other".into(), "COM3".into(), "saved".into()];
assert_eq!(find_best_port(&ports, &config), Some(1));
config.port = "saved".into();
assert_eq!(find_best_port(&ports, &config), Some(2));
assert_eq!(find_best_port(&["other".into()], &config), Some(0));
assert_eq!(find_best_port(&[], &config), None);
}
#[test]
fn custom_baud_choices_are_bounded_before_rendering() {
let config =
Config::from_toml("baudrate = 9600\n[serial]\nbaudrates = [9600, 19200]").unwrap();
let mut list = BaudRateList::new(&config);
assert_eq!(list.selected_baudrate().unwrap(), 9600);
for _ in 0..100 {
list.change_cursor(InputDirection::Down);
}
assert_eq!(list.selected_baudrate().unwrap(), 19200);
for _ in 0..100 {
list.change_cursor(InputDirection::Up);
}
assert_eq!(list.selected_baudrate().unwrap(), 9600);
}
}

527
src/ui/view.rs Normal file
View File

@ -0,0 +1,527 @@
//! Ratatui rendering; acquisition results arrive through shared scan state.
use super::state::{
App, AppState, Plot, SelectedConnection, SelectedScan, SELECTED_COLOR, UNSELECTED_COLOR,
};
use crate::error::UiError;
use ratatui::{
layout::{Constraint, Layout, Rect},
style::{Color, Style},
symbols::Marker,
widgets::{Axis, Block, Chart, Clear, Dataset, GraphType, List, Paragraph, Wrap},
Frame,
};
impl App {
/// Render the active screen; lifecycle transitions happen in the controller.
pub(super) fn draw(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> {
match self.flow_state {
AppState::SelectingConnection(_) => self.draw_config(frame),
AppState::SelectingScan(_) => self.draw_final_config(frame),
AppState::Scanning => self.draw_progress(frame),
AppState::Live => self.draw_live(frame),
AppState::Complete => self.draw_end_window(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.
fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> {
let [_, spaced, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(100),
Constraint::Min(7),
])
.areas(frame.area());
let [_, title_area, _, main_area, _, status_area] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(3),
Constraint::Length(1),
Constraint::Length(3),
Constraint::Min(0),
Constraint::Length(1),
])
.areas(spaced);
let [area_minf, area_maxf, area_points, repeat] = Layout::horizontal([
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
Constraint::Percentage(25),
])
.areas(main_area);
let (mif_color, maf_color, poi_color, rpt_color) = match self.flow_state {
AppState::SelectingScan(SelectedScan::StartFreq) => (
SELECTED_COLOR,
UNSELECTED_COLOR,
UNSELECTED_COLOR,
UNSELECTED_COLOR,
),
AppState::SelectingScan(SelectedScan::FinalFreq) => (
UNSELECTED_COLOR,
SELECTED_COLOR,
UNSELECTED_COLOR,
UNSELECTED_COLOR,
),
AppState::SelectingScan(SelectedScan::Points) => (
UNSELECTED_COLOR,
UNSELECTED_COLOR,
SELECTED_COLOR,
UNSELECTED_COLOR,
),
AppState::SelectingScan(SelectedScan::Repeat) => (
UNSELECTED_COLOR,
UNSELECTED_COLOR,
UNSELECTED_COLOR,
SELECTED_COLOR,
),
_ => unreachable!(),
};
frame.render_widget(
Paragraph::new(self.start_frequency.to_string())
.block(Block::bordered().title("Start Frequency"))
.style(mif_color),
area_minf,
);
frame.render_widget(
Paragraph::new(self.stop_frequency.to_string())
.block(Block::bordered().title("Stop Frequency"))
.style(maf_color),
area_maxf,
);
frame.render_widget(
Paragraph::new(self.points.to_string())
.block(Block::bordered().title("Points"))
.style(poi_color),
area_points,
);
frame.render_widget(
Paragraph::new(self.repeat.to_string())
.block(Block::bordered().title("Repeat"))
.style(rpt_color),
repeat,
);
self.update_color()?;
frame.render_widget(
Paragraph::new(self.status_message.clone())
.wrap(Wrap { trim: true })
.block(Block::bordered()),
title_area,
);
self.render_footer(frame, status_area);
Ok(())
}
/// Show keyboard guidance below editable settings.
fn render_footer(&self, frame: &mut Frame, area: Rect) {
let guidance = match self.flow_state {
AppState::SelectingScan(SelectedScan::StartFreq | SelectedScan::FinalFreq)
if self.start_frequency.is_editing() || self.stop_frequency.is_editing() =>
{
"Type MHz; Backspace deletes, ↲ applies, and Esc cancels."
}
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.
fn draw_config(&mut self, frame: &mut Frame) -> Result<(), UiError> {
let [_, spaced, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(100),
Constraint::Min(7),
])
.areas(frame.area());
let [_, title_area, _, main_area, status_area] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(3),
Constraint::Length(1),
Constraint::Min(10),
Constraint::Length(1),
])
.areas(spaced);
let [area_ports, area_baud] =
Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)])
.areas(main_area);
let list_ports = self
.menu_items
.portlist
.as_ref()
.ok_or(UiError::UninitializedItemList("Port", line!(), file!()))?;
let list_baudrates = self
.menu_items
.baudlist
.as_ref()
.ok_or(UiError::UninitializedItemList("Baud", line!(), file!()))?;
frame.render_stateful_widget(list_ports, area_ports, &mut self.port_list.state);
frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state);
frame.render_widget(
Paragraph::new(self.status_message.clone())
.wrap(Wrap { trim: true })
.block(Block::bordered()),
title_area,
);
self.render_footer(frame, status_area);
Ok(())
}
/// Render a snapshot of worker progress without consuming completed samples.
fn draw_progress(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> {
let [_, main_s, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(90),
Constraint::Min(7),
])
.areas(frame.area());
let [title_area, progress_area, main_area, _, _] = Layout::vertical([
Constraint::Length(3),
Constraint::Length(1),
Constraint::Min(10),
Constraint::Length(1),
Constraint::Length(1),
])
.areas(main_s);
let (pb, status, message) = {
let status = self.scan_state.message();
let status = Paragraph::new(status.clone())
.block(Block::bordered().title("Operation"))
.style(SELECTED_COLOR);
let message = self.scan_state.info();
let message = Paragraph::new(message.clone())
.wrap(Wrap { trim: true })
.block(Block::bordered().title("TinySA Info"))
.style(SELECTED_COLOR);
let pb = self
.menu_items
.progress_bar
.take()
.ok_or(UiError::UninitializedItemList(
"ProgressBar",
line!(),
file!(),
))?
.ratio(self.scan_state.progress() as f64 / 100.);
(pb, status, message)
};
frame.render_widget(pb.clone(), progress_area);
frame.render_widget(status, title_area);
frame.render_widget(message, main_area);
self.menu_items.progress_bar = Some(pb);
Ok(())
}
/// Render the original failure context and the last worker operation.
fn draw_error(&mut self, frame: &mut Frame) -> Result<(), UiError> {
let [_, main_s, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(90),
Constraint::Min(7),
])
.areas(frame.area());
let [_, title_area, _main_area, message_area, _, footer_area] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(3),
Constraint::Length(1),
Constraint::Min(10),
Constraint::Length(1),
Constraint::Length(1),
])
.areas(main_s);
let conn_status = self.scan_state.status();
let status_message = self.error_message_from_current_error();
let status = Paragraph::new(status_message)
.wrap(Wrap { trim: true })
.block(Block::bordered().title("Status"))
.style(Color::Red);
let additional = self.scan_state.error().unwrap_or_default();
let error = Paragraph::new(format!(
"Last status: {:?}\nLast message: {}\n{}",
conn_status,
self.scan_state.message(),
additional
))
.wrap(Wrap { trim: true })
.block(Block::bordered().title("Status"));
let footer = Paragraph::new("Press ↲ or q to exit".to_string()).centered();
frame.render_widget(status, title_area);
frame.render_widget(error, message_area);
frame.render_widget(footer, footer_area);
Ok(())
}
/// Display the original error context rather than maintaining a second mapping.
fn error_message_from_current_error(&self) -> String {
self.scan_state
.error()
.unwrap_or_else(|| "An unspecified error occurred".into())
}
/// Plot completed samples using the configured level bounds.
fn draw_end_window(&mut self, frame: &mut Frame) -> Result<(), UiError> {
let [_, main_s, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(90),
Constraint::Min(7),
])
.areas(frame.area());
let [title_area, _main_area, graph_area, _, footer_area] = Layout::vertical([
Constraint::Length(3),
Constraint::Length(1),
Constraint::Min(10),
Constraint::Length(1),
Constraint::Length(1),
])
.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!(
"{} — {} points — visible {} to {} MHz",
plot.label,
plot.data.len(),
format_frequency(bounds[0], span),
format_frequency(bounds[1], span),
))
.block(Block::bordered().title("Status"))
.style(SELECTED_COLOR);
let datasets = vec![Dataset::default()
.marker(Marker::Dot)
.graph_type(GraphType::Scatter)
.style(Style::new().yellow())
.data(&plot.data)];
let midpoint = (bounds[0] + bounds[1]) / 2.0;
let chart = Chart::new(datasets)
.x_axis(
Axis::default()
.title("Frequency (MHz)")
.bounds(bounds)
.style(Style::default().fg(Color::Gray))
.labels([
format_frequency(bounds[0], span),
format_frequency(midpoint, span),
format_frequency(bounds[1], span),
]),
)
.y_axis(
Axis::default()
.bounds([self.config.ui.chart_min_dbm, self.config.ui.chart_max_dbm])
.style(Style::default().fg(Color::Gray))
.labels([
format!("{} dBm", self.config.ui.chart_min_dbm),
format!(
"{} dBm",
(self.config.ui.chart_min_dbm + self.config.ui.chart_max_dbm) / 2.0
),
format!("{} 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);
}
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!(
"zoom {} / {}; pan {} / {}; reset {}; m peak{}; q exits",
keys.zoom_in.join("|"),
keys.zoom_out.join("|"),
keys.pan_left.join("|"),
keys.pan_right.join("|"),
keys.reset_view.join("|"),
restart,
))
.centered();
frame.render_widget(status, title_area);
frame.render_widget(footer, footer_area);
Ok(())
}
}
/// 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 {
/// Apply the active/inactive style to a cached list widget.
pub(crate) fn change_color(
&mut self,
name: &'static str,
list: List<'static>,
color: Color,
) -> Option<List<'static>> {
Some(
list.block(Block::bordered().title(name).border_style(color))
.style(Style::default().fg(color)),
)
}
}
impl App {
/// Update connection selection styling after navigation.
pub(crate) fn update_color(&mut self) -> Result<(), UiError> {
match self.flow_state {
AppState::SelectingConnection(ref c) => {
let (p_c, b_c) = match c {
SelectedConnection::Baudrate => (UNSELECTED_COLOR, SELECTED_COLOR),
SelectedConnection::Port => (SELECTED_COLOR, UNSELECTED_COLOR),
};
let (p, b) = (
self.menu_items
.portlist
.take()
.ok_or(UiError::UninitializedItemList(
"Port List",
line!(),
file!(),
))?,
self.menu_items
.baudlist
.take()
.ok_or(UiError::UninitializedItemList(
"Port List",
line!(),
file!(),
))?,
);
self.menu_items.portlist = self.change_color("COM Ports", p, p_c);
self.menu_items.baudlist = self.change_color("Baudrate", b, b_c);
}
AppState::SelectingScan(_selected_final_config) => (),
_ => (),
}
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");
}
}

View File

@ -1,415 +0,0 @@
//! All ui structures and utility functions
//! The (minimal) user interface to control the program
use color_eyre::Result;
use ratatui::{
style::{Color, Style},
widgets::{Block, LineGauge, List, ListState, Paragraph},
};
use serialport::SerialPortInfo;
use std::{iter::Iterator, ops::Add};
use strum::{EnumCount, EnumIter};
use strum::{FromRepr, IntoEnumIterator};
use crate::structs::{ConnectionInfo, InputDirection, SavedConfig, TinyError, TinyUIError};
/// Color of a selected border
pub(crate) const SELECTED_COLOR: Color = Color::White;
/// Color of an unselected item
pub(crate) const UNSELECTED_COLOR: Color = Color::DarkGray;
/// This struct holds the current state of the app.
#[derive(Debug)]
pub(crate) struct AppInfo<'a> {
/// Wether the app sould immediately quit
pub(crate) should_quit: bool,
/// The list of baudrates
pub(crate) baudrate: BaudRateList,
/// The list of ports
pub(crate) port_list: PortList,
/// State of the configuration, akin to tab or window
pub(crate) flow_state: AppState,
/// The list of menu item generated
pub(crate) menu_items: MenuItems<'a>,
/// A debug message string
pub(crate) status_message: String,
/// The start frequency
pub(crate) start_frequency: UIUsize,
/// The stop frequency
pub(crate) stop_frequency: UIUsize,
/// The number of points
pub(crate) points: UIUsize,
/// Number of times to repeat a measure
pub(crate) repeat: UIUsize,
/// A struct holding all the information needed to handle a connection with a tinySA
pub(crate) connection_info: Option<ConnectionInfo>,
/// The return data, moved from a mutex to a static place
pub(crate) return_data: Vec<(f64, f64)>,
/// Whether an unrecoverable error has been logged (and therefore stop logging it)
pub(crate) logged_message: bool,
}
#[derive(Debug)]
pub(crate) struct UIUsize {
/// Current value held by the usize
value: usize,
/// Increment by witch it can be upped
increment: usize,
/// Min value to clamp it to
min_clamp: usize,
/// Max value to clamp it to
max_clamp: usize,
}
impl UIUsize {
/// Change the value depending on selection
pub(crate) fn change_value(&mut self, direction: InputDirection) {
match direction {
InputDirection::Up => {
self.value = self
.value
.add(self.increment)
.clamp(self.min_clamp, self.max_clamp)
}
InputDirection::Down => {
self.value = self
.value
.saturating_sub(self.increment)
.clamp(self.min_clamp, self.max_clamp)
}
_ => (),
}
}
/// Create a new UIUsize, usefull for TUI manipulation
pub(crate) fn new(value: usize, increment: usize, min_clamp: usize, max_clamp: usize) -> Self {
Self {
value,
increment,
max_clamp,
min_clamp,
}
}
/// Convert to a string with the litteral value
pub(crate) fn int_to_string(&self) -> String {
format!("{}", self.value)
}
/// Convert to mhz multiplying it by 1_000_000
pub(crate) fn mhz_to_usize(&self) -> usize {
self.value * 1000000
}
/// Output inner value
pub(crate) fn int_to_usize(&self) -> usize {
self.value
}
}
#[derive(Debug)]
/// The inner state of the app, useful for display and keystrokes
pub(crate) enum AppState {
/// Initial config, baudrate and port
InitialConfig(SelectedConfig),
/// Final config, frequencies and points
FinalConfig(SelectedFinalConfig),
/// The end window for confirmation
EndWindow,
/// Save window
Finished,
/// Error window
Error,
}
impl Default for AppState {
fn default() -> Self {
Self::InitialConfig(SelectedConfig::default())
}
}
#[macro_export]
/// Shortcut for move right
macro_rules! mright {
($v:ident, $cname:ident,$fname:ident) => {
Some(AppState::$cname(
$fname::from_repr(min(($v + 1), $fname::COUNT - 1))
.ok_or(TinyUIError::MenuSelectionError)?,
))
};
}
#[macro_export]
/// Shortcut to move left
macro_rules! mleft {
($v:ident, $cname:ident,$fname:ident) => {
if $v == 0 {
None
} else {
Some(AppState::$cname(
$fname::from_repr($v - 1).ok_or(TinyUIError::MenuSelectionError)?,
))
}
};
}
/// The selected item in the config
#[derive(Debug, EnumCount, FromRepr, Clone, Copy)]
pub(crate) enum SelectedConfig {
/// Selects the ports
Port,
/// Selects the baudrate
Baudrate,
// /// Selects <Ok> to proceed
// Proceed,
}
impl Default for SelectedConfig {
fn default() -> Self {
Self::Port
}
}
/// The selected item in the final menu
#[derive(Debug, EnumCount, FromRepr, Copy, Clone)]
pub(crate) enum SelectedFinalConfig {
/// Selects the start frequency
StartFreq,
/// Selects the final frequency
FinalFreq,
/// Selects the number of points
Points,
/// Selects the repeat
Repeat,
// /// Selects <Ok> to proceed
// Proceed,
}
impl Default for SelectedFinalConfig {
fn default() -> Self {
Self::StartFreq
}
}
/// The list of all baudrates selectables
#[derive(Debug)]
pub(crate) struct BaudRateList {
// /// The selected baudrate (default : BAUD1115200)
// pub(crate) selected: usize,
/// The baudrate list
pub(crate) baudrates: Vec<BaudRate>,
/// The inner state of the widget
pub(crate) state: ListState,
}
impl BaudRateList {
/// Convert into a vec of strings, this is extremely expensive and shouldn't be done that way
pub(crate) fn to_vecstr(&self) -> Vec<String> {
self.baudrates
.iter()
.map(|i| format!("{}", *i as usize))
.collect()
}
/// Change the cursor position on the baudrates
pub(crate) fn change_cursor(&mut self, direction: InputDirection) {
match direction {
InputDirection::Down => self.state.select_next(),
InputDirection::Up => self.state.select_previous(),
_ => (),
}
}
/// Create a baudrate from a config file
pub(crate) fn from_conf(loaded_conf: &Result<SavedConfig, TinyError>) -> BaudRateList {
if let Ok(c) = loaded_conf {
for (i, baud) in BaudRate::iter().enumerate() {
if c.baudrate == baud as u32 {
return Self {
state: ListState::default().with_selected(Some(i)),
..Default::default()
};
}
}
}
Self::default()
}
/// Returns the final selected baudrate
pub(crate) fn selected_baudrate(&self) -> Result<u32, TinyUIError> {
Ok(BaudRate::iter()
.nth(
self.state
.selected()
.ok_or(TinyUIError::UninitializedItemList(
"Baudrate",
line!(),
file!(),
))?,
)
.ok_or(TinyUIError::MenuSelectionError)? as u32)
}
}
impl Default for BaudRateList {
fn default() -> Self {
Self {
baudrates: BaudRate::iter().collect::<Vec<_>>(),
state: ListState::default().with_selected(Some(3)),
}
}
}
/// A list of possible baudrates
#[derive(Debug, EnumIter, Copy, Clone)]
pub(crate) enum BaudRate {
BAUD19200 = 19_200,
BAUD38400 = 38_400,
BAUD57600 = 57_600,
BAUD115200 = 115_200,
BAUD230400 = 230_400,
BAUD460800 = 460_800,
BAUD921600 = 921_600,
BAUD1843200 = 1_843_200,
BAUD2000000 = 2_000_000,
BAUD3000000 = 3_000_000,
}
/// A wrapper over the list of ports
#[derive(Debug)]
pub(crate) struct PortList {
/// The list of found ports
pub(crate) ports: Vec<String>,
// /// The currently selected port (doing it that way completly avoids the )
// pub(crate) selected: usize,
/// The inner state of the widget
pub(crate) state: ListState,
}
impl PortList {
/// Make a port list from a serial reading
pub(crate) fn from_serial(
info: Vec<SerialPortInfo>,
saved_config: &Result<SavedConfig, TinyError>,
) -> Self {
let ports: Vec<String> = info.into_iter().map(|port| port.port_name).collect();
let selected = find_best_port(&ports, saved_config);
Self {
ports,
// selected,
state: ListState::default().with_selected(Some(selected)),
}
}
/// Convert the list of ports
pub(crate) fn to_vecstr(&self) -> Vec<String> {
self.ports.clone()
}
/// Change the selected item
pub(crate) fn change_cursor(&mut self, direction: InputDirection) {
match direction {
InputDirection::Up => self.state.select_previous(),
InputDirection::Down => self.state.select_next(),
_ => (),
}
}
/// Returns the final selected port
pub(crate) fn selected_port(&self) -> Result<String, TinyUIError> {
Ok(self.ports[self.state.selected().ok_or(TinyUIError::NoPortSelected)?].clone())
}
}
#[derive(Debug, Default)]
/// The static list of all menu items
pub(crate) struct MenuItems<'a> {
/// List of port items
pub(crate) portlist: Option<List<'a>>,
/// List of port items
pub(crate) baudlist: Option<List<'a>>,
/// List of all the textboxes
pub(crate) textboxes: Vec<Paragraph<'a>>,
/// The progress bar
pub(crate) progress_bar: Option<LineGauge<'a>>,
// /// Controller info
// pub(crate) info: Option<Chart<'a>>,
// /// The final graph
// pub(crate) graph: Option<Chart<'a>>,
}
/// Try to guess the best port to preselect
fn find_best_port(ports: &[String], saved_config: &Result<SavedConfig, TinyError>) -> usize {
let mut best_ports = vec!["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"];
let p: Vec<&str> = if let Ok(c) = saved_config {
let mut v = vec![&*c.port];
v.append(&mut best_ports);
v
} else {
best_ports
};
for port in p {
if let Some(p) = ports.iter().position(|v| v == port) {
return p;
}
}
0
}
impl<'a> AppInfo<'a> {
/// Put an item a specified color
pub(crate) fn change_color(
&mut self,
name: &'a str,
list: List<'a>,
color: Color,
) -> Option<List<'a>> {
Some(
list.block(Block::bordered().title(name).border_style(color))
.style(Style::default().fg(color)),
)
}
/// Save the config with the current runtime variables
pub(crate) fn save_config(&self) -> Result<(), TinyUIError> {
SavedConfig::save(self)
}
}
impl<'a> AppInfo<'a> {
/// Update all the colors
pub(crate) fn update_color(&mut self) -> Result<(), TinyUIError> {
match self.flow_state {
AppState::InitialConfig(ref c) => {
let (p_c, b_c) = match c {
SelectedConfig::Baudrate => (UNSELECTED_COLOR, SELECTED_COLOR),
SelectedConfig::Port => (SELECTED_COLOR, UNSELECTED_COLOR),
};
let (p, b) =
(
self.menu_items.portlist.take().ok_or(
TinyUIError::UninitializedItemList("Port List", line!(), file!()),
)?,
self.menu_items.baudlist.take().ok_or(
TinyUIError::UninitializedItemList("Port List", line!(), file!()),
)?,
);
// self.status_message = format!("{:?} p:{:?} {:?} {:?}", Instant::now(), p_c, b_c, c);
self.menu_items.portlist = self.change_color("COM Ports", p, p_c);
self.menu_items.baudlist = self.change_color("Baudrate", b, b_c);
}
// TODO: Have all color update here
AppState::FinalConfig(_selected_final_config) => (),
_ => (),
}
Ok(())
}
}
// /// Create a textbox with a custom title
// macro_rules! text_with_title {
// ($name:expr) => {{
// let mut texta = TextArea::default();
// let block = Block::default().title($name);
// texta.set_block(block);
// texta
// }};
// }

702
task.md Normal file
View File

@ -0,0 +1,702 @@
# tinySA Basic and Ultra implementation tasks
Planning baseline: repository state after `b4d1462`, reviewed 2026-10-05.
This file is the detailed implementation backlog. The
[roadmap](docs/roadmap.md) remains the short feature overview; shared IDs below
refer to the same work. All unchecked items are proposals, not implemented
features or certified device support. Stretch goals are unselected until the
user chooses them.
## What complete coverage means
Coverage here means instrument features, not Rust line coverage. Qualify each
exact model, hardware revision, firmware version, and host platform separately.
Basic and Ultra are the primary targets; Ultra+ and other revisions need
explicit profiles and evidence rather than inheriting support by name.
For every console command and front-panel feature, record one disposition:
implemented and verified; implemented but awaiting hardware; front-panel-only;
not present on this model/build; or blocked with a concrete upstream dependency.
No feature may disappear silently from the inventory. A documented limitation
completes the audit entry, but does not make that feature remotely implemented.
Do not advertise full remote coverage while remote-capable entries remain open.
Use the existing [source catalogue](docs/sources.md),
[protocol evidence](docs/usb-protocol.md), and
[compatibility matrix](docs/tiny-wb-operations.md#compatibility-matrix).
Their firmware observations are dated; this planning change does not reverify
upstream firmware. Command names below are investigation candidates until P01
confirms their syntax and availability on the selected build.
## Current baseline
Update 2026-10-05: automatic family detection, offset readback and common Ultra
normal-range acquisition are now implemented. The table below is the planning
baseline; [current support status](docs/ultra-support.md) supersedes its missing
model-detection entry. Hardware and extended-range gates remain open.
| Area | Delivered | Still missing |
| --- | --- | --- |
| Library | Terminal-independent config, framing, Basic acquisition, CSV; optional serial/mock features | Model/session API and the remaining device operations |
| 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 |
| Transport | Buffered mixed text/binary I/O, complete writes, bounded responses, serial/TCP adapters | Overall deadlines, abort, reconnect, typed replies and full recovery |
| 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 |
- [x] F01–F04: reusable library, injected I/O, bounded mock profiles and loopback tests.
- [x] H00: initial [hardware checklist](docs/hardware-validation.md),
[launcher](scripts/test-hardware.sh), and [validator](examples/validate-hardware.rs).
- [ ] H00 qualification: execute on real Basic and Ultra units and retain evidence.
Providing the validator has not completed hardware acceptance.
## Implementation rules and common completion gate
Keep the boundaries in [architecture](docs/architecture.md). Candidate new
modules such as `device`, `commands`, `session`, and `measurements` below are
proposed responsibilities, not existing APIs. Introduce them only with the
first concrete consumer; do not recreate a miscellaneous `structs` module.
Every feature slice must include:
- [ ] A typed library operation, validation before mutation, and an explicit
supported-model/firmware capability entry.
- [ ] Protocol parsing over bytes or `Read`/`Write`, with no hidden port/file
opening; settings use MHz/dBm/milliseconds, wire frequencies use Hz.
- [ ] Mock/transcript tests for success, rejection, boundaries, fragmentation,
timeouts, partial writes, disconnects and recovery where applicable.
- [ ] CLI/TUI exposure appropriate to the operation, including unsupported-state
feedback; diagnostics must not turn a rejected command into success.
- [ ] Configuration compatibility or a tested migration, Rustdoc, user guidance,
source links and hardware evidence status updated together.
- [ ] The [required verification commands](docs/security-and-ci.md#local-verification)
pass; run `cargo coverage` for Rust behavior and security gates for dependency
changes. Keep production coverage exclusions and the floor policy unchanged.
Hardware results must name the device/build, settings, RF setup and references,
expected result, observed result, tolerances and artifact paths. Mock results
must remain labeled synthetic. Publish or run shared Jenkins jobs only as a
separately authorized action.
## Delivery order
| Milestone | Work | Exit condition |
| --- | --- | --- |
| M0: reliable evidence | H01, P01, initial Q01/Q02 | Identity and command fixtures for each target; failed tests retain reports |
| M1: trustworthy acquisition | P02–P04, C01, initial I01/I02 | Basic and Ultra scans use verified profiles; timeout/cancel/recovery work |
| M2: analyzer parity | A01–A07, continuing I01/I02/Q01/Q02 | Analyzer controls and traces exposed and qualified per profile |
| M3: remaining device workflows | G01, D01–D04 | Generator, display, persistence, calibration and management classified/implemented |
| M4: supported release | I03, Q02, Q03 | Complete feature ledger and tested releases for explicitly supported combinations |
Start the small `list`/`inspect` CLI in M0 and extend it feature by feature.
Do not postpone all interface work until every analyzer control exists.
Hardware evidence collection can run alongside implementation; it is a gate
for support claims, not a reason to stop developing transcript tests.
## M0 — evidence and device identity
### H01 — harden the guided hardware validator
Depends on H00; extend incrementally with P01/P03/P04. Start in
`examples/validate-hardware.rs`, `scripts/test-hardware.sh`, and the checklist.
- [ ] Treat stdin EOF as cancellation. Do not interpret a closed input stream
as confirmation to start a scan.
- [ ] Retry enumeration for a bounded interval; require explicit selection if
no newly attached port is found. The current sole-port fallback can select an
unrelated serial device. Handle multiple devices and permissions explicitly.
- [ ] Query identity and `help` before any mutating acquisition. Confirm the
selected model/profile before scanning; current confirmation happens afterward.
- [ ] Create a unique session directory with exclusive creation and write the
initial report immediately. Append/checkpoint each stage so early I/O failures
preserve identity, completed work and the original failure.
- [ ] Record app revision/version, OS, model label, firmware, raw identity/help,
test settings including zero offset and frequency-axis policy, and timestamps.
Preserve bounded raw transcripts separately from sanitized terminal text.
- [ ] Give separate pass/fail/skipped/unverified results for command acceptance,
data framing, export, operator identity and front-panel recovery. A no-signal
scan cannot establish RF amplitude or frequency accuracy or prove zero readback.
- [ ] Run paired legacy/direct scans with identical settings before attributing
differences to the preparatory scan. Keep Basic high-path coverage as its own
case; currently Basic changes path and preparation in the same comparison.
- [ ] Add portable invocation instructions using `cargo run --example` on
Windows, an optional prebuilt validator, and concise `--help`/argument errors.
- [ ] Add optional reference-source and unplug/reconnect stages after P03/P04;
skip them explicitly when equipment is absent. Prompt once per physical wiring
change, automate all software checks, and retain a useful final summary.
Acceptance: test EOF, ambiguous ports, wrong model, second-scan failure, failed
report writes and negative operator confirmation without hardware. A real failed
run must still leave a report; a skipped check must never become a pass.
### P01 — inventory, identification and capabilities
Depends on F01–F04; H01 supplies evidence. Touch acquisition identification and
add a concrete `device` module plus versioned fixture metadata.
- [ ] Build a ledger per exact device/build: feature, command/arguments, units,
limits, query/readback form, mutation/persistence effects, source revision,
test fixture and support status.
- [ ] Inventory both official menu trees and command registration at the matching
firmware commit. Resolve the differing upstream repository references in local
docs against each captured firmware; do not treat a moving branch as evidence.
- [ ] Parse `version`/`info` after removing only known echo/prompt framing. Reject
empty and echo-only replies; retain unknown fields verbatim.
- [ ] Parse command availability from `help`, but distinguish advertised commands
from verified argument forms and successful readback.
- [ ] Represent identity confidence and unknown firmware explicitly. Permit a
recorded profile override without pretending it proves hardware identity.
- [ ] Gate optional diagnostic queries (`threads`, `usart_cfg`, etc.) on
availability; an absent debug command must not invalidate a supported scan.
- [ ] Keep inspection free of calibration, RF-output and persistent-write probes.
Acceptance: Basic, Ultra, unknown build, conflicting identity, echo-only and
missing-optional-command fixtures produce the expected profile or an explicit
unsupported/uncertain result before settings change.
## M1 — reliable Basic and Ultra acquisition
### P02 — separate model policy from raw decoding
Depends on P01. Main files: `src/protocol.rs`, `src/acquisition.rs`,
`src/config.rs`, `src/ui/state.rs`, `src/ui/mod.rs` and `src/mock/`.
- [ ] Move Basic physical-path/range selection out of generic frame-length and
sample-decoding rules. Keep delimiters, little-endian representation and raw
scale in the protocol module.
- [ ] Introduce a validated acquisition plan containing selected profile/path,
command sequence, sample count, axis policy and confirmed encoding offset.
- [ ] Preserve the current Basic overlap/boundary policy unless hardware evidence
justifies a documented change; test spans below, at and across each boundary.
- [ ] Add Ultra normal/extended/harmonic mode plans only for evidenced ranges.
Never send Basic `mode high input` on Ultra. Distinguish hardware revisions,
unlocked state and firmware limitations; the mock's ceiling is not a spec.
- [ ] Remove Basic-only UI/config ceilings when a resolved profile supplies the
range. Split structural config validation from post-identification validation
so detection can occur before rejecting a legitimate Ultra request.
- [ ] Verify `zero` acceptance/readback where available, bind the decoder to the
actual encoding, and expose uncertainty when a setting cannot be confirmed.
- [ ] Resolve frequency assignment using matching firmware and a reference
signal; preserve legacy inclusive behavior through an explicit migration.
- [ ] Qualify removal/replacement of the legacy `scan ... 290 101` preparation;
explain its undocumented mask and observed effects before changing defaults.
Acceptance: Basic path boundaries and Ultra boundaries reject invalid plans
without writes; valid Ultra plans above 960 MHz work on declared hardware.
Known-source measurements verify frequency/level conversion, including the
potential 46 dB offset mismatch. No synthetic result alone closes this task.
### P03 — typed replies, deadlines, abort and reconnect
Depends on P01; develop alongside P02. Extend `src/transport.rs` and
`src/connection.rs`; add small command-specific parsers as needed.
- [ ] Define typed replies/errors for implemented commands. Handle known firmware
rejection variants, optional echoes and readback mismatches; a prompt alone is
not acknowledgement of a setting change.
- [ ] Track an overall transaction deadline separately from idle read timeout.
Bound each blocking adapter call by remaining time; checking a clock only
between indefinitely blocking reads is insufficient.
- [ ] Add a cancellation token checked at bounded intervals, verified firmware
abort syntax, and a drain/resynchronization state before another command.
- [ ] Decode streaming/aborted frames with explicit complete/partial states.
Never search arbitrary sample bytes for a text prompt.
- [ ] Include command, stage, expected/received bytes and bounded diagnostics in
errors. Keep binary captures as bytes; escape terminal-control characters.
- [ ] Retry only operations known to be safe/idempotent. Reconnect must reidentify
the unit and reset stale buffers; never replay output/calibration mutations.
- [ ] Introduce a clock/adapter test seam only where needed to simulate elapsed
deadlines and blocking behavior deterministically.
Acceptance: fragmented prompts, slow trickle, total silence, late replies,
unplug mid-frame, aborted short frames and reconnect to another device all
terminate predictably without reporting partial data as a complete acquisition.
### P04 — session ownership and state restoration
Depends on P02/P03. A concrete session should own connection, identified profile,
operation state and restorable settings; the UI owns its worker lifetime.
- [ ] Snapshot queryable settings before mutation and track only successful
changes. Record settings whose previous values cannot be queried.
- [ ] Restore settings in a verified order on success, failure and cancellation;
preserve the primary failure together with every recovery failure.
- [ ] Replace detached worker exit with cancel-and-join under a bounded timeout.
Ensure `q`, Escape and process interrupts do not silently abandon acquisition.
- [ ] Expose recovery as events/status, not just a `Drop` side effect. Abort-mode
panics, unplugged devices and power loss cannot guarantee remote restoration.
- [ ] Prevent simultaneous commands from UI, scanning and diagnostics. Document
limits of OS port exclusivity rather than assuming universal locking.
- [ ] Do not automatically re-enable RF output when restoring a preset/session;
generator recovery needs a separate, explicit state policy in G01.
Acceptance: inject failure after each mutation and assert restoration attempts,
error preservation and worker termination. Verify final device state physically;
mark unavailable restoration as incomplete, never silently successful.
### C01 — typed settings and compatibility migration
Depends on P01/P02; accompanies every new control. Extend `src/config.rs`,
`config/default.toml`, persistence and configuration examples.
- [ ] Design explicit profile selection, analyzer settings and operation timeout
sections; distinguish requested settings from observed device state.
- [ ] Preserve six legacy selection keys and existing partial overrides, or
provide a tested migration with backup and actionable errors.
- [ ] Validate units, finite values, supported enum choices, mode combinations,
allocation limits and empty collections before commands/output creation.
- [ ] Keep model/wire invariants in code/profile evidence; changing a config
number must not authorize an unsupported physical range.
- [ ] Persist only intended user settings; do not silently save transient
generator enablement or hardware identity as permanent truth.
Acceptance: old configs still load, unknown keys fail, invalid combinations
cause no mutations, and failed persistence leaves the previous config usable.
## M2 — analyzer feature coverage
Each A-task depends on P01–P04/C01 and must extend I01/I02/Q01/Q02 in the same
feature slice. Firmware-only controls are conditional on the capability ledger.
### A01 — frequency, sweep and timing controls
- [ ] Add start/stop and center/span conversion with checked arithmetic; separate
frequency sweeps from CW/zero-span time traces so the axis cannot be mislabeled.
- [ ] Add supported point counts, repeat, sweep time, single/continuous operation
and actual frequency tables/readback rather than assuming requested settings.
- [ ] Inventory external reference, frequency offset, wideband/multiband and
segment behavior; implement supported forms with explicit metadata.
- [ ] Estimate progress from known phases without presenting byte count as a
reliable prediction of measurement duration.
Acceptance: boundary and overflow tests; compare requested/actual sweep and time
axis on hardware. Unsupported sweep forms fail before commands are sent.
### A02 — input paths, attenuation, gain and Ultra modes
- [ ] Model Basic low/high input separately from Ultra normal/extended/harmonic
modes; surface the physical connector and selected mode to the user.
- [ ] Add manual/automatic attenuation, available AGC/LNA stages and legal
combinations using per-profile ranges and mutual-exclusion rules.
- [ ] Inventory exposed IF and expert controls; retain automatic defaults until
an explicit user choice and verified syntax justify changing them.
- [ ] Capture overload/readback indicators where available; distinguish measured
overload status from a host heuristic.
Acceptance: illegal combinations are rejected, transitions/readback match the
panel, and low-level reference measurements show expected gain changes within
documented tolerances. Do not use damage-limit signals as test inputs.
### A03 — bandwidth, detector and trace processing
- [ ] Implement auto/manual RBW and available VBW with explicit unit conversion
at command boundaries; profile limits may differ.
- [ ] Add supported averaging, detector/calculation modes, min/max hold,
reference/subtraction traces and spur controls, including reset semantics.
- [ ] Record firmware processing separately from host processing. Changing span,
RBW or mode must invalidate incompatible accumulated/reference traces.
- [ ] Keep state and bounded trace buffers outside terminal rendering code.
Acceptance: deterministic sequences verify averaging/hold/reset; real-device
fixtures verify command forms, and RF tests record their bandwidth/settings.
### A04 — amplitude, display units and correction
- [ ] Add supported reference level, scale and display units; keep canonical
exported levels explicit and do not change values merely to fit a chart.
- [ ] Separate raw encoding offset, external loss/gain and calibration correction
in types and metadata; prevent correction from being applied twice.
- [ ] Define conversions requiring impedance or bandwidth only when that context
is available. Never label arbitrary dBm conversions as noise density.
- [ ] Validate correction tables for ordering, units, interpolation and range
policy; device-persistent calibration writes belong to D03.
Acceptance: numeric tests cover zero/negative/non-finite inputs and round trips;
reference measurements verify exported amplitude and visible correction state.
### A05 — trace APIs, streaming and export provenance
- [ ] Add typed ASCII scan, binary raw, stored trace and frequency-query decoders
only for advertised forms. Verify frequency/value lengths and record counts.
- [ ] Introduce trace metadata: device/build/profile, requested and actual range,
axis policy, offset, RF path, processing, timestamps and completion status.
- [x] Support repeated complete snapshots with bounded sixteen-sweep history,
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
or a documented versioned format; keep serialization independent of paths.
- [ ] Define atomic completion for trace plus metadata and a clearly labeled
partial-output policy. Disk-full/cancel must not leave a success-looking file.
Acceptance: transcript replay, multiple frames per read, truncated streaming
frames, full queues and disk failures preserve correct ordering and status.
### A06 — markers and measurement readouts
- [ ] Implement available marker enable/select/move, peak, tracking, reference
and delta controls with typed frequency/level results.
- [ ] Inventory model-specific readouts and measurement modes; implement each
exposed form or record a precise front-panel limitation.
- [ ] Distinguish firmware readouts from calculations over exported samples;
include algorithm and resolution when the host computes a result.
- [ ] Handle flat traces, tied peaks, nonuniform frequency tables and stale traces.
Acceptance: known trace fixtures and device-panel comparisons agree within
specified resolution/tolerance; unsupported readouts are never fabricated.
### A07 — trigger workflows
- [ ] Inventory trigger sources, level, polarity, position and auto/single modes
per build; add validated operations and readback where available.
- [ ] Represent armed, waiting, triggered, complete, cancelled and failed states.
Trigger waiting must have its own configurable deadline/status.
- [ ] Combine cancellation with P03 abort/resynchronization and P04 restoration.
Acceptance: no-trigger timeout, delayed trigger, cancel while armed and repeated
arming are covered synthetically and with a controlled hardware stimulus.
## M3 — generator and remaining device workflows
### G01 — RF generator
Depends on P01–P04/C01. Add a dedicated generator state/operation module rather
than reusing analyzer input-mode booleans.
- [ ] Inventory Basic output paths and Ultra output modes, frequency/level
bounds, step sizes, swept frequency/level and supported modulation variants.
- [ ] Add configure, explicitly enable, query and disable operations; opening
a connection, identifying a unit or loading a host profile must not emit RF.
- [ ] Validate modulation type/depth/rate and sweep parameters per profile before
switching modes. Record which limits cannot be remotely read back.
- [ ] Implement orderly shutdown/output-off attempts and report unknown state
after disconnect; never promise software can turn off an unreachable device.
- [ ] Extend CLI/TUI with visible output state and a direct stop control.
Acceptance: command-order/failure tests plus frequency/level/modulation checks
using suitable external equipment and a documented terminated/attenuated setup.
Analyzer-only or no-signal tests cannot qualify this task.
### D01 — display capture and remote panel
Depends on P01/P03; use A05 metadata conventions.
- [ ] Implement profile-specific capture dimensions/pixel format and exact byte
counts in a pure decoder; test truncated and oversized image responses.
- [ ] Export screenshots with firmware/settings provenance; keep image encoding
separate from serial I/O and add a dependency only if justified.
- [ ] Implement supported refresh, color/display options and touch coordinates
with bounds checks and known panel dimensions/orientation.
- [ ] Classify front-panel-only features explicitly. Touch navigation sequences
are firmware-specific automation, not a replacement for a typed command API.
Acceptance: capture fixtures decode correctly; hardware screenshots match the
panel; malformed captures cannot desynchronize the following command.
### D02 — presets, traces and storage
Depends on P04/C01/A05.
- [ ] Separate host profiles, instrument preset slots and removable storage in
types and UI. Inventory query/save/recall/delete support per firmware.
- [ ] Prevent accidental overwrite, path traversal and invalid names; use atomic
replacement for host files and explicit intent for device persistence.
- [ ] Read back settings after recall and refresh capabilities/trace provenance
if a preset changes mode. Recalled output state follows G01 policy.
- [ ] Implement SD trace/screenshot/file access only when a documented remote
interface exists; otherwise supply the verified manual transfer procedure.
Acceptance: full storage, missing media, interrupted writes, wrong profile and
recall failures preserve existing data and expose actual resulting state.
### D03 — calibration and self-test
Depends on P01–P04 and G01 when calibration output is involved.
- [ ] Inventory read-only calibration/status queries separately from self-test,
calibration-output enablement and persistent correction writes.
- [ ] Provide model-specific wiring/equipment instructions and explicit entry
into mutating procedures; do not probe service commands automatically.
- [ ] Capture preconditions, firmware result codes, before/after status and
operator observations; use staged progress with a defined abort procedure.
- [ ] Document recovery if interruption can leave calibration incomplete; never
claim rollback where firmware provides none.
Acceptance: parser/state tests plus operator-performed calibration/self-test
on each supported revision. Skipped equipment or failed firmware results remain
visible; a mock success never constitutes calibration evidence.
### D04 — device information and maintenance
Depends on P01/P03/P04.
- [ ] Add typed supported battery, device ID, build, clock/RTC and diagnostic
queries with unknown-field preservation and bounded output.
- [ ] Distinguish USB CDC settings from internal USART controls; implement only
verified forms and explain changes that can break the active connection.
- [ ] Add explicit reset/reconnect lifecycle handling and fresh identification.
- [ ] Inventory bootloader/update capabilities; where remote updating is not
supported, provide an exact manual workflow and classify the limitation.
If implemented, verify target image/device matching and recovery prerequisites.
Acceptance: restart, re-enumeration, changed port names and incompatible firmware
are handled without silently reusing an old profile or repeating mutations.
## M4 — interfaces, tests and release qualification
### I01 — scriptable command interface
Start with P01 inspection; extend alongside each feature family.
- [ ] Separate CLI parsing from the small startup entry point; keep ordinary TUI
startup compatible. Provide real `--help`/`--version` that never initialize a
terminal, enumerate/open a port or start an RF operation.
- [ ] Add discover/inspect/acquire first, then typed analyzer, generator, capture
and preset subcommands as their library APIs arrive.
- [ ] Define explicit model/port selection, machine-readable output, stable exit
categories and stdout/stderr separation; noninteractive mode must never prompt.
- [ ] Return failures for acquisition/export/recovery errors and propagate
cancellation/interrupt status. Validate config before opening output.
Acceptance: subprocess tests cover invalid arguments, no terminal, missing port,
unknown profile, timeout, cancellation and successful machine-readable output.
### I02 — capability-aware terminal UI
Depends incrementally on P01/P02 and each exposed feature.
- [ ] Display model/build/connection state and derive field limits/choices from
capabilities. Explain unavailable features rather than offering illegal values.
- [x] Add rescan, return-to-settings and a repeated-snapshot live plot without
restarting the process.
- [ ] Add marker controls and appropriate analyzer/generator/preset screens.
- [ ] Keep worker events/state updates outside rendering; add cancel, recovery,
trigger-wait and reconnect states without blocking the event loop.
- [ ] Label MHz/dBm/time axes, selected path, corrections, output state and dropped
frames. Keep rendering bounded on small terminals and long acquisitions.
Acceptance: in-memory rendering/event tests plus keyboard testing on real
terminals; every implemented end-user feature has a documented access path.
### I03 — public library and compatibility policy
Depends on stable P02–P04 interfaces, then evolves with feature slices.
- [ ] Expose session/profile/trace/error types with Rustdoc for units, invariants,
side effects, cancellation and restoration guarantees.
- [ ] Keep native serial and TUI optional; prove core-only downstream builds and
caller-provided streams remain usable.
- [ ] Document breaking changes and migration for config, exported metadata and
library calls. Add small downstream examples for Basic and Ultra inspection
and acquisition rather than speculative framework abstractions.
Acceptance: MSRV and feature matrix pass; examples build independently and public
APIs do not leak terminal types into device/protocol layers.
### Q01 — feature contracts, fixtures and fault coverage
Continuous task accompanying each feature.
- [ ] Add stateful mock behavior only for implemented commands; unsupported forms
continue to reject rather than return universal `ok` responses.
- [ ] Store approved bounded real transcripts with model/build/date/settings,
source provenance and byte-exact binary fixtures; redact identifying details
without altering protocol behavior.
- [ ] Replay identical feature contracts against mocks, captured transcripts and
explicitly enabled hardware sessions. Label their evidence levels separately.
- [ ] Add delayed responses, interrupted/partial writes, buffer limits, disconnect
at each mutation, rejected settings and recovery failures.
- [ ] Use property/exhaustive boundary tests for pure codecs where valuable;
never exclude production code to improve the reported coverage percentage.
Acceptance: each capability-ledger row links to a relevant test, and simulation
tests assert semantic outcomes as well as the actual command sequence.
### Q02 — hardware, host and distribution matrix
Depends on H01 and the feature being qualified.
- [ ] Maintain rows for exact Basic/Ultra revision + firmware + host OS + transport
+ build/artifact version, with pass/fail/skipped/unverified per feature group.
- [ ] Execute no-signal checks first; add calibrated/reference measurements for
frequency, amplitude, processing, triggers and generator as equipment permits.
- [ ] Measure tolerances from the chosen instrument specification and reference
uncertainty before running tests; do not retrofit thresholds to observed data.
- [ ] Test permissions, multiple devices, sleep/wake, USB unplug, reconnect and
extended acquisition memory/runtime behavior on declared platforms.
- [ ] Verify packaged binaries as well as source builds; reconcile supported
targets with `rust-release.toml` and [release guidance](docs/releases.md).
- [ ] Investigate the Jenkinsfile's documented FreeBSD release-startup SIGILL;
obtain a reproducible trace/build comparison before declaring that runtime
supported or making its diagnostic smoke stage a required gate.
- [ ] Keep local verification, physical-device runs, Jenkins execution and
publication evidence separate. Do not infer runtime support from compilation.
Acceptance: every claimed support combination has retained results and no
unexplained critical failure; unavailable hardware/platforms remain unverified.
### Q03 — final feature audit and support declaration
Depends on all baseline tasks for the declared profiles.
- [ ] Reconcile every P01 command/menu entry with implementation, interface,
regression tests, hardware evidence and any remote-control limitation.
- [ ] Resolve unclassified entries and stale compatibility/README claims.
Maintain separate Basic and Ultra support tables, including firmware ranges.
- [ ] Record residual limitations with consequences and evidence needed to
remove them; do not close tasks using vague future-work notes.
- [ ] Produce a release acceptance record linking artifacts and measurements,
migration notes and known issues. Publishing is a separate requested action.
Acceptance: no open remote-capable feature in the declared completeness scope;
any front-panel/upstream limitation is explicit in the public support statement.
## Optional stretch goals — choose individually
These add host-side capabilities beyond device feature parity. None is selected
or required for M0–M4. Size is relative implementation effort, not a delivery
estimate: M = a contained feature with several components; L = multiple feature
slices; XL = an additional subsystem. Pick by ID, for example `S01, S03, S06`.
| Pick | ID | Feature | Depends on | Size |
| --- | --- | --- | --- | --- |
| [ ] | S01 | Waterfall, history and offline replay | A05, I02 | L |
| [ ] | S02 | Scheduled unattended measurement sessions | P03/P04, A05, I01 | L |
| [ ] | S03 | Spectrum masks, alarms and change detection | A04/A05/A06 | M |
| [ ] | S04 | Occupancy and channel-power analysis | A01/A03/A04/A05 | L |
| [ ] | S05 | Wide-span segmented survey planner | P02/P04, A01/A02/A05 | L |
| [ ] | S06 | Measurement comparison and report bundles | A04/A05, D01 | M |
| [ ] | S07 | Local web dashboard and remote-control service | P04, I01/I03 | XL |
| [ ] | S08 | Multiple instruments and comparison sessions | P04, A05, I03 | XL |
| [ ] | S09 | Generator/analyzer characterization recipes | G01, A04/A05, P04 | XL |
| [ ] | S10 | Python analysis bindings | I03, A05 | L |
| [ ] | S11 | Guided overload and measurement-quality assistant | A02–A05, Q02 | L |
| [ ] | S12 | Additional export formats and integrations | A05, I01 | M |
### S01 — waterfall, history and offline replay
- [ ] Define a versioned recording containing timestamped traces and immutable
settings snapshots; use a bounded ring buffer and configurable disk retention.
- [ ] Render waterfall/time-history with pause, zoom and color scale; replay
recordings through the same view without opening a device.
- [ ] Test missing frames, changing axes, bounded memory, truncated recordings
and replay speed. Acceptance: a recorded session reproduces its trace order,
timing and settings; gaps remain visible rather than interpolated silently.
### S02 — scheduled unattended sessions
- [ ] Define recipes with profile, span, interval, duration, output retention,
retry limits and collision policy; use monotonic time for intervals.
- [ ] Run one owner per connection, checkpoint progress, detect disk exhaustion,
and recover only safe analyzer operations after reconnect.
- [ ] Integrate through the headless CLI before adding a scheduler UI. Test clock
jumps, missed intervals and process restart. Acceptance: bounded, resumable
sessions report missed measurements and do not reactivate RF output.
### S03 — spectrum masks and alerts
- [ ] Represent frequency-dependent limits with units, interpolation, hysteresis,
debounce and an explicit response to missing/out-of-range samples.
- [ ] Compare compatible traces against masks or saved baselines and retain the
triggering trace plus settings as evidence.
- [ ] Start with local events/files; outbound notifications require a selected
integration. Acceptance: synthetic edge cases verify no alert chatter, while
dropped/incompatible data creates uncertainty rather than a false pass.
### S04 — occupancy and channel-power analysis
- [ ] Define channel plans, level thresholds, observation duration and denominators
that account for scan gaps and unequal dwell time.
- [ ] Implement linear-power integration only with defensible bandwidth/sample
assumptions; report RBW, detector and uncertainty with every result.
- [ ] Test analytic synthetic spectra and controlled signals. Acceptance: label
sweep-based estimates explicitly; do not claim simultaneous real-time capture,
demodulation or IQ information that the source trace does not contain.
### S05 — segmented surveys
- [ ] Plan overlapping segments constrained by model/path/RBW/point limits;
estimate duration and show any required physical connector change.
- [ ] Preserve each segment's settings and timing; define overlap/deduplication
and level-discontinuity handling before constructing a combined trace.
- [ ] Test cancellation/resume and segment-boundary peaks. Acceptance: no missing
frequencies or hidden cross-path correction; never assume software can switch
a Basic cable between physical connectors.
### S06 — comparison and reproducible reports
- [ ] Compare recordings only after checking axes, RF path, correction and
bandwidth compatibility; make interpolation explicit and retain originals.
- [ ] Generate a portable HTML report first: plots, settings, identity, reference
setup, uncertainty, pass/fail criteria and links to original trace data.
- [ ] Add deterministic fixtures for differences and missing metadata.
Acceptance: another user can recompute the comparison from the exported bundle.
### S07 — local web dashboard and control service
- [ ] Wrap the typed session API with one device owner, bounded requests and
streamed telemetry; begin bound to localhost with view-only operation.
- [ ] Add explicit control ownership, authentication for network exposure and
operation authorization; never expose arbitrary shell/serial command execution.
- [ ] Provide cancellation and disconnect behavior matching the native client.
Acceptance: concurrent browsers cannot interleave commands, exhaust queues or
leave output state misrepresented. Deployment is a separate scope decision.
### S08 — multiple instruments
- [ ] Maintain independent sessions/capabilities and stable device selection;
record host/device timestamps and measured scheduling skew.
- [ ] Coordinate start/stop and comparison while isolating a failed unit; model
hardware synchronization only where an actual supported interface exists.
- [ ] Test two mocks with different timing plus paired hardware.
Acceptance: do not label host-scheduled USB scans phase-coherent or simultaneous.
### S09 — characterization recipes
- [ ] Define typed generator/analyzer steps, expected wiring, settling, source
limits and a dry-run plan; require explicit output enablement at execution.
- [ ] Capture scalar gain/loss versus frequency with fixture/reference corrections
and preserve raw measurements. Do not label scalar data vector S-parameters.
- [ ] Add stop/recovery for failure on either instrument and operator checkpoints
for cabling. Acceptance: reference fixtures reproduce known scalar behavior
within stated uncertainty; disconnected output state is reported as unknown.
### S10 — Python analysis bindings
- [ ] Select a concrete use case first; compare invoking the stable CLI with a
native binding before adding packaging and interpreter dependencies.
- [ ] Expose profiles, traces, metadata and structured exceptions; document
ownership/cancellation if direct device access is included.
- [ ] Test wheels/imports on chosen platforms and version the binding contract.
Acceptance: notebooks can inspect/replay/analyze traces without hidden device
access and without requiring terminal dependencies.
### S11 — measurement-quality guidance
- [ ] Detect suspicious overload/image patterns using documented heuristics and
explain confidence; never equate a heuristic with calibrated diagnosis.
- [ ] Offer guided attenuation/span/RBW comparison steps with operator approval
for physical changes, keeping original measurements and settings.
- [ ] Validate suggestions against reference setups and known false positives.
Acceptance: advice is tied to recorded evidence and cannot silently alter
calibration, RF output or user-selected pass/fail criteria.
### S12 — additional exports and integrations
- [ ] Choose actual consumers and formats before adding dependencies: versioned
JSON/JSONL, analysis-tool imports, compressed archives or selected databases.
- [ ] Serialize the common A05 trace model with units, identity, corrections and
completion status; stream large datasets and document precision loss.
- [ ] Add round-trip/schema compatibility tests and interrupted-write recovery.
Acceptance: data retains provenance across formats; external publication or
account writes require a separately selected integration and destination.
## Suggested first implementation slice
Choose H01 + P01 first: identify before mutation, preserve failure reports,
capture `help`, and create the per-firmware capability ledger. Then implement
one end-to-end M1 slice: verified Basic/Ultra profile, one-shot acquisition,
bounded cancellation/recovery, minimal inspect/acquire CLI and its hardware test.
After that, prioritize analyzer tasks or select stretch goals by ID; selecting a
stretch goal brings its listed prerequisites into scope but does not select the
other stretch goals.

408
tests/mock_device.rs Normal file
View File

@ -0,0 +1,408 @@
//! Production acquisition exercised against stateful, synthetic instruments.
use std::{
io::{self, Read, Write},
net::TcpListener,
time::Duration,
};
use tiny_wb::{
acquisition::acquire,
config::{Backend, Config, FrequencyAxis},
connection::open_connection,
mock::{serve_connection, MockConfig, MockFault, MockModel, MockStream},
protocol::ScanRequest,
transport::Shell,
};
fn settings() -> Config {
let mut config = Config::default();
config.serial.command_delay_ms = 0;
config.serial.settle_delay_ms = 0;
config.serial.scan_delay_ms = 0;
config.scan.frequency_axis = FrequencyAxis::Firmware;
config
}
fn request() -> ScanRequest {
ScanRequest {
start_hz: 240_000_000,
stop_hz: 360_000_000,
points: 4,
repeat: 2,
}
}
fn drain(device: &mut MockStream) -> Vec<u8> {
let mut response = Vec::new();
let mut bytes = [0; 4096];
while device.pending_bytes() > 0 {
let count = device.read(&mut bytes).unwrap();
response.extend_from_slice(&bytes[..count]);
}
response
}
fn command(device: &mut MockStream, command: &str) -> String {
device
.write_all(format!("{command}\r\n").as_bytes())
.unwrap();
String::from_utf8_lossy(&drain(device)).into_owned()
}
#[test]
fn acquisition_survives_bytewise_io_and_restores_sweeping() {
for echo in [false, true] {
for legacy in [false, true] {
let mut device = MockStream::new(MockConfig {
echo,
read_chunk_bytes: 1,
write_chunk_bytes: 1,
..MockConfig::default()
})
.unwrap();
let mut config = settings();
config.scan.legacy_pre_scan = legacy;
let samples = acquire(
&mut Shell::new(&mut device, 65536),
&request(),
&config.scan,
&config.serial,
|_| {},
)
.unwrap();
assert_eq!(samples.len(), 4);
assert_eq!(samples[2].level_dbm, -32.0);
assert_eq!(samples[0].level_dbm, -96.0);
assert!(!device.state().paused);
assert_eq!(device.state().repeat, 2);
assert_eq!(device.state().commands.back().unwrap(), "resume");
}
}
}
#[test]
fn faults_fail_acquisition_and_attempt_recovery() {
for fault in [
MockFault::Reject,
MockFault::Timeout,
MockFault::Disconnect,
MockFault::MissingPrompt,
MockFault::TruncatedFrame,
MockFault::BadAlignment,
] {
let mut device = MockStream::new(MockConfig {
fault,
..MockConfig::default()
})
.unwrap();
let config = settings();
let result = acquire(
&mut Shell::new(&mut device, 65536),
&request(),
&config.scan,
&config.serial,
|_| {},
);
assert!(result.is_err(), "{fault:?}");
if fault != MockFault::Disconnect {
assert!(!device.state().paused, "{fault:?}");
let result = acquire(
&mut Shell::new(&mut device, 65536),
&request(),
&config.scan,
&config.serial,
|_| {},
);
assert!(result.is_ok(), "one-shot {fault:?}: {result:?}");
} else {
assert!(!device.is_connected());
assert_eq!(device.read(&mut [0]).unwrap(), 0);
assert_eq!(
device.write(b"resume").unwrap_err().kind(),
io::ErrorKind::BrokenPipe
);
}
}
}
#[test]
fn rejected_pause_is_not_silent_success() {
let mut device = MockStream::new(MockConfig {
fault: MockFault::Reject,
fault_command: "pause".into(),
..MockConfig::default()
})
.unwrap();
let config = settings();
let error = acquire(
&mut Shell::new(&mut device, 65536),
&request(),
&config.scan,
&config.serial,
|_| {},
)
.unwrap_err();
assert!(error.to_string().contains("reject"), "{error}");
assert!(!device.state().paused);
}
#[test]
fn acquisition_detects_ultra_and_uses_native_offset_without_high_mode() {
let mut device = MockStream::new(MockConfig {
model: MockModel::Ultra,
..MockConfig::default()
})
.unwrap();
let config = settings();
let samples = acquire(
&mut Shell::new(&mut device, 65536),
&request(),
&config.scan,
&config.serial,
|_| {},
)
.unwrap();
assert_eq!(samples.len(), request().points);
assert_eq!(device.state().zero_offset, 174);
assert_eq!(device.state().input, "input");
assert!(device
.state()
.commands
.iter()
.any(|command| command == "mode low input"));
assert!(!device
.state()
.commands
.iter()
.any(|command| command == "mode high input"));
}
#[test]
fn ultra_profile_and_explicit_command_subset() {
let mut device = MockStream::new(MockConfig {
model: MockModel::Ultra,
echo: false,
..MockConfig::default()
})
.unwrap();
drain(&mut device);
assert_eq!(device.state().zero_offset, 174);
assert!(command(&mut device, "version").contains("tinySA4_v"));
assert!(command(&mut device, "help").contains("lna ultra"));
for cmd in [
"mode input",
"mode low input",
"lna on",
"ultra on",
"sweep start 1000000000",
"sweep stop 2000000000",
] {
assert_eq!(command(&mut device, cmd), "ch>");
}
assert!(device.state().lna && device.state().ultra);
device
.write_all(b"scanraw 1000000000 2000000000 2\r")
.unwrap();
let frame = drain(&mut device);
assert_eq!(frame[0], b'{');
assert_eq!(frame[1], b'x');
assert_eq!(frame.len(), 13);
for cmd in ["lna off", "ultra off"] {
command(&mut device, cmd);
}
assert!(!device.state().lna && !device.state().ultra);
for cmd in [
"mode high input",
"lna auto",
"reset",
"scanraw 0 6000000001 2",
] {
assert!(command(&mut device, cmd).contains("error:"));
}
}
#[test]
fn invalid_commands_do_not_mutate_measurement_state() {
let mut device = MockStream::new(MockConfig::default()).unwrap();
drain(&mut device);
for cmd in [
"repeat 0",
"repeat xyz",
"zero 2048",
"zero xyz",
"sweep start -1",
"sweep stop 960000001",
"scanraw 10 1 2",
"scanraw 0 350000000 2",
"scanraw 0 10 1",
"scanraw x 10 2",
"scanraw 0 10 10002",
"lna on",
] {
assert!(command(&mut device, cmd).contains("error:"), "{cmd}");
}
assert_eq!(device.state().repeat, 1);
assert_eq!(device.state().zero_offset, 128);
assert_eq!(device.state().start_hz, 240_000_000);
assert_eq!(device.state().stop_hz, 960_000_000);
command(&mut device, "mode high input");
assert!(command(&mut device, "scanraw 0 300000000 2").contains("error:"));
}
#[test]
fn framing_limits_and_history_are_bounded() {
let mut device = MockStream::new(MockConfig {
command_limit_bytes: 16,
echo: false,
..MockConfig::default()
})
.unwrap();
assert_eq!(device.read(&mut []).unwrap(), 0);
assert_eq!(device.write(&[]).unwrap(), 0);
drain(&mut device);
assert_eq!(
device.read(&mut [0]).unwrap_err().kind(),
io::ErrorKind::TimedOut
);
assert!(command(&mut device, &"x".repeat(17)).contains("too long"));
device.write_all(b"\xff\r").unwrap();
assert!(String::from_utf8(drain(&mut device))
.unwrap()
.contains("ASCII"));
for _ in 0..1030 {
command(&mut device, "pause");
}
assert_eq!(device.state().commands.len(), 1024);
assert_eq!(command(&mut device, "resume"), "ch>");
let error = loop {
if let Err(error) = device.write_all(b"help\r") {
break error;
}
};
assert_eq!(error.kind(), io::ErrorKind::OutOfMemory);
}
#[test]
fn mock_templates_and_invalid_configuration() {
Config::from_toml(include_str!("../config/mock-client.toml")).unwrap();
for source in [
include_str!("../config/mock-basic.toml"),
include_str!("../config/mock-ultra.toml"),
] {
toml::from_str::<MockConfig>(source)
.unwrap()
.validate()
.unwrap();
}
for source in [
"read_chunk_bytes=0",
"write_chunk_bytes=0",
"command_limit_bytes=1",
"max_points=1",
"ultra_max_hz=1",
"floor_dbm=nan",
"peak_dbm=-100.0",
"peak_width_hz=0",
"fault_command='BAD'",
"fault='bad_alignment'\nfault_command='pause'",
] {
assert!(
MockStream::new(toml::from_str(source).unwrap()).is_err(),
"{source}"
);
}
assert!(toml::from_str::<MockConfig>("unknown=1").is_err());
}
#[test]
fn tcp_backend_runs_real_acquisition_and_closes_cleanly() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let mut config = settings();
config.connection.backend = Backend::Tcp;
config.connection.tcp_address = listener.local_addr().unwrap().to_string();
let server = std::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()
});
{
let mut shell = Shell::new(open_connection(&config).unwrap(), 65536);
let samples =
acquire(&mut shell, &request(), &config.scan, &config.serial, |_| {}).unwrap();
assert_eq!(samples.len(), 4);
assert_eq!(samples[2].level_dbm, -32.0);
}
assert!(!server.join().unwrap().paused);
}
#[test]
fn stream_server_handles_interrupts_disconnects_and_io_errors() {
struct Duplex {
input: std::io::Cursor<Vec<u8>>,
output: Vec<u8>,
interrupt: bool,
fail_write: bool,
fail_read: bool,
}
impl Read for Duplex {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
if std::mem::take(&mut self.interrupt) {
return Err(io::ErrorKind::Interrupted.into());
}
if self.fail_read {
return Err(io::ErrorKind::ConnectionReset.into());
}
self.input.read(bytes)
}
}
impl Write for Duplex {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if self.fail_write {
return Err(io::ErrorKind::BrokenPipe.into());
}
self.output.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let new_stream = || Duplex {
input: std::io::Cursor::new(b"pause\rresume\r".to_vec()),
output: Vec::new(),
interrupt: true,
fail_write: false,
fail_read: false,
};
let mut stream = new_stream();
let state = serve_connection(&mut stream, MockConfig::default()).unwrap();
assert!(!state.paused);
assert!(stream.output.starts_with(b"ch>"));
let state = serve_connection(
new_stream(),
MockConfig {
fault: MockFault::Disconnect,
fault_command: "pause".into(),
..MockConfig::default()
},
)
.unwrap();
assert_eq!(state.commands.len(), 1);
let mut stream = new_stream();
stream.fail_write = true;
assert_eq!(
serve_connection(stream, MockConfig::default())
.unwrap_err()
.kind(),
io::ErrorKind::BrokenPipe
);
let mut stream = new_stream();
stream.fail_read = true;
assert_eq!(
serve_connection(stream, MockConfig::default())
.unwrap_err()
.kind(),
io::ErrorKind::ConnectionReset
);
}

48
tests/startup.rs Normal file
View File

@ -0,0 +1,48 @@
//! Verify configuration errors are reported before terminal/device initialization.
use std::{fs, process::Command};
#[test]
fn invalid_override_exits_without_entering_the_terminal() {
let directory = std::env::temp_dir().join(format!("tiny-wb-startup-{}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
let path = directory.join("custom.toml");
fs::write(&path, "points = 1").unwrap();
let result = Command::new(env!("CARGO_BIN_EXE_tiny-wb"))
.current_dir(&directory)
.env("TINY_WB_CONFIG", &path)
.output()
.unwrap();
assert!(!result.status.success());
let error = String::from_utf8_lossy(&result.stderr);
assert!(error.contains("custom.toml"));
assert!(error.contains("points must be within"));
assert!(!result.stdout.windows(2).any(|bytes| bytes == b"\x1b["));
assert_eq!(fs::read_dir(&directory).unwrap().count(), 1);
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();
}