ci: document project and harden Rust checks
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-10-04 17:17:56 +02:00
parent 960c3d6c59
commit 595aaf7b0c
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
20 changed files with 3888 additions and 80 deletions

View File

@ -1,2 +1,5 @@
[build] [build]
rustflags = ["-Clink-arg=-fuse-ld=lld"] rustflags = ["-Clink-arg=-fuse-ld=lld"]
[resolver]
incompatible-rust-versions = "fallback"

4
.gitignore vendored
View File

@ -4,10 +4,6 @@
debug/ debug/
target/ 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 # These are backup files generated by rustfmt
**/*.rs.bk **/*.rs.bk

2360
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,26 +2,24 @@
name = "tiny-wb" name = "tiny-wb"
version = "0.1.1" version = "0.1.1"
edition = "2021" edition = "2021"
rust-version = "1.88.0"
license = "MIT"
[dependencies] [dependencies]
chrono = "0.4.38" chrono = "0.4.38"
clap = { version = "4.5.17", features = ["derive"] }
color-eyre = "0.6.3" color-eyre = "0.6.3"
flexi_logger = "0.29.0" flexi_logger = "0.29.0"
# human-panic = "2.0.1" # human-panic = "2.0.1"
log = { version = "0.4.22", features = ["release_max_level_error"] } log = { version = "0.4.22", features = ["release_max_level_error"] }
# log = { version = "0.4.22"} # log = { version = "0.4.22"}
memchr = "2.7.4" memchr = "2.7.4"
once_cell = "1.19.0"
packed_struct = "0.10.1" packed_struct = "0.10.1"
ratatui = "0.28.1" ratatui = "=0.30.2"
ratatui-splash-screen = "0.1.4"
serde = { version = "1.0.210", features = ["derive"] } serde = { version = "1.0.210", features = ["derive"] }
serialport = "4.5.0" serialport = "4.5.0"
strum = { version = "0.26.3", features = ["derive"] } strum = { version = "0.28.0", features = ["derive"] }
thiserror = "1.0.63" thiserror = "2.0.21"
toml = "0.8.19" toml = "0.8.19"
tui-textarea = "0.6.1"
[profile.release] [profile.release]
opt-level = "z" opt-level = "z"
@ -53,4 +51,4 @@ incremental = false
panic = "abort" panic = "abort"
[build-dependencies] [build-dependencies]
winresource = "0.1.17" winresource = "=0.1.17"

89
Jenkinsfile vendored
View File

@ -10,6 +10,13 @@ pipeline {
RUST_BACKTRACE = '1' RUST_BACKTRACE = '1'
// LTS-like compatibility floor verified by the dedicated MSRV stage.
MSRV = '1.88.0'
// Supply-chain tools are pinned for reproducible policy behavior.
CARGO_AUDIT_VERSION = '0.22.2'
CARGO_DENY_VERSION = '0.20.2'
// Keep CI build products separate. // Keep CI build products separate.
CARGO_TARGET_DIR = "${WORKSPACE}/target-ci" CARGO_TARGET_DIR = "${WORKSPACE}/target-ci"
@ -51,8 +58,25 @@ pipeline {
--component rustfmt \ --component rustfmt \
--component clippy --component clippy
rustup toolchain install "${MSRV}" \
--profile minimal
rustup default stable 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
# --------------------------------------------------------- # ---------------------------------------------------------
# LLD # LLD
# --------------------------------------------------------- # ---------------------------------------------------------
@ -91,6 +115,18 @@ pipeline {
echo "Clippy:" echo "Clippy:"
cargo clippy --version 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
echo "Compiler:" echo "Compiler:"
cc --version || true cc --version || true
@ -114,6 +150,45 @@ pipeline {
} }
} }
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') { stage('Format') {
steps { steps {
sh ''' sh '''
@ -137,6 +212,7 @@ pipeline {
echo "Checking tiny-wb..." echo "Checking tiny-wb..."
cargo check \ cargo check \
--locked \
--all-targets \ --all-targets \
--all-features --all-features
''' '''
@ -151,6 +227,7 @@ pipeline {
echo "Running tests..." echo "Running tests..."
cargo test \ cargo test \
--locked \
--all-targets \ --all-targets \
--all-features --all-features
''' '''
@ -165,8 +242,11 @@ pipeline {
echo "Running Clippy..." echo "Running Clippy..."
cargo clippy \ cargo clippy \
--locked \
--all-targets \ --all-targets \
--all-features --all-features \
-- \
-D warnings
''' '''
} }
} }
@ -179,6 +259,7 @@ pipeline {
echo "Building tiny-wb release..." echo "Building tiny-wb release..."
cargo build \ cargo build \
--locked \
--release \ --release \
--all-features --all-features
@ -259,7 +340,7 @@ pipeline {
conclusion: 'SUCCESS', conclusion: 'SUCCESS',
name: 'Rust CI', name: 'Rust CI',
summary: 'tiny-wb passed CI.', summary: 'tiny-wb passed CI.',
text: 'Formatting, compilation checks, tests, Clippy and the release build completed successfully. The release runtime smoke test is currently diagnostic only.', text: 'RustSec audit, dependency policy, MSRV, formatting, compilation checks, tests, Clippy and the release build completed successfully. The release runtime smoke test is currently diagnostic only.',
title: 'Build Successful' title: 'Build Successful'
) )
@ -271,7 +352,7 @@ pipeline {
conclusion: 'FAILURE', conclusion: 'FAILURE',
name: 'Rust CI', name: 'Rust CI',
summary: 'tiny-wb failed CI.', summary: 'tiny-wb failed CI.',
text: 'Formatting, compilation, tests, Clippy, or the release build failed. Check the Jenkins log.', text: 'RustSec audit, dependency policy, MSRV, formatting, compilation, tests, Clippy, or the release build failed. Check the Jenkins log.',
title: 'Build Failed' title: 'Build Failed'
) )
@ -290,4 +371,4 @@ pipeline {
echo '⚠️ tiny-wb CI is unstable.' echo '⚠️ tiny-wb CI is unstable.'
} }
} }
} }

