From b5da980b6f427a21fb2821a0dfb4cfb3f7917667 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 4 Oct 2026 22:31:05 +0200 Subject: [PATCH] refactor: wire configured acquisition into separated terminal UI --- Cargo.lock | 63 ---- Cargo.toml | 6 +- README.md | 15 +- docs/README.md | 6 + docs/architecture.md | 287 +++++++--------- docs/configuration.md | 11 + docs/testing.md | 1 + docs/tiny-wb-operations.md | 88 ++--- docs/usb-protocol.md | 39 ++- src/error.rs | 44 +++ src/lib.rs | 13 + src/main.rs | 54 +-- src/scan.rs | 494 +++++++++------------------ src/structs.rs | 324 ------------------ src/ui.rs | 674 ------------------------------------- src/ui/mod.rs | 373 ++++++++++++++++++++ src/ui/state.rs | 356 ++++++++++++++++++++ src/ui/view.rs | 386 +++++++++++++++++++++ src/ui_struct.rs | 406 ---------------------- tests/startup.rs | 23 ++ 20 files changed, 1597 insertions(+), 2066 deletions(-) create mode 100644 src/error.rs delete mode 100644 src/structs.rs delete mode 100644 src/ui.rs create mode 100644 src/ui/mod.rs create mode 100644 src/ui/state.rs create mode 100644 src/ui/view.rs delete mode 100644 src/ui_struct.rs create mode 100644 tests/startup.rs diff --git a/Cargo.lock b/Cargo.lock index b776432..d37ee78 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -119,18 +119,6 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -[[package]] -name = "bitvec" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -523,12 +511,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - [[package]] name = "futures-core" version = "0.3.34" @@ -1017,28 +999,6 @@ version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" -[[package]] -name = "packed_struct" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36b29691432cc9eff8b282278473b63df73bea49bc3ec5e67f31a3ae9c3ec190" -dependencies = [ - "bitvec", - "packed_struct_codegen", - "serde", -] - -[[package]] -name = "packed_struct_codegen" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd6706dfe50d53e0f6aa09e12c034c44faacd23e966ae5a209e8bdb8f179f98" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "palette" version = "0.7.7" @@ -1243,12 +1203,6 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" -[[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - [[package]] name = "rand" version = "0.8.8" @@ -1654,12 +1608,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - [[package]] name = "termina" version = "0.3.3" @@ -1814,8 +1762,6 @@ dependencies = [ "color-eyre", "flexi_logger", "log", - "memchr", - "packed_struct", "ratatui", "serde", "serialport", @@ -2349,12 +2295,3 @@ name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "wyz" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" -dependencies = [ - "tap", -] diff --git a/Cargo.toml b/Cargo.toml index d9d8d86..acaa495 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,11 +9,7 @@ license = "MIT" chrono = "0.4.38" 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" -packed_struct = "0.10.1" +log = "0.4.22" ratatui = "=0.30.2" serde = { version = "1.0.210", features = ["derive"] } serialport = "4.5.0" diff --git a/README.md b/README.md index 9e759be..1c62550 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,8 @@ before connecting an Ultra or Ultra+. ## Documentation - [Documentation index](docs/README.md) — where to start and source policy +- [Configuration](docs/configuration.md) — defaults, partial overrides, units, validation, and saved selections +- [Testing guide](docs/testing.md) — hardware-free regression tests and test boundaries - [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, @@ -49,8 +51,10 @@ as a COM port. The user running `tiny-wb` must have permission to open it. The interface uses arrow keys or Vim-style `h`, `j`, `k`, `l`. Left/right selects a field, up/down changes its value, Enter advances, and `q` or Escape quits. Scan frequencies shown in the UI are MHz. The selected settings are -stored in `config.toml`; scan results are written in the current directory as -`scan_YYYYMMDD HH_MM_SS.csv`. +stored in `config.toml` (or `TINY_WB_CONFIG`); scan results default to the current +directory with collision-safe timestamped names. Timing, scan defaults, chart +bounds, CSV output, and logging are configurable. See the commented +[defaults](config/default.toml) and [configuration guide](docs/configuration.md). ## Current scan flow @@ -90,9 +94,10 @@ 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`. +The binary builds on a reusable library for configuration, protocol decoding, +transport, acquisition, and CSV export. UI control flow, state, and rendering +live in `src/ui/`. See [architecture](docs/architecture.md) for the source map +and [AGENTS.md](AGENTS.md) for code, documentation, and commit conventions. ## License diff --git a/docs/README.md b/docs/README.md index 47c7b18..9d7b377 100644 --- a/docs/README.md +++ b/docs/README.md @@ -42,3 +42,9 @@ 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. diff --git a/docs/architecture.md b/docs/architecture.md index 1ce11a6..f7bf6dc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,196 +1,143 @@ # 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> 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>` values. The selected connection and -scan parameters themselves are copied into the worker. +`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/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. | +| `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` | Basic input-path rules, scan request validation and pure raw-frame decoding. | +| `src/transport.rs` | Buffered `Read + Write` shell I/O, complete command writes, text prompts and length-delimited raw frames. | +| `src/acquisition.rs` | Command ordering, progress events, frame decoding and resume attempts. | +| `src/export.rs` | CSV serialization to a writer and collision-safe file export. | +| `src/main.rs` | Load configuration, start diagnostics, enumerate ports and manage terminal lifetime. | +| `src/error.rs` | Application/UI boundary errors with original context. | +| `src/scan.rs` | Open the serial port, 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 + | + serial worker + | + Shell -> acquisition + | + decode_frame -> Vec + | + 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; inclusive labels +remain the default for compatibility. + +The core reports `ScanEvent` values. `ScanState` adapts them to one +`Arc>`; 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 -`AppState` advances in one direction during a normal run: - ```text -InitialConfig -> FinalConfig -> Finished -> EndWindow -> exit - | | | - `---------------+-------------+-> Error -> exit +SelectingConnection -> SelectingScan -> Scanning -> Complete -> 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. +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. -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. +The terminal guard restores terminal modes on ordinary returns and unwinding. +Configuration, logging and enumeration errors occur before terminal takeover. +Process termination or release-mode panic abort cannot be recovered by a guard. -## Acquisition pipeline +## Acquisition and protocol boundary -`scan_with_progress` performs these operations: +1. Validate the Basic range and sample/repeat limits before opening/using a port. +2. Synchronize with stale input, allowing an idle timeout only during this step. +3. Query `version`, `info` and the existing diagnostic commands. +4. Set `repeat` and the configured raw zero offset, then query markers. +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. -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. +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`. -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. +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. -## Protocol boundary +## Configuration and persistence -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: +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. -- 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`. +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. -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). +See [configuration](configuration.md) for settings, paths and exact behavior. -## Persistence and outputs +## Extension points and remaining limits -`config.toml` is stored in the process working directory and contains: +- 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. +- Responses are still not parsed into explicit success/error acknowledgments; + an echo-only identity reply can appear nonempty. Prompt arrival is not proof + that a mutating command was accepted. +- 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. -```toml -port = "/dev/ttyACM0" -baudrate = 115200 -start_frequency = 240 -stop_frequency = 960 -points = 10001 -repeat = 1 -``` +## Dependency policy -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. +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, chrono, log/flexi_logger, color-eyre and thiserror retain +their device, presentation, timestamp and error-reporting roles. diff --git a/docs/configuration.md b/docs/configuration.md index 44bd8e8..0ce08bf 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -5,6 +5,17 @@ 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 diff --git a/docs/testing.md b/docs/testing.md index 2588efa..5b7aa56 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -16,6 +16,7 @@ cargo test --locked --doc | Protocol | Basic mode boundaries, point/repeat validation, truncated/extra records, alignment, closing brace, binary delimiter bytes, little-endian levels, offset and both frequency-axis conventions. | | Transport | One-byte/fragmented reads, multiple responses in one read, retained bytes after prompts, partial writes, invalid command lines, EOF, timeout, response size limits and raw-body framing. | | Acquisition | Exact command ordering, optional legacy pre-scan, progress completion, successful decoding, resume after malformed frames, and preservation of acquisition plus recovery errors. | +| UI/startup | Missing/stale ports, numeric overflow and clamping, configured baud rates, navigation, one-time result transfer, every screen on small/headless terminals, and invalid config before terminal startup. | | Export | Header/units, deterministic CSV values, propagated write failures and collision-safe output files. | `Shell` accepts `T: Read + Write`. To add a regression, provide a transcript diff --git a/docs/tiny-wb-operations.md b/docs/tiny-wb-operations.md index 0ab25c8..4c42988 100644 --- a/docs/tiny-wb-operations.md +++ b/docs/tiny-wb-operations.md @@ -47,8 +47,8 @@ cargo build --release ``` 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. +starts the interactive terminal immediately. Run it from the working directory for your settings and output, or set +`TINY_WB_CONFIG` to another configuration path. See [configuration](configuration.md). ### Serial permissions @@ -73,15 +73,17 @@ normally own the port. 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`); +2. the configured `serial.preferred_ports` (by default `/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. +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 -Fields and bounds are: +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 | | --- | --- | ---: | ---: | ---: | @@ -101,8 +103,9 @@ received, not a predictive time estimate. 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. +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. ## Files @@ -119,40 +122,47 @@ 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. +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 -The scanner writes `scan_YYYYMMDD HH_MM_SS.csv` in the working directory. It -has no header: +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 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). +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). ### Logs -`flexi_logger` writes diagnostic logs to a file in the working directory. 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. It also runs an auxiliary textual scan before -the raw scan. It does not snapshot and restore previous values. If preserving a +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. -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 +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 @@ -177,7 +187,8 @@ power-cycle/reload a preset after making the RF setup safe. - 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. + slow command when the configured read timeout is too short. Fragmented prompts +are handled by the buffered transport. ### Parse beginning/end/alignment error @@ -185,15 +196,15 @@ power-cycle/reload a preset after making the RF setup safe. - 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. +- 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 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. +The default `inclusive` labeling uses `points - 1` intervals, while the reviewed +firmware uses a `span / points` step. Verify with a known carrier and record the +firmware version before choosing `scan.frequency_axis = "firmware"`. This setting +changes CSV/chart labels; it does not change the instrument request. ### Levels are wrong by about 46 dB @@ -226,18 +237,11 @@ Include: 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 +## Remaining engineering work -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. +Model/capability detection, Ultra-specific command/range support, 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). diff --git a/docs/usb-protocol.md b/docs/usb-protocol.md index 59613e1..09d6ced 100644 --- a/docs/usb-protocol.md +++ b/docs/usb-protocol.md @@ -2,7 +2,7 @@ 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`. +in the upstream C source and in `src/protocol.rs`, `src/transport.rs`, and `src/acquisition.rs`. ## Transport @@ -124,7 +124,8 @@ 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: +defaults to `zero 128` before every acquisition. `scan.zero_offset` supplies both +the command and decoder offset; with the default it uses: ```text dBm = raw_u16 / 32 - 128 @@ -165,7 +166,7 @@ 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: +tiny-wb preserves historical output labels by default (`scan.frequency_axis = "inclusive"`): ```text host_step = (stop - start) / (points - 1) @@ -174,8 +175,10 @@ 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. +the last point. `scan.frequency_axis = "firmware"` selects the reviewed firmware +denominator instead. Before changing the setting, capture a known narrow carrier +with the target firmware and retain the `version` string; firmware behavior may +change. Both conventions have synthetic regression tests, not hardware proof. ## Prompt and synchronization behavior @@ -224,15 +227,21 @@ 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 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. -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. +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. Device command acceptance is not explicitly acknowledged +beyond a prompt. + +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 @@ -267,6 +276,6 @@ Use a byte-oriented program and a bounded point count instead. - 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) +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. diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..069e5c3 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,44 @@ +//! Application boundary errors; core modules keep their own typed errors. + +/// Errors surfaced during startup or acquisition. +#[derive(Debug, thiserror::Error)] +pub(crate) enum AppError { + /// 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), + /// Filesystem or terminal I/O failed. + #[error("I/O: {0}")] + Io(#[from] std::io::Error), + /// Acquisition failed, potentially including a failed resume attempt. + #[error(transparent)] + Acquisition(#[from] tiny_wb::acquisition::AcquisitionError), + /// 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, +} diff --git a/src/lib.rs b/src/lib.rs index 2fa0152..0a2047c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,19 @@ //! //! 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. +//! +//! # 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::Inclusive)?; +//! let mut csv = Vec::new(); +//! write_csv(&mut csv, &samples, true)?; +//! assert_eq!(String::from_utf8(csv)?, "frequency_MHz,level_dBm\n240,-64\n960,0\n"); +//! # Ok::<(), Box>(()) +//! ``` #![warn(missing_docs)] diff --git a/src/main.rs b/src/main.rs index 8dc8f51..d445f08 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,35 +1,41 @@ -//! 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)] +mod error; mod scan; -mod structs; mod ui; -mod ui_struct; - -use color_eyre::Result; -use structs::TinyError; -use ui_struct::AppInfo; +use error::AppError; use flexi_logger::{FileSpec, Logger, WriteMode}; +use std::path::PathBuf; +use tiny_wb::config::Config; -fn main() -> Result<(), TinyError> { - let _logger = Logger::try_with_str("info, my::critical::module=trace") - .unwrap() - .log_to_file(FileSpec::default()) +/// 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 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 _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(); - let ports = serialport::available_ports()?; - let app_r = AppInfo::new(ports).run(terminal); - - ratatui::restore(); - - app_r.map_err(TinyError::TUIRuntimeError) + let _session = TerminalSession; + let terminal = ratatui::try_init()?; + ui::App::new(ports, config, config_path).run(terminal)?; + Ok(()) } diff --git a/src/scan.rs b/src/scan.rs index 84607ee..2808562 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -1,362 +1,180 @@ -//! The "lib" used for all scan related functions +//! Serial worker adapter and shared progress state for the terminal application. +//! +//! The worker opens the device and exports completed samples. Protocol parsing +//! and orchestration stay in the library; no core type knows about UI widgets. -/// The offset used for sending data -static OFFSET: usize = 128; -/// The base delay used inbetween commands -static SHORT_WAIT: u64 = 20; -/// A long delay used to wait for alignment -static LONG_WAIT: u64 = 200; -/// The standard timeout time -static TIMEOUT: u64 = 2000; - -use crate::structs::ConnectionInfo; -use crate::structs::{ConnectionStatus, TinyError}; -use log::{error, trace, warn}; -use memchr::memmem; -use packed_struct::prelude::*; -use serialport::SerialPort; +use crate::error::{AppError, UiError}; use std::{ - fs::File, - io::{BufWriter, Read, Write}, - sync::{Arc, Mutex, OnceLock}, - thread::{self}, + path::PathBuf, + sync::{Arc, Mutex, MutexGuard}, time::Duration, }; +use tiny_wb::{ + acquisition::{acquire, ScanEvent}, + config::Config, + export::save_csv, + protocol::ScanRequest, + transport::Shell, +}; -use chrono::Local; - -/// A single datapoint, using a struct might be overkill but msb/lsb could become a problem in the future -#[derive(PackedStruct, Debug)] -#[packed_struct(endian = "lsb")] -pub struct DataPoint { - /// The alignement character 'x' - align: u8, - /// The value sent with as a u16 - value: u16, +/// Acquisition lifecycle visible to the UI. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ScanStatus { + /// No worker has started. + #[default] + Ready, + /// Port opening, acquisition or CSV export is in progress. + Running, + /// Samples and CSV are available. + Complete, + /// A worker or UI transition failed. + Failed, } -/// A static memory lookup function to find the eof string with speed -/// This will construct a lookup fonction for "ch>" -static EOF: OnceLock> = OnceLock::new(); +/// Data protected by one lock so terminal state changes are coherent. +#[derive(Debug, Default)] +struct Progress { + /// Completion estimate, clamped to 0–100. + percent: usize, + /// Lifecycle status. + status: ScanStatus, + /// Current operation or completion message. + message: String, + /// Verbatim identification replies. + info: String, + /// Samples converted to the chart's `(MHz, dBm)` representation. + samples: Option>, + /// Completed output path. + filename: Option, + /// User-readable error with its underlying context. + error: Option, +} -/// Scan a specific range and returns the scan result -pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(), TinyError> { - let mode = mode_from(connection_info.start, connection_info.stop)?; - let mut port = acquire_port(&connection_info)?; +/// Cloneable progress handle; acquisition parameters are passed separately. +#[derive(Debug, Clone, Default)] +pub(crate) struct ScanState(Arc>); - connection_info.update_message("Initialisation..."); - connection_info.update_progress(5); - initialize(&mut port); - connection_info.set_connection_status(ConnectionStatus::Connected); - - connection_info.update_progress(15); - connection_info.update_message("Acquiring version & info"); - let v = send_cmd(&mut port, "version\r", SHORT_WAIT)?; - let i = send_cmd(&mut port, "info\r", SHORT_WAIT)?; - let f = send_cmd(&mut port, "leveloffset\r", SHORT_WAIT)?; - let g = send_cmd(&mut port, "vbat\r", SHORT_WAIT)?; - let h = send_cmd(&mut port, "usart_cfg\r", SHORT_WAIT)?; - let k = send_cmd(&mut port, "threads\r", SHORT_WAIT)?; - log::info!("{f}{g}{h}{k}"); - - // TODO: Parse this info in a struct and do a version check - if v.is_empty() || i.is_empty() { - return Err(TinyError::NoVersionFound); +impl ScanState { + /// Recover telemetry after a poisoned lock rather than panic in error rendering. + fn lock(&self) -> MutexGuard<'_, Progress> { + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) } - connection_info.update_info(format!("{v}{i}")); - connection_info.update_message("Setting up repeat"); - send_cmd( - &mut port, - &format!("repeat {}\r", connection_info.repeat), - SHORT_WAIT, - )?; - // // TODO: Allow for user configuration - // send_cmd(&mut port, "calc aver16\r", SHORT_WAIT); - - connection_info.update_progress(16); - connection_info.update_message("Setting zero..."); - send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT)?; - - connection_info.update_progress(17); - connection_info.update_message("Setting up marker"); - send_cmd(&mut port, "marker\r", SHORT_WAIT)?; - send_cmd(&mut port, "pause\r", SHORT_WAIT)?; - - connection_info.update_progress(18); - connection_info.update_message("Setting up scan & mode"); - send_cmd(&mut port, &format!("mode {} input\r", mode), SHORT_WAIT)?; - - connection_info.update_progress(19); - connection_info.update_message("Setting up sweep"); - send_cmd( - &mut port, - &format!("sweep start {}\r", connection_info.start), - SHORT_WAIT, - )?; - send_cmd( - &mut port, - &format!("sweep stop {}\r", connection_info.stop), - SHORT_WAIT, - )?; - - connection_info.update_progress(20); - connection_info.update_message("Sweeping..."); - send_cmd(&mut port, "sweep\r", SHORT_WAIT)?; - send_cmd( - &mut port, - &format!( - "scan {} {} 290 101\r", - connection_info.start, connection_info.stop - ), - TIMEOUT, - )?; - - connection_info.update_progress(22); - connection_info.update_message("Starting scan..."); - connection_info.set_connection_status(ConnectionStatus::ScanStarted); - connection_info.update_filename(scanraw(&mut port, connection_info.clone())?); - - connection_info.update_message("Scan finished"); - send_cmd(&mut port, "resume\r", SHORT_WAIT)?; - - connection_info.update_progress(100); - connection_info.set_connection_status(ConnectionStatus::ClosedWithSuccess); - Ok(()) -} - -/// Open the configured serial port and reflect failures in the shared status. -fn acquire_port(connection_info: &ConnectionInfo) -> Result, TinyError> { - let port = { - connection_info.update_message("Opening connection"); - connection_info.set_connection_status(ConnectionStatus::Initialised); - let port = serialport::new(&connection_info.port, connection_info.baudrate) - .timeout(Duration::from_millis(3000)) - .open(); - if let Err(e) = port { - connection_info.set_error(Some(TinyError::PortConnection(e.clone()).into())); - return Err(TinyError::PortConnection(e)); + /// Reflect a library event without coupling the library to the terminal. + fn report(&self, event: ScanEvent) { + let mut state = self.lock(); + match event { + ScanEvent::Message(message) => state.message = message.into(), + ScanEvent::Progress(percent) => state.percent = usize::from(percent).min(99), + ScanEvent::InstrumentInfo(info) => state.info = info, } - port - }?; - Ok(port) -} - -/// Get the mode of operation from the start & stop scan values -fn mode_from(start: usize, stop: usize) -> Result { - if start > stop { - return Err(TinyError::BadScanFrequencies(format!( - "Start frequency {}Hz is higher than stop frequency {}Hz", - start, stop - ))); } - if start >= 350_000_000 && stop <= 960_000_000 { - Ok("high".to_string()) - } else if stop < 350_000_000 { - Ok("low".to_string()) - } 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(), - )) + + /// Current completion estimate; 100 means acquisition and export succeeded. + pub(crate) fn progress(&self) -> usize { + self.lock().percent + } + /// Current operation description. + pub(crate) fn message(&self) -> String { + self.lock().message.clone() + } + /// Device identification response. + pub(crate) fn info(&self) -> String { + self.lock().info.clone() + } + /// Current lifecycle state. + pub(crate) fn status(&self) -> ScanStatus { + self.lock().status + } + /// Error text, if any. + pub(crate) fn error(&self) -> Option { + self.lock().error.clone() + } + /// Transfer completed samples once, avoiding per-frame copies of a large scan. + pub(crate) fn take_samples(&self) -> Result, UiError> { + self.lock().samples.take().ok_or(UiError::NoReturnData) + } + /// Publish output and samples together after successful acquisition and export. + pub(crate) fn complete(&self, filename: PathBuf, samples: Vec<(f64, f64)>) { + let mut progress = self.lock(); + progress.message = format!("Saved {}", filename.display()); + progress.filename = Some(filename); + progress.samples = Some(samples); + progress.percent = 100; + progress.status = ScanStatus::Complete; + } + + /// Record failure and move to the error state together. + pub(crate) fn fail(&self, error: impl std::fmt::Display) { + log::error!("{error}"); + let mut state = self.lock(); + state.error = Some(error.to_string()); + state.status = ScanStatus::Failed; } } -/// A (lame) function used for initialisation: -/// Wait's for a whole timeout for data stuck in the buffer and dumps it -fn initialize(port: &mut Box) { - wait_sync(SHORT_WAIT); - let d = read_port(port); - if !d.is_empty() { - log::info!(target: "scan", "Pre-init data found"); - log::info!(target: "scan", "{:?}", String::from_utf8_lossy(&d).to_string()); +/// Open one port, acquire through the reusable core, then export valid samples. +pub(crate) fn run_scan( + state: ScanState, + request: ScanRequest, + config: Config, +) -> Result<(), AppError> { + { + let mut progress = state.lock(); + progress.status = ScanStatus::Running; + progress.message = "Opening connection".into(); } - wait_sync(SHORT_WAIT) -} - -/// Bad synchronisation method to ensure data is truthfully sent/received -fn wait_sync(duration: u64) { - thread::sleep(Duration::from_millis(duration)); -} - -/// Scan raw frequencies -fn scanraw( - port: &mut Box, - connection_info: ConnectionInfo, -) -> Result { - unsafe { - send_raw( - port, - &format!( - "scanraw {} {} {}\r", - connection_info.start, connection_info.stop, connection_info.points - ), - )? - } - wait_sync(SHORT_WAIT); - let (name, val) = read_scanraw(port, connection_info.clone())?; - connection_info.update_return_data(val); - wait_sync(LONG_WAIT); - Ok(name) -} - -/// Send a command and reads it to a string -fn send_cmd(port: &mut Box, command: &str, wait: u64) -> Result { - unsafe { send_raw(port, command)? } - wait_sync(wait); - let r = read_utf8(port); - wait_sync(LONG_WAIT); - Ok(r) -} - -/// Send a command without reading the output buffer -/// This command will produce unknown results if the output buffer is never read -unsafe fn send_raw(port: &mut Box, command: &str) -> Result<(), TinyError> { - let output = command.as_bytes(); - let _r = port.write(output).map_err(TinyError::SendError)?; - Ok(()) -} - -/// Reads from port and tries to convert it to string with loss -fn read_utf8(port: &mut Box) -> String { - String::from_utf8_lossy(&read_port(port)).to_string() -} - -/// Reads the serial port until it reaches EOF -fn read_port_with_progress( - port: &mut Box, - expected: usize, - progress: Arc>, -) -> Vec { - let mut serial_buf: Vec = vec![0; 64]; - let mut res = Vec::new(); - let finder = EOF.get_or_init(|| memmem::Finder::new("ch>")); - while let Ok(r) = port.read(serial_buf.as_mut_slice()) { - // TODO: Pass the whole object to avoid this unwrap ? - *progress.lock().unwrap() = (100usize.saturating_sub( - (80 * (expected.saturating_sub(res.len())).clamp(0, expected)) / expected, - )) - .clamp(20, 99); - if let Some(pos) = finder.find(&serial_buf) { - res.extend_from_slice(&serial_buf[..pos]); - break; - } - res.extend_from_slice(&serial_buf[..r]); - } - res -} - -/// Read port without updating progress -// TODO: Find a way to avoid code duplication -fn read_port(port: &mut Box) -> Vec { - let mut serial_buf: Vec = vec![0; 256]; - let mut res = Vec::new(); - let finder = EOF.get_or_init(|| memmem::Finder::new("ch>")); - while let Ok(r) = port.read(serial_buf.as_mut_slice()) { - if let Some(pos) = finder.find(&serial_buf) { - res.extend_from_slice(&serial_buf[..pos]); - break; - } - res.extend_from_slice(&serial_buf[..r]); - } - res -} - -/// Scan for a raw frequencies, assumes everything is setup and the scan can proceed -/// Waits the normal start Character '{' and begins treating data as normal -/// -/// Returns a struct summerizing the information processed -fn read_scanraw( - port: &mut Box, - connection_info: ConnectionInfo, -) -> Result<(String, Vec<(f64, f64)>), TinyError> { - let v = read_port_with_progress( - port, - connection_info.points * 3 + 6, - connection_info.mutex_progress(), + config.validate()?; + request + .input_mode() + .map_err(tiny_wb::acquisition::AcquisitionError::from)?; + let port = serialport::new(&config.port, config.baudrate) + .timeout(Duration::from_millis(config.serial.timeout_ms)) + .open()?; + let mut shell = Shell::new(port, config.serial.max_response_bytes); + let samples = acquire( + &mut shell, + &request, + &config.scan, + &config.serial, + |event| state.report(event), + )?; + state.report(ScanEvent::Message("Writing CSV")); + let filename = save_csv(&samples, &config.output)?; + state.complete( + filename, + samples + .into_iter() + .map(|sample| (sample.frequency_mhz, sample.level_dbm)) + .collect(), ); - parse_data( - v, - connection_info.points, - connection_info.start, - (connection_info.stop - connection_info.start) as f64 / (connection_info.points - 1) as f64, - ) + Ok(()) } -/// A utility function used for parsing the raw data of a scan -// TODO: Split save data to another function -pub fn parse_data( - v: Vec, - points: usize, - start: usize, - increment: f64, -) -> Result<(String, Vec<(f64, f64)>), TinyError> { - // let mut values: Vec = Vec::with_capacity(points); - let name = format!("scan_{}.csv", Local::now().format("%Y%m%d %H_%M_%S")); - let mut out = BufWriter::new(File::create(&name)?); - let mut csvdata = Vec::with_capacity(points); - if let Some(begining) = memchr::memchr(b'{', &v) { - let end_tmp = v.len(); - let data = &v[begining + 1..end_tmp]; // -4 since ch>\r will always be ignored - // TODO: Fix weird data - log::info!( - "The begining looks like :{:?}", - &v[begining - 1..begining + 9] - ); - log::info!("The end looks like :{:?}", &v[end_tmp - 10..end_tmp]); +#[cfg(test)] +mod tests { + use super::*; - let mut end = end_tmp; - let (chunks, _remainder) = data.as_chunks::<3>(); - // if chunks_exact.remainder().is_empty() { - // return Err(TinyError::ParseEnd( - // "The data received doesn't have a end char (empty)".to_owned(), - // )); - // } else if chunks_exact.remainder()[0] != b'}' { - // error!("Incorrect right end char {:?}", chunks_exact.remainder()); - // // No end char, bogus - // return Err(TinyError::ParseEnd(format!( - // "The returned data doesn't have the right end char expected }} found {:?}", - // chunks_exact.remainder() - // ))); - // } - for (i, slice) in chunks.iter().enumerate() { - let d = DataPoint::unpack(slice)?; - if d.align == b'}' { - // Found an end and the rest is garbage - end = i * 3; - // TODO: why doesn't it pop ? - warn!("Found an end at {end} {:?}", &v[end - 4..end]); - break; - } else if d.align != b'x' { - // The alignment char is wrong - error!("Wrong alignment char expected {} found {}", b'x', d.align); - return Err(TinyError::ParseEnd("Wrong alignement char".to_owned())); - } - let (pos, val) = ( - (i as f64 * increment + start as f64) / 1000000., - u16_to_f64(d.value), - ); - trace!("{} : {pos},{val}", i); + #[test] + fn shared_progress_and_errors_are_visible_across_clones() { + let state = ScanState::default(); + let worker = state.clone(); + worker.report(ScanEvent::Progress(100)); + assert_eq!(state.progress(), 99, "export must finish before 100%"); + worker.report(ScanEvent::InstrumentInfo("Basic".into())); + assert_eq!(state.info(), "Basic"); + worker.fail("disconnected"); + assert_eq!(state.status(), ScanStatus::Failed); + assert_eq!(state.error().as_deref(), Some("disconnected")); + } - csvdata.push((pos, val)); - writeln!(out, "{},{}", pos, val,)?; - } - // TODO: Dont return use mutex - // info!("debug",format!("{} {}", data.len(), v.len()); - log::info!( - "End at {end} expected {} and found {} ({:?})", - b'}', - v[end - 1], - &v[end - 4..=end - 1] - ); - Ok((name, csvdata)) - } else { - Err(TinyError::ParseBeggining("{".to_owned())) + #[test] + fn completed_samples_are_transferred_once() { + let state = ScanState::default(); + state.lock().samples = Some(vec![(240.0, -64.0)]); + assert_eq!(state.take_samples().unwrap(), vec![(240.0, -64.0)]); + assert!(state.take_samples().is_err()); } } - -/// Utility function converting the received data as u16 to float data -fn u16_to_f64(v: u16) -> f64 { - (v as f64) / 32. - OFFSET as f64 -} diff --git a/src/structs.rs b/src/structs.rs deleted file mode 100644 index 4c073c7..0000000 --- a/src/structs.rs +++ /dev/null @@ -1,324 +0,0 @@ -//! All the structs used internally - -use std::{ - fs::File, - io::{Read, Write}, - sync::{Arc, Mutex}, -}; - -use flexi_logger::FlexiLoggerError; - -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)] -/// Configuration persisted between tiny-wb sessions. -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 { - 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, - /// A scan command was accepted and acquisition has started. - ScanStarted, -} - -/// Frequency and amplitude pairs returned by a scan. -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>, - /// 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>>, - /// The information of the TinySA - scan_info: Arc>, - /// The last scan message (what's happening as the scan goes) - scan_message: Arc>, - /// 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>, - /// The connection status - connection_status: Arc>, - /// The last error raised - pub(crate) error_raised: Arc>>, -} - -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> { - 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, TinyUIError> { - self.return_data - .lock() - .unwrap() - .take() - .ok_or(TinyUIError::NoReturnData) - } - - /// Set an error - pub(crate) fn set_error(&self, e: Option) { - 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 { - // 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)), - } - } -} diff --git a/src/ui.rs b/src/ui.rs deleted file mode 100644 index 994b58f..0000000 --- a/src/ui.rs +++ /dev/null @@ -1,674 +0,0 @@ -//! The (minimal) user interface to control the program -use log::info; -use ratatui::{ - crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, - layout::{Constraint, Layout, Rect}, - style::{Color, Modifier, Style}, - symbols::Marker, - widgets::{Axis, Block, Chart, Dataset, GraphType, LineGauge, List, Paragraph, Wrap}, - DefaultTerminal, Frame, -}; -use serialport::SerialPortInfo; -use std::{thread, time::Duration}; -use strum::EnumCount; - -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) -> 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).unwrap_or_else(|e| panic!("{}", e)))?; - 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.status_message = format!( - "TinyWB version {}-{}, by the Dandaedre 🄯 2024", - env!("CARGO_PKG_VERSION"), - env!("GIT_HASH") - ); - 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 [_, 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); - // 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()) - .wrap(Wrap { trim: true }) - .block(Block::bordered()), - 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 [_, 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(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()) - .wrap(Wrap { trim: true }) - .block(Block::bordered()), - 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()) - .wrap(Wrap { trim: true }) - .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) - .wrap(Wrap { trim: true }) - .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 - )) - .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(()) - } - - /// Extract a user explaination for an error message - fn error_message_from_current_error(&self) -> Result { - 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) => { - return Ok(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(()) - } -} diff --git a/src/ui/mod.rs b/src/ui/mod.rs new file mode 100644 index 0000000..b5e3485 --- /dev/null +++ b/src/ui/mod.rs @@ -0,0 +1,373 @@ +//! 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, PortList, SelectedConnection, + SelectedScan, +}; +use std::{path::PathBuf, thread, time::Duration}; +use strum::EnumCount; +use tiny_wb::{config::Config, protocol::ScanRequest}; + +impl App { + /// Construct UI state from already validated settings; no file I/O here. + pub(crate) fn new(info: Vec, 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, + 960, + ), + stop_frequency: NumericInput::new( + config.stop_frequency, + config.scan.frequency_step_mhz, + 10, + 960, + ), + 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(), + return_data: Vec::new(), + config, + config_path, + } + } + + /// 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; + } + let mut draw_error = None; + terminal.draw(|frame| { + draw_error = self.draw(frame).err(); + })?; + if let Some(error) = draw_error { + return Err(error.into()); + } + 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; + }; + }; + if self.should_quit { + break; + } + } + } + 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(()); + } + 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 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::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::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(_) => { + 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 + .input_mode() + .map_err(tiny_wb::acquisition::AcquisitionError::from) + .map_err(AppError::from)?; + config.save(&self.config_path).map_err(AppError::from)?; + self.flow_state = AppState::Scanning; + self.init_progress()?; + let connection = self.scan_state.clone(); + thread::spawn(move || { + if let Err(error) = scan::run_scan(connection.clone(), request, config) { + connection.fail(error); + } + }); + } + AppState::Complete => { + self.should_quit = true; + } + AppState::Scanning => {} + AppState::Error => { + self.should_quit = true; + } + } + 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 => { + self.return_data = self.scan_state.take_samples()?; + self.flow_state = AppState::Complete; + } + ScanStatus::Failed => self.flow_state = AppState::Error, + ScanStatus::Ready | ScanStatus::Running => {} + } + } + Ok(()) + } +} + +#[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 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(0, 10, 0, 960); + 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.return_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 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(); + 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::Complete, + AppState::Error, + ] { + app.flow_state = screen; + terminal.draw(|frame| app.draw(frame).unwrap()).unwrap(); + } + } + } +} diff --git a/src/ui/state.rs b/src/ui/state.rs new file mode 100644 index 0000000..4c5b087 --- /dev/null +++ b/src/ui/state.rs @@ -0,0 +1,356 @@ +//! 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::ScanState, +}; +use tiny_wb::config::Config; + +/// 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, + /// Validated settings retained when the selection is saved. + pub(crate) config: Config, + /// Explicit settings path selected at startup. + pub(crate) config_path: PathBuf, + /// Completed samples owned by the UI, in MHz and dBm. + pub(crate) return_data: Vec<(f64, f64)>, +} + +#[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, +} + +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, + } + } + + /// Read the current value. + pub(crate) fn value(&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 + SelectingConnection(SelectedConnection), + /// Final config, frequencies and points + SelectingScan(SelectedScan), + /// The end window for confirmation + Complete, + /// Acquisition and export progress. + Scanning, + /// 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, + /// 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 { + 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 { + 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, + /// 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, config: &Config) -> Self { + let ports: Vec = 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 { + 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 { + 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>, + /// Cached list widget. + pub(crate) baudlist: Option>, + /// The progress bar + pub(crate) progress_bar: Option>, +} + +/// Prefer the saved device, then configured candidates, then the first port. +fn find_best_port(ports: &[String], config: &Config) -> Option { + 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 { + 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 { + 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 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); + } +} diff --git a/src/ui/view.rs b/src/ui/view.rs new file mode 100644 index 0000000..e850dcd --- /dev/null +++ b/src/ui/view.rs @@ -0,0 +1,386 @@ +//! Ratatui rendering; acquisition results arrive through shared scan state. + +use super::state::{ + App, AppState, 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, 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::Complete => self.draw_end_window(frame), + AppState::Error => self.draw_error(frame), + } + } + + /// 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) { + frame.render_widget( + Paragraph::new( + "Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.", + ) + .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 status = Paragraph::new(format!( + "The scan of {} points in the range ({}MHz - {}MHz) finished successfully", + self.points.value(), + self.start_frequency.value(), + self.stop_frequency.value(), + )) + .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.value() as f64, + self.stop_frequency.value() as f64, + ]) + .style(Style::default().fg(Color::Gray)) + .labels([ + format!("{}MHz", self.start_frequency), + format!( + "{}MHz", + self.start_frequency.value() + + (self + .stop_frequency + .value() + .saturating_sub(self.start_frequency.value())) + / 2 + ), + format!("{}MHz", self.stop_frequency), + ]), + ) + .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); + let footer = Paragraph::new(format!( + "{}, press ↲ or q to exit", + self.scan_state.message(), + )) + .centered(); + frame.render_widget(status, title_area); + frame.render_widget(footer, footer_area); + Ok(()) + } +} + +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> { + 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(()) + } +} diff --git a/src/ui_struct.rs b/src/ui_struct.rs deleted file mode 100644 index 85052a4..0000000 --- a/src/ui_struct.rs +++ /dev/null @@ -1,406 +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, - /// 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)] -/// Numeric input state with bounded keyboard increments. -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(std::cmp::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, Default, EnumCount, FromRepr, Clone, Copy)] -pub(crate) enum SelectedConfig { - /// Selects the ports - #[default] - Port, - /// Selects the baudrate - Baudrate, - // /// Selects to proceed - // Proceed, -} - -/// The selected item in the final menu -#[derive(Debug, Default, EnumCount, FromRepr, Copy, Clone)] -pub(crate) enum SelectedFinalConfig { - /// Selects the start frequency - #[default] - StartFreq, - /// Selects the final frequency - FinalFreq, - /// Selects the number of points - Points, - /// Selects the repeat - Repeat, - // /// Selects to proceed - // Proceed, -} - -/// 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, - /// 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 { - 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) -> 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 { - 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::>(), - 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, - // /// 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, - saved_config: &Result, - ) -> Self { - let ports: Vec = 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 { - 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 { - 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 of port items - pub(crate) baudlist: Option>, - /// List of all the textboxes - pub(crate) textboxes: Vec>, - /// The progress bar - pub(crate) progress_bar: Option>, - // /// Controller info - // pub(crate) info: Option>, - // /// The final graph - // pub(crate) graph: Option>, -} - -/// Try to guess the best port to preselect -fn find_best_port(ports: &[String], saved_config: &Result) -> 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> { - 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 -// }}; -// } diff --git a/tests/startup.rs b/tests/startup.rs new file mode 100644 index 0000000..70ab613 --- /dev/null +++ b/tests/startup.rs @@ -0,0 +1,23 @@ +//! 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(); +}