116
README.md
View File

@ -1,43 +1,95 @@
# tiny-wb # tiny-wb
Simple tinySA to Workbench converter `tiny-wb` is an interactive terminal application that acquires a frequency
sweep from a tinySA over its USB serial console and exports the result as CSV.
It is written in Rust and uses Ratatui for the interface.
# First window The current implementation is primarily shaped around the original **tinySA
> Selection Basic** command set and its 0–960 MHz low/high input ranges. The tinySA Ultra
family uses much of the same console protocol, but model detection and the
Ultra frequency ranges are not implemented yet; see the compatibility notes
before connecting an Ultra or Ultra+.
Starts with the most likely com port selected (last used, then usual suspect, then port 0) ## Documentation
Enter selects it (in the validation sense)
Selects the first likely baudrate (same algo)
Enter selects it
Selects the validate text box
First selection should be enter, then with L/R U/D (or mouse?) you can change the params - [Documentation index](docs/README.md) — where to start and source policy
(P) to select a port (B) to select a baudrate (Enter) to be put on the <Next> selection - [Project architecture](docs/architecture.md) — components, state, data flow,
files, dependencies, and extension points
- [tinySA field guide](docs/tinysa-field-guide.md) — models, RF architecture,
specifications, safe operation, measurement practice, calibration, and
firmware
- [USB console and `scanraw` protocol](docs/usb-protocol.md) — framing,
commands, binary decoding, synchronization, and a worked example
- [tiny-wb compatibility and operations](docs/tiny-wb-operations.md) — current
behavior, setup, controls, files, troubleshooting, and known limitations
- [Security, dependency policy, and MSRV](docs/security-and-ci.md) — Rust 1.88
compatibility floor, locked builds, RustSec, licenses, and CI gates
- [Upstream source catalogue](docs/sources.md) — authoritative links and what
each source is used for
# Second window The documentation was checked against the official tinySA wiki and firmware
> Customisation source on 2026-10-04. Instrument firmware evolves, so `help`, `version`, and
`info` on the connected unit remain the final authority for its command set.
Tab/L/R for navigation, Enter to change a parameter ## Build and run
Starts with <Scan> selected and either (L/R/U/D) to be put on the fields
# Third window Install Rust 1.88.0 or newer, connect and power on the instrument, then run:
> Result
Show a progress bar, then show a nice message with a prompt to ask where to save, then exits ```console
cargo run --release
```
# References On Linux the USB CDC device is commonly `/dev/ttyACM0`; on Windows it appears
as a COM port. The user running `tiny-wb` must have permission to open it.
* First line is discardable as it contains only a repead of sent command The interface uses arrow keys or Vim-style `h`, `j`, `k`, `l`. Left/right
* Read needs to stop on "ch>" 99, 104, 62 selects a field, up/down changes its value, Enter advances, and `q` or Escape
* Need to send resume afterward quits. Scan frequencies shown in the UI are MHz. The selected settings are
* Doc: https://tinysa.org/wiki/pmwiki.php?n=Main.USBInterface stored in `config.toml`; scan results are written in the current directory as
* Working example: http://athome.kaashoek.com/tinySA/python/ `scan_YYYYMMDD HH_MM_SS.csv`.
* Firmwares: All firmware files are located in http://athome.kaashoek.com/tinySA/DFU/
* QT5 GUI:https://github.com/g4ixt/QtTinySA?tab=readme-ov-file ## Current scan flow
* TUI: Rattatui
* ProgressB: Indicatif At a high level, `tiny-wb`:
* Version: tinySA4: Ultra, tinySA_ Tiny
* Scan will start with 123 and end with 125 1. opens the selected serial port;
* https://groups.io/g/tinysa 2. identifies the instrument with `version` and `info`;
* https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c 3. configures repeat count, raw-value zero offset, input mode, and sweep;
* NANOVNA: https://github.com/ttrftech/NanoVNA?tab=readme-ov-file 4. requests a binary `scanraw` acquisition;
5. decodes each level sample into dBm and writes `frequency_MHz,dBm`;
6. resumes the instrument sweep and plots the acquired points.
For the exact command sequence and compatibility implications, read
[USB console and `scanraw` protocol](docs/usb-protocol.md) and
[tiny-wb compatibility and operations](docs/tiny-wb-operations.md).
## Safety
Do not connect an unknown RF source directly to a tinySA. Use external
attenuation for transmitters and a DC block where a DC component may be
present. The Ultra family has an absolute RF input limit of +6 dBm at 0 dB
internal attenuation; the Basic limit is +10 dBm. These are damage limits,
not recommended measurement levels. See the [safe-operation section](docs/tinysa-field-guide.md#safe-operation-read-before-connecting-a-signal).
## Development
The Jenkins pipeline checks formatting, compilation, tests, Clippy, and a
release build. Run the equivalent local checks with:
```console
cargo fmt --all -- --check
cargo audit --deny warnings
cargo deny check
cargo +1.88.0 check --locked --all-targets --all-features
cargo check --locked --all-targets --all-features
cargo test --locked --all-targets --all-features
cargo clippy --locked --all-targets --all-features -- -D warnings
```
The application is currently a binary crate rather than a reusable library.
Protocol work is concentrated in `src/scan.rs`; UI state and rendering are in
`src/ui.rs`, `src/ui_struct.rs`, and `src/structs.rs`.
## License
See [LICENSE](LICENSE).

View File

@ -14,7 +14,7 @@ fn main() -> io::Result<()> {
} }
let output = Command::new("git") let output = Command::new("git")
.args(&["rev-parse", "--short", "HEAD"]) .args(["rev-parse", "--short", "HEAD"])
.output() .output()
.unwrap(); .unwrap();
let git_hash = String::from_utf8(output.stdout).unwrap(); let git_hash = String::from_utf8(output.stdout).unwrap();

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 = []

44
docs/README.md Normal file
View File

@ -0,0 +1,44 @@
# 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.
## 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.

196
docs/architecture.md Normal file
View File

@ -0,0 +1,196 @@
# Project architecture
## Purpose and boundary
`tiny-wb` is a single-process desktop terminal application. Its job is narrow:
collect an amplitude-versus-frequency sweep from a tinySA through the USB
serial console, persist the sweep as CSV, and show the result in a terminal
chart.
It is not currently a general tinySA controller, live spectrum display,
firmware updater, calibration utility, or Rust protocol library. It changes a
small amount of temporary instrument state during acquisition and restores
continuous sweeping with `resume`; it does not restore every preceding device
setting.
## Runtime data flow
```text
keyboard
|
v
Ratatui event loop (AppInfo)
| selected port, baud, MHz range, points, repeat
v
ConnectionInfo (shared Arc<Mutex<...>> state)
|
+---- UI thread: render progress, device info, errors, chart
|
`---- scan worker thread
|
v
serialport / USB CDC
|
v
tinySA shell ---- text responses ending in "ch>"
|
`------------ scanraw binary frame
|
v
parser -> Vec<(MHz, dBm)>
|
+-> timestamped CSV
`-> final Ratatui chart
```
The UI remains responsive because scanning runs in a worker thread. Clones of
`ConnectionInfo` share progress, status, returned data, messages, file name,
and error state through `Arc<Mutex<_>>` values. The selected connection and
scan parameters themselves are copied into the worker.
## Source map
| File | Responsibility |
| --- | --- |
| `src/main.rs` | Start file logging and error reporting, initialize/restore the terminal, enumerate serial ports, and run the application. |
| `src/ui.rs` | Construct defaults, drive the event/render loop, transition screens, spawn the scan worker, plot results, and map errors to user messages. |
| `src/ui_struct.rs` | Define UI state, selectable fields, baud-rate and port lists, numeric bounds, colors, and navigation helpers. |
| `src/structs.rs` | Define configuration persistence, shared connection state, status values, and application/protocol error types. |
| `src/scan.rs` | Open the serial port, issue shell commands, find prompts, request `scanraw`, parse binary samples, convert levels, and write CSV. |
| `build.rs` | Embed the Git short hash and, on Windows, compile the application icon resource. |
| `Jenkinsfile` | Run formatting, checks, tests, Clippy, release build, and a non-fatal interactive-binary smoke diagnostic. |
## UI state machine
`AppState` advances in one direction during a normal run:
```text
InitialConfig -> FinalConfig -> Finished -> EndWindow -> exit
| | |
`---------------+-------------+-> Error -> exit
```
- `InitialConfig` selects a serial port and baud rate.
- `FinalConfig` selects start/stop MHz, sample count, and repeat count.
- Enter from `FinalConfig` writes `config.toml`, fills `ConnectionInfo`, and
spawns the worker.
- `Finished` is somewhat counter-intuitively the in-progress screen. It polls
shared status while the worker runs.
- `EndWindow` plots the collected samples and reports success.
- `Error` presents the mapped failure and exits on confirmation.
Defaults are 240–960 MHz, 10,001 points, one measurement per frequency, and
115,200 baud. The UI permits 0–960 MHz in 10 MHz steps, 101–1,000,001 points in
100-point steps, and repeat values from 1–1,000. A valid `config.toml` overrides
the defaults. Frequencies are converted from UI MHz to protocol Hz only when
`ConnectionInfo` is filled.
## Acquisition pipeline
`scan_with_progress` performs these operations:
1. Validate the requested range and choose Basic `low` or `high` input mode.
2. Open the selected port with a 3 s read timeout.
3. Drain stale input until the shell prompt is seen or reading times out.
4. Query `version`, `info`, `leveloffset`, `vbat`, `usart_cfg`, and `threads`.
5. Send `repeat N` and `zero 128`.
6. Query markers, pause the normal sweep, and set the input mode.
7. Set sweep start/stop, query the sweep, then run a 290-point textual `scan`.
8. Send `scanraw START STOP POINTS` without immediately consuming a text reply.
9. Read and parse its binary frame, update progress, and write CSV.
10. Send `resume`, set progress to 100%, and expose the samples to the UI.
Step 7's textual `scan ... 290 101` does not contribute samples to the final
CSV; its response is read and discarded. It therefore needs a documented
reason or removal during a future protocol cleanup.
## Protocol boundary
Text commands are terminated with carriage return (`\r`). `send_cmd` sleeps,
then reads until it finds the ASCII prompt `ch>`, and sleeps again. This is a
timing-assisted, prompt-delimited request/response protocol. The application
does not currently:
- parse command echo separately from command output;
- validate an explicit success status;
- retain bytes after a prompt found in the middle of a serial read;
- account for a prompt split across two read buffers;
- preserve partial results after a read timeout;
- negotiate capabilities from `version`, `info`, or `help`.
The `scanraw` body is different: it is a binary `{...}` frame made of
three-byte sample records. See [USB console and `scanraw` protocol](usb-protocol.md).
## Persistence and outputs
`config.toml` is stored in the process working directory and contains:
```toml
port = "/dev/ttyACM0"
baudrate = 115200
start_frequency = 240
stop_frequency = 960
points = 10001
repeat = 1
```
Each acquisition immediately creates a timestamped CSV in the working
directory. It has no header. Column one is the application-computed frequency
in MHz and column two is level in dBm. Logs are produced by `flexi_logger` in
the working directory with its default file naming policy.
## Important invariants and risks
- A scan needs at least two points because host interpolation divides by
`points - 1`; the UI minimum of 101 enforces this, but the parser itself does
not.
- `read_port_with_progress` estimates `3 * points + 6` bytes. Progress is only
an estimate because command echo and prompt bytes are also present.
- The parser finds the first `{`, requires each subsequent full triple to start
with `x`, and stops on a triple whose first byte is `}`. End-frame validation
is currently commented out, so a truncated frame can be accepted.
- The firmware emits sample bytes little-endian even though one wiki sentence
labels them “MSB LSB.” The upstream C implementation and the Rust parser both
use low byte followed by high byte.
- Firmware computes `scanraw`'s step as `(stop - start) / points`, while the
host labels samples using `(stop - start) / (points - 1)`. The final host CSV
therefore labels its last point at `stop`, but current firmware measures its
last point one step below `stop`. This should be resolved in code, ideally by
testing against the target firmware version.
- `zero 128` deliberately asks firmware to encode the level around a 128 dB
offset and the host subtracts 128. Without that command, the documented
default offset is 128 for Basic and 174 for Ultra.
- Input-mode selection encodes Basic-only assumptions. Ultra has no `high`
input command, and the UI cannot request its ranges above 960 MHz.
## Dependency roles
- `ratatui` and `crossterm` (through Ratatui) provide terminal rendering and
input.
- `serialport` enumerates and opens the device.
- `packed_struct` decodes the three-byte sample representation.
- `memchr` locates `{` and the `ch>` prompt.
- `serde` and `toml` persist settings.
- `chrono` names scan files.
- `flexi_logger`, `log`, `color-eyre`, and `thiserror` cover diagnostics and
error propagation.
- `strum` derives iteration/counting for menu enums.
The manifest intentionally contains only dependencies used by the current
binary. In particular, the parser uses `std::sync::OnceLock`; no external
`once_cell` dependency is needed.
## Recommended evolution path
The cleanest route to reliable multi-model support is to separate four layers:
1. a byte-accurate transport that preserves unread bytes and uses deadlines;
2. a shell codec for echo, response, prompt, and binary frames;
3. a capability/model layer derived from `version`/`info` plus explicit
firmware quirks;
4. the TUI and CSV application built on a reusable acquisition API.
Tests should cover prompt fragmentation, binary frames containing arbitrary
byte values, truncation, Basic versus Ultra offsets/modes, frequency labeling,
timeouts, and disconnects. Captured serial transcripts make good fixtures and
do not require hardware in CI.

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

@ -0,0 +1,135 @@
# 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.88.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. The project therefore treats 1.88.0 as the lowest supported clean
graph rather than adding advisory exceptions or local dependency patches.
`Cargo.toml` declares `rust-version = "1.88.0"`. CI installs that exact
toolchain and runs:
```console
cargo +1.88.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.
## 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.88.0 check --locked --all-targets --all-features
cargo check --locked --all-targets --all-features
cargo test --locked --all-targets --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.

84
docs/sources.md Normal file
View File

@ -0,0 +1,84 @@
# Upstream source catalogue
This catalogue records the authoritative references used to build the local
guide. It was last checked on **2026-10-04**. 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 `span / points`
`scanraw` step. Both are explained in [the protocol guide](usb-protocol.md).

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

@ -0,0 +1,243 @@
# 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+ below 350 MHz | Experimental, not declared supported | `mode low input` and `zero 128` are plausible, but the client neither detects nor tests the model. |
| tinySA Ultra/Ultra+ at or above 350 MHz | Not supported | The client sends Basic-only `mode high input`; Ultra has no such high input mode. |
| Ultra mode above the normal range | Not supported | UI stops at 960 MHz and never negotiates Ultra state/capabilities. |
| Generator control, live streaming, 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
```
The program does not currently expose meaningful command-line options; it
starts the interactive terminal immediately. Run it from the directory where
you want `config.toml`, logs, and scan CSV files to appear.
### 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. common candidates (`/dev/ttyACM0`, `COM3`, `COM5`, `/dev/ttyS16`);
3. the first enumerated port.
Baud choices range from 19,200 to 3,000,000; default is 115,200 unless a saved
value matches the built-in list.
### Scan screen
Fields and bounds are:
| Field | Unit | Default | Step | Bounds |
| --- | --- | ---: | ---: | ---: |
| Start frequency | MHz | 240 | 10 | 0–960 |
| Stop frequency | MHz | 960 | 10 | 10–960 |
| 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. Enter advances to the next screen. `q` or Escape exits.
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 is fixed to −128–0 dBm, so valid results outside that
range are clipped visually even though CSV data may contain them.
## 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). The file
is overwritten by the next run. A missing or invalid configuration falls back
to defaults; validate unexpected values before assuming they were loaded.
### CSV
The scanner writes `scan_YYYYMMDD HH_MM_SS.csv` in the working directory. It
has no header:
```csv
240,-92.4375
240.072,-91.96875
```
Column one is MHz and column two is dBm. The file is created before full frame
validation, so an error can leave a partial or empty CSV. Also note the
[known frequency-label mismatch](usb-protocol.md#frequency-assignment).
### Logs
`flexi_logger` writes diagnostic logs to a file in the working directory. 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. It also runs an auxiliary textual scan before
the raw scan. 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.
If acquisition fails after `pause`, error handling does not guarantee a final
`resume`; the front panel may remain paused. 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.
### “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 or fragmented prompt even when the instrument is healthy.
### 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.
- Be aware that the current reader can mistake binary bytes equal to `ch>` for
the shell prompt or miss a prompt split between OS reads.
### Trace is shifted in frequency
The current host labels `points` samples over `points - 1` intervals, while the
reviewed firmware measures using a `span / points` step. Verify with a known
carrier, record firmware version, and use the firmware formula when correcting
the exported axis offline.
### Levels are wrong by about 46 dB
That is the difference between Ultra's documented default raw offset (174) and
Basic's (128). tiny-wb sends `zero 128`; a 46 dB shift suggests the firmware
did not accept/apply that command or the reply was not validated. Stop treating
the result as calibrated data and capture `version`, `info`, and the `zero`
command response.
### 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.
## Current engineering backlog implied by the documentation
These are documentation-derived gaps, not changes made in this task:
1. Parse `version`/`info` into a model and capability structure.
2. Add Ultra/Ultra+ ranges and correct mode syntax, or explicitly reject them.
3. Replace prompt searches with a persistent mixed text/binary framing state
machine.
4. Resolve the `scanraw` frequency denominator against real firmware fixtures.
5. Remove or justify the preliminary `scan ... 290 101` request.
6. Validate exact record count and closing delimiter before accepting/writing a
completed CSV.
7. Restore changed instrument state on success, cancellation, and error.
8. Put model/firmware/settings and column names in output metadata.
9. Add protocol tests based on captured Basic and Ultra transcripts.

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

@ -0,0 +1,313 @@
# 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 currently chooses `mode low input` below 350 MHz and `mode high input`
above that, limits the UI to 960 MHz, and does not inspect the model. That is a
Basic-oriented policy. Ultra supports `mode [low] input`, has no Basic-style
high input, and needs capability-driven ranges. Until model support is added,
use [the compatibility matrix and cautions](tiny-wb-operations.md#compatibility-matrix).
For the wire format and exact command behavior, continue with
[USB console and `scanraw` protocol](usb-protocol.md).

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

@ -0,0 +1,272 @@
# 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/scan.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 it requests one buffered acquisition. The firmware
buffers in small blocks internally; “buffered” does not mean the entire sweep
is delivered in a single USB transfer.
## 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.
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 documented default conversion is:
```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.
Upstream firmware calculates the transmitted integer from the measured value
plus `config.ext_zero_level`; the `zero N` command changes that offset. tiny-wb
sends `zero 128` before every acquisition and always uses:
```text
dBm = raw_u16 / 32 - 128
```
That normalizes the wire representation to a Basic-style offset and can make
the conversion work on firmware honoring `zero`, including Ultra. A robust
client should still detect the model, verify the command response, and bind the
decoder offset to the value it successfully configured. If `zero 128` is
rejected or ignored, applying 128 to an Ultra default frame produces a 46 dB
error.
### 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 upstream `cmd_scanraw` implementation calculates:
```text
firmware_step = (stop - start) / points
frequency[i] = start + firmware_step * i for i = 0 .. points-1
```
The arithmetic includes floating/intermediate and integer-frequency details
that vary with the firmware's `freq_t`, but the denominator is visibly
`points`, not `points - 1` in the reviewed source. Therefore the last measured
point is one nominal step below stop.
tiny-wb currently labels output using:
```text
host_step = (stop - start) / (points - 1)
frequency[i] = start + host_step * i
```
This labels the endpoints inclusively and disagrees with the reviewed firmware.
The discrepancy grows linearly through a sweep to almost one firmware step at
the last point. Before changing it, capture a known narrow carrier with the
target firmware and retain the `version` string; firmware behavior may change.
## 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
leveloffset
vbat
usart_cfg
threads
repeat REPEAT
zero 128
marker
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 `scanraw` reader also searches raw incoming chunks for `ch>` while the
binary body is in flight. Because arbitrary sample bytes can coincidentally
contain those three bytes, that is a correctness risk. The finder also cannot
detect `ch>` split across two read calls. A framed binary state machine should
replace this behavior.
The `scan` outmask value `101` is outside the documented three-bit mask and its
returned data is discarded. It should not be copied into new clients without
first establishing why it is necessary.
## 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#important-invariants-and-risks) for
repository-specific parser risks and [tiny-wb operations](tiny-wb-operations.md)
for what users can safely expect today.

View File

@ -14,7 +14,6 @@ use structs::TinyError;
use ui_struct::AppInfo; use ui_struct::AppInfo;
use flexi_logger::{FileSpec, Logger, WriteMode}; use flexi_logger::{FileSpec, Logger, WriteMode};
use log;
fn main() -> Result<(), TinyError> { fn main() -> Result<(), TinyError> {
let _logger = Logger::try_with_str("info, my::critical::module=trace") let _logger = Logger::try_with_str("info, my::critical::module=trace")

View File

@ -125,6 +125,7 @@ pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(),
Ok(()) Ok(())
} }
/// Open the configured serial port and reflect failures in the shared status.
fn acquire_port(connection_info: &ConnectionInfo) -> Result<Box<dyn SerialPort>, TinyError> { fn acquire_port(connection_info: &ConnectionInfo) -> Result<Box<dyn SerialPort>, TinyError> {
let port = { let port = {
connection_info.update_message("Opening connection"); connection_info.update_message("Opening connection");
@ -149,13 +150,16 @@ fn mode_from(start: usize, stop: usize) -> Result<String, TinyError> {
start, stop start, stop
))); )));
} }
match (start, stop) { if start >= 350_000_000 && stop <= 960_000_000 {
(350_000_000..=960_000_000, 350_000_000..=960_000_000) => Ok("high".to_string()), Ok("high".to_string())
(0..350_000_000, 0..350_000_000) => Ok("low".to_string()), } else if stop < 350_000_000 {
(240_000_000..350_000_000, 350_000_000..=960_000_000) => Ok("high".to_string()), Ok("low".to_string())
_ => Err(TinyError::BadScanFrequencies( } else if (240_000_000..350_000_000).contains(&start) && stop <= 960_000_000 {
Ok("high".to_string())
} else {
Err(TinyError::BadScanFrequencies(
"Scan frequencies must either be in range (0MHz-240MHz) or (240MHz-960MHz)".to_owned(), "Scan frequencies must either be in range (0MHz-240MHz) or (240MHz-960MHz)".to_owned(),
)), ))
} }
} }
@ -303,7 +307,7 @@ pub fn parse_data(
log::info!("The end looks like :{:?}", &v[end_tmp - 10..end_tmp]); log::info!("The end looks like :{:?}", &v[end_tmp - 10..end_tmp]);
let mut end = end_tmp; let mut end = end_tmp;
let chunks_exact = data.chunks_exact(3); let (chunks, _remainder) = data.as_chunks::<3>();
// if chunks_exact.remainder().is_empty() { // if chunks_exact.remainder().is_empty() {
// return Err(TinyError::ParseEnd( // return Err(TinyError::ParseEnd(
// "The data received doesn't have a end char (empty)".to_owned(), // "The data received doesn't have a end char (empty)".to_owned(),
@ -316,9 +320,8 @@ pub fn parse_data(
// chunks_exact.remainder() // chunks_exact.remainder()
// ))); // )));
// } // }
for (i, slice) in chunks_exact.enumerate() { for (i, slice) in chunks.iter().enumerate() {
let s: &[u8; 3] = &[slice[0], slice[1], slice[2]]; let d = DataPoint::unpack(slice)?;
let d = DataPoint::unpack(s)?;
if d.align == b'}' { if d.align == b'}' {
// Found an end and the rest is garbage // Found an end and the rest is garbage
end = i * 3; end = i * 3;

View File

@ -7,9 +7,6 @@ use std::{
}; };
use flexi_logger::FlexiLoggerError; use flexi_logger::FlexiLoggerError;
use log;
use serde;
use thiserror;
use crate::ui_struct::AppInfo; use crate::ui_struct::AppInfo;
@ -102,6 +99,7 @@ pub enum TinyUIError {
} }
#[derive(serde::Serialize, serde::Deserialize, Debug)] #[derive(serde::Serialize, serde::Deserialize, Debug)]
/// Configuration persisted between tiny-wb sessions.
pub(crate) struct SavedConfig { pub(crate) struct SavedConfig {
/// The default com port /// The default com port
pub(crate) port: String, pub(crate) port: String,
@ -160,9 +158,11 @@ pub(crate) enum ConnectionStatus {
ConnectionFailure, ConnectionFailure,
/// The connection is closed and the connection was a succes /// The connection is closed and the connection was a succes
ClosedWithSuccess, ClosedWithSuccess,
/// A scan command was accepted and acquisition has started.
ScanStarted, ScanStarted,
} }
/// Frequency and amplitude pairs returned by a scan.
type ScanData = Vec<(f64, f64)>; type ScanData = Vec<(f64, f64)>;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]

View File

@ -3,7 +3,7 @@ use log::info;
use ratatui::{ use ratatui::{
crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
layout::{Constraint, Layout, Rect}, layout::{Constraint, Layout, Rect},
style::{Color, Modifier, Style, Stylize}, style::{Color, Modifier, Style},
symbols::Marker, symbols::Marker,
widgets::{Axis, Block, Chart, Dataset, GraphType, LineGauge, List, Paragraph, Wrap}, widgets::{Axis, Block, Chart, Dataset, GraphType, LineGauge, List, Paragraph, Wrap},
DefaultTerminal, Frame, DefaultTerminal, Frame,
@ -68,7 +68,7 @@ impl<'a> AppInfo<'a> {
) -> Result<(), color_eyre::eyre::Error> { ) -> Result<(), color_eyre::eyre::Error> {
self.init_config()?; self.init_config()?;
loop { loop {
terminal.draw(|v| self.draw(v).inspect_err(|e| panic!("{}", e)).unwrap())?; terminal.draw(|v| self.draw(v).unwrap_or_else(|e| panic!("{}", e)))?;
let timeout = Duration::from_millis(16); let timeout = Duration::from_millis(16);
if event::poll(timeout)? { if event::poll(timeout)? {
if let Event::Key(key) = event::read()? { if let Event::Key(key) = event::read()? {
@ -428,7 +428,9 @@ impl<'a> AppInfo<'a> {
.unwrap_or(&TinyUIError::NoErrorSpecified) .unwrap_or(&TinyUIError::NoErrorSpecified)
{ {
TinyUIError::MenuSelectionError => "An error occured while trying to select a menu item", 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::UninitializedItemList(i, _l, _ff) => {
return Ok(format!("The item {i} was left uninitialized"));
}
TinyUIError::KeyPress(_) => "An error occured while processing key events", TinyUIError::KeyPress(_) => "An error occured while processing key events",
TinyUIError::NoPortSelected => "No connection port was selected", TinyUIError::NoPortSelected => "No connection port was selected",
TinyUIError::NoConnectionInfoCreated => { TinyUIError::NoConnectionInfoCreated => {

View File

@ -50,6 +50,7 @@ pub(crate) struct AppInfo<'a> {
} }
#[derive(Debug)] #[derive(Debug)]
/// Numeric input state with bounded keyboard increments.
pub(crate) struct UIUsize { pub(crate) struct UIUsize {
/// Current value held by the usize /// Current value held by the usize
value: usize, value: usize,
@ -153,9 +154,10 @@ macro_rules! mleft {
}; };
} }
/// The selected item in the config /// The selected item in the config
#[derive(Debug, EnumCount, FromRepr, Clone, Copy)] #[derive(Debug, Default, EnumCount, FromRepr, Clone, Copy)]
pub(crate) enum SelectedConfig { pub(crate) enum SelectedConfig {
/// Selects the ports /// Selects the ports
#[default]
Port, Port,
/// Selects the baudrate /// Selects the baudrate
Baudrate, Baudrate,
@ -163,16 +165,11 @@ pub(crate) enum SelectedConfig {
// Proceed, // Proceed,
} }
impl Default for SelectedConfig {
fn default() -> Self {
Self::Port
}
}
/// The selected item in the final menu /// The selected item in the final menu
#[derive(Debug, EnumCount, FromRepr, Copy, Clone)] #[derive(Debug, Default, EnumCount, FromRepr, Copy, Clone)]
pub(crate) enum SelectedFinalConfig { pub(crate) enum SelectedFinalConfig {
/// Selects the start frequency /// Selects the start frequency
#[default]
StartFreq, StartFreq,
/// Selects the final frequency /// Selects the final frequency
FinalFreq, FinalFreq,
@ -184,12 +181,6 @@ pub(crate) enum SelectedFinalConfig {
// Proceed, // Proceed,
} }
impl Default for SelectedFinalConfig {
fn default() -> Self {
Self::StartFreq
}
}
/// The list of all baudrates selectables /// The list of all baudrates selectables
#[derive(Debug)] #[derive(Debug)]
pub(crate) struct BaudRateList { pub(crate) struct BaudRateList {