feat: add live scan mode
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-10-08 09:39:05 +02:00
parent 82eaffc17b
commit 78bd22023c
15 changed files with 1082 additions and 73 deletions

View File

@ -43,6 +43,11 @@ From the repository root:
cargo run --release cargo run --release
``` ```
Use `cargo run --release -- --live` to confirm the usual connection and scan
settings, then display repeated complete sweeps until stopped. Number keys select
average/hold/decay traces, `s` saves the visible buffer, and `q`, Escape, or
Enter stops, resumes the instrument, saves once more, and exits.
On Linux the serial device is commonly `/dev/ttyACM0`; on Windows it appears as On Linux the serial device is commonly `/dev/ttyACM0`; on Windows it appears as
a COM port. If the port cannot be opened, follow the a COM port. If the port cannot be opened, follow the
[serial-permission guidance](docs/tiny-wb-operations.md#serial-permissions). [serial-permission guidance](docs/tiny-wb-operations.md#serial-permissions).

View File

@ -20,7 +20,8 @@ widgets, port discovery, worker threads, or the application's working directory.
| `examples/mock-tinysa-server.rs` | Portable TCP listener for the mock, outside release binaries. | | `examples/mock-tinysa-server.rs` | Portable TCP listener for the mock, outside release binaries. |
| `src/acquisition.rs` | Command ordering, progress events, frame decoding and resume attempts. | | `src/acquisition.rs` | Command ordering, progress events, frame decoding and resume attempts. |
| `src/export.rs` | CSV parsing/serialization over I/O traits and collision-safe file export. | | `src/export.rs` | CSV parsing/serialization over I/O traits and collision-safe file export. |
| `src/main.rs` | Select acquisition/direct-view mode, load configuration, start diagnostics, enumerate ports when needed and manage terminal lifetime. | | `src/live.rs` | Bounded rolling average, hold and decay calculations over explicit sweeps. |
| `src/main.rs` | Select single/live/direct-view mode, load configuration, start diagnostics, enumerate ports when needed and manage terminal lifetime. |
| `src/error.rs` | Application/UI boundary errors with original context. | | `src/error.rs` | Application/UI boundary errors with original context. |
| `src/scan.rs` | Open the configured connection, adapt core events to shared progress, and export successful acquisitions. | | `src/scan.rs` | Open the configured connection, adapt core events to shared progress, and export successful acquisitions. |
| `src/ui/mod.rs` | Screen transitions, keyboard handling, worker startup and progress reconciliation. | | `src/ui/mod.rs` | Screen transitions, keyboard handling, worker startup and progress reconciliation. |
@ -73,6 +74,7 @@ SelectingConnection -> SelectingScan -> Scanning -> Complete -> exit
| | | | | |
+------------------+-------------+-> Error -> exit +------------------+-------------+-> Error -> exit
CSV file -------------------------------------> Complete -> exit CSV file -------------------------------------> Complete -> exit
--live: SelectingConnection -> SelectingScan -> Live --stop+save--> exit
``` ```
The constructor takes configuration and enumerated ports as values, without The constructor takes configuration and enumerated ports as values, without
@ -87,6 +89,13 @@ Zooming and panning mutate only that viewport, not sample data. This plot
boundary can grow into a tabbed collection without coupling CSV parsing or boundary can grow into a tabbed collection without coupling CSV parsing or
acquisition to Ratatui. acquisition to Ratatui.
Live mode uses repeated complete snapshots over one configured connection. The
worker publishes only decoded sweeps into a bounded `TraceBuffer`; rendering
copies at most once per completed sweep. Stop and save requests cross the shared
state boundary, while device I/O and CSV creation remain in the worker. Native
continuous `scanraw` is intentionally deferred because it needs verified abort
syntax and stream resynchronization.
The terminal guard restores terminal modes on ordinary returns and unwinding. The terminal guard restores terminal modes on ordinary returns and unwinding.
Configuration and direct-view CSV errors occur before logger initialization; Configuration and direct-view CSV errors occur before logger initialization;
logging and enumeration errors occur before terminal takeover. logging and enumeration errors occur before terminal takeover.

View File

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

View File

@ -17,7 +17,8 @@ can represent it in the UI.
| Ultra+ ZS406 0.1–900 MHz | Hardware communications validated | Explicit ZS406/V0.4.6 identity permits the full normal-mode range; RF accuracy is not qualified. | | Ultra+ ZS406 0.1–900 MHz | Hardware communications validated | Explicit ZS406/V0.4.6 identity permits the full normal-mode range; RF accuracy is not qualified. |
| Ultra+ ZS406 above 900 MHz through 5.4 GHz | Opt-in; hardware communications validated | Requires `scan.enable_ultra_mode = true`, sends `ultra on`, and verifies sweep readback. Expect slower scans, aliases/spurs and RF-port LO leakage. | | Ultra+ ZS406 above 900 MHz through 5.4 GHz | Opt-in; hardware communications validated | Requires `scan.enable_ultra_mode = true`, sends `ultra on`, and verifies sweep readback. Expect slower scans, aliases/spurs and RF-port LO leakage. |
| ZS407 extended mode or any harmonic mode | Rejected | Their different ceilings and measurement behavior are not implemented. | | ZS407 extended mode or any harmonic mode | Rejected | Their different ceilings and measurement behavior are not implemented. |
| Generator control, live streaming, capture, calibration, firmware update | Out of scope | No corresponding application workflow exists. | | Repeated-snapshot live display | Implemented; awaiting hardware qualification | `--live` retains a bounded 16-sweep history and one point buffer per derived hold/decay trace. It does not use native continuous framing. |
| Generator control, display capture, calibration, firmware update | Out of scope | No corresponding application workflow exists. |
At the exact 350 MHz boundary, the implementation's matching rules matter: At the exact 350 MHz boundary, the implementation's matching rules matter:
low accepts frequencies strictly below 350 MHz, while high accepts 350 MHz low accepts frequencies strictly below 350 MHz, while high accepts 350 MHz
@ -59,6 +60,18 @@ open its renderer directly:
Run it from the working directory for your settings and output, or set Run it from the working directory for your settings and output, or set
`TINY_WB_CONFIG` to another configuration path. See [configuration](configuration.md). `TINY_WB_CONFIG` to another configuration path. See [configuration](configuration.md).
For live display, launch:
```console
./target/release/tiny-wb --live
```
Select the connection and scan parameters normally. The configured Points value
is the fixed size of every live sweep and visible/exported trace. tiny-wb opens
one connection, configures it once, and requests repeated complete `scanraw`
snapshots. This deliberately avoids firmware continuous framing until abort and
stream-resynchronization behavior is verified on supported hardware.
### Serial permissions ### Serial permissions
On Linux, identify the device after plugging it in: On Linux, identify the device after plugging it in:
@ -140,6 +153,31 @@ are not available when viewing a CSV directly. Plot bindings are configurable
under `[ui.bindings]`; on acquired results, `r` and `n` take precedence over any under `[ui.bindings]`; on acquired results, `r` and `n` take precedence over any
matching plot binding. `q`, Escape, or Enter exits the renderer. matching plot binding. `q`, Escape, or Enter exits the renderer.
### Live display
Live mode updates the plot only after a complete, validated sweep. Its host-side
calculation keys are:
| Key | Visible buffer |
| --- | --- |
| `1` | Rolling arithmetic average of up to 4 sweeps |
| `2` | Rolling arithmetic average of up to 16 sweeps |
| `3` | Maximum held at each frequency since live capture began |
| `4` | Maximum with a 1 dB fall per completed sweep, limited by the new value |
| `5` | Minimum held at each frequency since live capture began |
| `6` | Minimum with a 1 dB rise per completed sweep, limited by the new value |
The history is bounded to 16 complete sweeps regardless of run duration. Hold
and decay calculations retain one value per configured point. `s` writes the
currently selected buffer to a new collision-safe CSV while capture continues.
`q`, Escape, or Enter requests a stop; the current sweep is allowed to finish,
the instrument receives `resume`, the selected buffer is saved, and the program
exits. A transport failure is reported rather than exporting a partial frame.
Subtraction/reference-buffer processing is not implemented yet. The live modes
are host calculations over repeated snapshots, not claims about the firmware's
front-panel detector or trace modes, and require physical-device qualification.
## Files ## Files
### `config.toml` ### `config.toml`

View File

@ -82,9 +82,11 @@ Constraints visible in upstream firmware:
- waterfall is disabled before acquisition in current firmware; - waterfall is disabled before acquisition in current firmware;
- a continuous request must be explicitly aborted and needs a streaming parser. - a continuous request must be explicitly aborted and needs a streaming parser.
tiny-wb omits OPTIONS, so it requests one buffered acquisition. The firmware tiny-wb omits OPTIONS, so ordinary acquisition requests one buffered sweep and
buffers in small blocks internally; “buffered” does not mean the entire sweep `--live` repeats that complete request over one configured connection. The
is delivered in a single USB transfer. firmware buffers in small blocks internally; “buffered” does not mean the entire
sweep is delivered in a single USB transfer. Native option-2 continuous framing
remains unsupported until explicit abort and resynchronization are verified.
## Binary response framing ## Binary response framing

View File

@ -108,13 +108,85 @@ pub fn acquire<T: Read + Write>(
serial: &SerialConfig, serial: &SerialConfig,
mut report: impl FnMut(ScanEvent), mut report: impl FnMut(ScanEvent),
) -> Result<Vec<Sample>, AcquisitionError> { ) -> Result<Vec<Sample>, AcquisitionError> {
let prepared = prepare_acquisition(shell, request, scan, serial, &mut report)?;
// Pause may take effect even when its response times out, so recovery also
// covers failure receiving the pause response itself.
let result = (|| {
configure_paused(shell, request, scan, serial, prepared)?;
report(ScanEvent::Message("Acquiring samples"));
let frame = read_snapshot(shell, request, &mut report)?;
Ok(protocol::decode_frame(
&frame,
request,
prepared.zero_offset,
scan.frequency_axis,
)?)
})();
let samples = resume_after(shell, prepared, result)?;
report(ScanEvent::Message("Acquisition complete"));
report(ScanEvent::Progress(100));
Ok(samples)
}
/// Repeatedly acquire complete bounded snapshots on one configured connection.
///
/// This deliberately does not use firmware continuous framing. Cancellation is
/// checked before each snapshot, so an in-progress sweep completes before the
/// instrument is resumed. `on_sweep` receives only fully decoded frames.
///
/// # Errors
///
/// Returns an error when validation, device identification, configuration,
/// transport, frame decoding, or the final resume command fails. When both
/// acquisition and resume fail, both errors are retained.
pub fn acquire_live<T: Read + Write>(
shell: &mut Shell<T>,
request: &ScanRequest,
scan: &ScanConfig,
serial: &SerialConfig,
mut should_stop: impl FnMut() -> bool,
mut on_sweep: impl FnMut(Vec<Sample>),
mut report: impl FnMut(ScanEvent),
) -> Result<u64, AcquisitionError> {
let prepared = prepare_acquisition(shell, request, scan, serial, &mut report)?;
let result = (|| {
configure_paused(shell, request, scan, serial, prepared)?;
report(ScanEvent::Message("Live capture running"));
let mut sweeps = 0_u64;
while !should_stop() {
let frame = read_snapshot(shell, request, &mut report)?;
let samples =
protocol::decode_frame(&frame, request, prepared.zero_offset, scan.frequency_axis)?;
sweeps = sweeps.saturating_add(1);
on_sweep(samples);
}
Ok(sweeps)
})();
resume_after(shell, prepared, result)
}
#[derive(Clone, Copy)]
struct PreparedAcquisition {
delay: Duration,
settle: Duration,
plan: crate::device::AcquisitionPlan,
zero_offset: u16,
}
fn prepare_acquisition<T: Read + Write>(
shell: &mut Shell<T>,
request: &ScanRequest,
scan: &ScanConfig,
serial: &SerialConfig,
report: &mut impl FnMut(ScanEvent),
) -> Result<PreparedAcquisition, AcquisitionError> {
request.validate()?; request.validate()?;
let delay = Duration::from_millis(serial.command_delay_ms); let delay = Duration::from_millis(serial.command_delay_ms);
let settle = Duration::from_millis(serial.settle_delay_ms); let settle = Duration::from_millis(serial.settle_delay_ms);
report(ScanEvent::Message("Identifying instrument")); report(ScanEvent::Message("Identifying instrument"));
report(ScanEvent::Progress(5)); report(ScanEvent::Progress(5));
shell.synchronize()?; shell.synchronize()?;
let identity = identify_with_retry(shell, delay, settle, &mut report)?; let identity = identify_with_retry(shell, delay, settle, report)?;
let expected = match scan.device_model { let expected = match scan.device_model {
ModelSelection::Auto => None, ModelSelection::Auto => None,
ModelSelection::Basic => Some(DeviceModel::Basic), ModelSelection::Basic => Some(DeviceModel::Basic),
@ -176,59 +248,82 @@ pub fn acquire<T: Read + Write>(
None => { None => {
return Err(AcquisitionError::MissingZeroReadback { return Err(AcquisitionError::MissingZeroReadback {
requested: zero_offset, requested: zero_offset,
}); })
} }
} }
report(ScanEvent::Progress(20)); report(ScanEvent::Progress(20));
// Pause may take effect even when its response times out, so recovery also Ok(PreparedAcquisition {
// covers failure receiving the pause response itself. delay,
let result = (|| { settle,
shell.command_checked("pause", delay, settle)?; plan,
shell.command_checked(plan.input_command, delay, settle)?; zero_offset,
if plan.enable_ultra_mode { })
shell.command_checked("ultra on", delay, settle)?; }
}
shell.command_checked(&format!("sweep start {}", request.start_hz), delay, settle)?; fn configure_paused<T: Read + Write>(
shell.command_checked(&format!("sweep stop {}", request.stop_hz), delay, settle)?; shell: &mut Shell<T>,
let sweep_response = shell.command_checked("sweep", delay, settle)?; request: &ScanRequest,
if plan.enable_ultra_mode scan: &ScanConfig,
&& parse_sweep_bounds(&sweep_response) != Some((request.start_hz, request.stop_hz)) serial: &SerialConfig,
{ prepared: PreparedAcquisition,
return Err(AcquisitionError::SweepReadbackMismatch { ) -> Result<(), AcquisitionError> {
requested_start: request.start_hz, shell.command_checked("pause", prepared.delay, prepared.settle)?;
requested_stop: request.stop_hz, shell.command_checked(prepared.plan.input_command, prepared.delay, prepared.settle)?;
response: sweep_response, if prepared.plan.enable_ultra_mode {
}); shell.command_checked("ultra on", prepared.delay, prepared.settle)?;
} }
if scan.legacy_pre_scan { shell.command_checked(
shell.command_checked( &format!("sweep start {}", request.start_hz),
&format!("scan {} {} 290 101", request.start_hz, request.stop_hz), prepared.delay,
Duration::from_millis(serial.scan_delay_ms), prepared.settle,
settle, )?;
)?; shell.command_checked(
} &format!("sweep stop {}", request.stop_hz),
report(ScanEvent::Message("Acquiring samples")); prepared.delay,
shell.send(&format!( prepared.settle,
"scanraw {} {} {}", )?;
request.start_hz, request.stop_hz, request.points let sweep_response = shell.command_checked("sweep", prepared.delay, prepared.settle)?;
))?; if prepared.plan.enable_ultra_mode
let frame = shell.read_frame(request, |received, expected| { && parse_sweep_bounds(&sweep_response) != Some((request.start_hz, request.stop_hz))
report(ScanEvent::Progress((20 + received * 75 / expected) as u8)) {
})?; return Err(AcquisitionError::SweepReadbackMismatch {
Ok(protocol::decode_frame( requested_start: request.start_hz,
&frame, requested_stop: request.stop_hz,
request, response: sweep_response,
zero_offset, });
scan.frequency_axis, }
)?) if scan.legacy_pre_scan {
})(); shell.command_checked(
let recovery = shell.command_checked("resume", delay, settle); &format!("scan {} {} 290 101", request.start_hz, request.stop_hz),
Duration::from_millis(serial.scan_delay_ms),
prepared.settle,
)?;
}
Ok(())
}
fn read_snapshot<T: Read + Write>(
shell: &mut Shell<T>,
request: &ScanRequest,
report: &mut impl FnMut(ScanEvent),
) -> Result<Vec<u8>, AcquisitionError> {
shell.send(&format!(
"scanraw {} {} {}",
request.start_hz, request.stop_hz, request.points
))?;
Ok(shell.read_frame(request, |received, expected| {
report(ScanEvent::Progress((20 + received * 75 / expected) as u8))
})?)
}
fn resume_after<T: Read + Write, R>(
shell: &mut Shell<T>,
prepared: PreparedAcquisition,
result: Result<R, AcquisitionError>,
) -> Result<R, AcquisitionError> {
let recovery = shell.command_checked("resume", prepared.delay, prepared.settle);
match (result, recovery) { match (result, recovery) {
(Ok(samples), Ok(_)) => { (Ok(value), Ok(_)) => Ok(value),
report(ScanEvent::Message("Acquisition complete"));
report(ScanEvent::Progress(100));
Ok(samples)
}
(Err(primary), Err(recovery)) => Err(AcquisitionError::Recovery { (Err(primary), Err(recovery)) => Err(AcquisitionError::Recovery {
primary: Box::new(primary), primary: Box::new(primary),
recovery, recovery,
@ -298,6 +393,7 @@ mod tests {
use super::*; use super::*;
use crate::config::Config; use crate::config::Config;
use std::{ use std::{
cell::Cell,
io::{self, Cursor}, io::{self, Cursor},
sync::{Arc, Mutex}, sync::{Arc, Mutex},
}; };
@ -431,6 +527,57 @@ mod tests {
assert!(events.contains(&ScanEvent::Message("Retrying instrument identification"))); assert!(events.contains(&ScanEvent::Message("Retrying instrument identification")));
} }
#[test]
fn live_acquisition_repeats_complete_snapshots_then_resumes() {
let config = Config::from_toml(
"[scan]\nlegacy_pre_scan=false\n[serial]\ncommand_delay_ms=0\nsettle_delay_ms=0",
)
.unwrap();
let request = ScanRequest {
start_hz: 240_000_000,
stop_hz: 960_000_000,
points: 2,
repeat: 1,
};
let mut input = b"ch>tinySA_v1.4-test\r\nch>tinySA\r\nch>Commands: repeat zero pause mode sweep scanraw resume\r\nch>"
.to_vec();
input.extend_from_slice(b"okch>".repeat(2).as_slice());
input.extend_from_slice(b"128dBm\r\nch>");
input.extend_from_slice(b"okch>".repeat(5).as_slice());
input.extend_from_slice(b"{x\0\x08x\0\x10}ch>");
input.extend_from_slice(b"{x\0\x10x\0\x18}ch>okch>");
let commands = Arc::new(Mutex::new(Vec::new()));
let mut shell = Shell::new(
Transcript {
input: Cursor::new(input),
commands: commands.clone(),
},
1024,
);
let received = Cell::new(0_u64);
let mut levels = Vec::new();
let sweeps = acquire_live(
&mut shell,
&request,
&config.scan,
&config.serial,
|| received.get() == 2,
|samples| {
received.set(received.get() + 1);
levels.push(samples[0].level_dbm);
},
|_| {},
)
.unwrap();
assert_eq!(sweeps, 2);
assert_eq!(levels, vec![-64.0, 0.0]);
let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap();
assert_eq!(written.matches("scanraw ").count(), 2);
assert!(written.ends_with("resume\r"));
}
#[test] #[test]
fn malformed_frames_still_resume_and_preserve_original_error() { fn malformed_frames_still_resume_and_preserve_original_error() {
let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", true, true); let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", true, true);

View File

@ -29,6 +29,9 @@ pub(crate) enum AppError {
/// Acquisition failed, potentially including a failed resume attempt. /// Acquisition failed, potentially including a failed resume attempt.
#[error(transparent)] #[error(transparent)]
Acquisition(#[from] tiny_wb::acquisition::AcquisitionError), Acquisition(#[from] tiny_wb::acquisition::AcquisitionError),
/// Host-side live trace processing failed.
#[error("live capture: {0}")]
Live(String),
/// The file logger could not be initialized. /// The file logger could not be initialized.
#[error("logging: {0}")] #[error("logging: {0}")]
Logger(#[from] flexi_logger::FlexiLoggerError), Logger(#[from] flexi_logger::FlexiLoggerError),

View File

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

283
src/live.rs Normal file
View File

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

View File

@ -15,6 +15,8 @@ use tiny_wb::config::{Backend, Config};
enum StartMode { enum StartMode {
/// Configure and acquire a new scan. /// Configure and acquire a new scan.
Acquire, Acquire,
/// Configure and run repeated snapshots until the user stops them.
Live,
/// Open an existing CSV directly in the renderer. /// Open an existing CSV directly in the renderer.
View(PathBuf), View(PathBuf),
/// Print command help without loading configuration. /// Print command help without loading configuration.
@ -26,12 +28,15 @@ fn parse_start_mode(args: impl IntoIterator<Item = OsString>) -> Result<StartMod
let args: Vec<OsString> = args.into_iter().collect(); let args: Vec<OsString> = args.into_iter().collect();
match args.as_slice() { match args.as_slice() {
[] => Ok(StartMode::Acquire), [] => Ok(StartMode::Acquire),
[flag] if flag == "--live" => Ok(StartMode::Live),
[flag] if flag == "-h" || flag == "--help" => Ok(StartMode::Help), [flag] if flag == "-h" || flag == "--help" => Ok(StartMode::Help),
[flag, path] if flag == "--view" => Ok(StartMode::View(PathBuf::from(path))), [flag, path] if flag == "--view" => Ok(StartMode::View(PathBuf::from(path))),
[path] if !path.to_string_lossy().starts_with('-') => { [path] if !path.to_string_lossy().starts_with('-') => {
Ok(StartMode::View(PathBuf::from(path))) Ok(StartMode::View(PathBuf::from(path)))
} }
_ => Err(AppError::Usage("usage: tiny-wb [--view] [SCAN.csv]".into())), _ => Err(AppError::Usage(
"usage: tiny-wb [--live | --view SCAN.csv | SCAN.csv]".into(),
)),
} }
} }
@ -49,7 +54,7 @@ fn main() -> Result<(), AppError> {
color_eyre::install()?; color_eyre::install()?;
let mode = parse_start_mode(std::env::args_os().skip(1))?; let mode = parse_start_mode(std::env::args_os().skip(1))?;
if mode == StartMode::Help { if mode == StartMode::Help {
println!("tiny-wb [--view] [SCAN.csv]\n\nWith no CSV, acquire a scan. With a CSV path, open the plot renderer directly."); println!("tiny-wb [--live | --view SCAN.csv | SCAN.csv]\n\nWith no option, acquire one scan. --live repeats complete snapshots until stopped. With a CSV path, open the plot renderer directly.");
return Ok(()); return Ok(());
} }
let config_path = std::env::var_os("TINY_WB_CONFIG") let config_path = std::env::var_os("TINY_WB_CONFIG")
@ -82,8 +87,9 @@ fn main() -> Result<(), AppError> {
.log_to_file(FileSpec::default().directory(&config.logging.directory)) .log_to_file(FileSpec::default().directory(&config.logging.directory))
.write_mode(WriteMode::BufferAndFlush) .write_mode(WriteMode::BufferAndFlush)
.start()?; .start()?;
let live_mode = mode == StartMode::Live;
let mut app = match mode { let mut app = match mode {
StartMode::Acquire => { StartMode::Acquire | StartMode::Live => {
let ports = match config.connection.backend { let ports = match config.connection.backend {
Backend::Serial => serialport::available_ports()?, Backend::Serial => serialport::available_ports()?,
Backend::Tcp => vec![serialport::SerialPortInfo { Backend::Tcp => vec![serialport::SerialPortInfo {
@ -91,7 +97,11 @@ fn main() -> Result<(), AppError> {
port_type: serialport::SerialPortType::Unknown, port_type: serialport::SerialPortType::Unknown,
}], }],
}; };
ui::App::new(ports, config, config_path) if live_mode {
ui::App::live(ports, config, config_path)
} else {
ui::App::new(ports, config, config_path)
}
} }
StartMode::View(path) => ui::App::viewer( StartMode::View(path) => ui::App::viewer(
config, config,
@ -113,6 +123,10 @@ mod tests {
#[test] #[test]
fn command_line_selects_acquisition_help_and_csv_viewer() { fn command_line_selects_acquisition_help_and_csv_viewer() {
assert_eq!(parse_start_mode([]).unwrap(), StartMode::Acquire); assert_eq!(parse_start_mode([]).unwrap(), StartMode::Acquire);
assert_eq!(
parse_start_mode([OsString::from("--live")]).unwrap(),
StartMode::Live
);
assert_eq!( assert_eq!(
parse_start_mode([OsString::from("--help")]).unwrap(), parse_start_mode([OsString::from("--help")]).unwrap(),
StartMode::Help StartMode::Help

View File

@ -9,10 +9,12 @@ use std::{
sync::{Arc, Mutex, MutexGuard}, sync::{Arc, Mutex, MutexGuard},
}; };
use tiny_wb::{ use tiny_wb::{
acquisition::{acquire, ScanEvent}, acquisition::{acquire, acquire_live, ScanEvent},
config::Config, config::Config,
connection::open_connection, connection::open_connection,
export::save_csv, export::save_csv,
live::{TraceBuffer, TraceMode},
protocol::Sample,
protocol::ScanRequest, protocol::ScanRequest,
transport::Shell, transport::Shell,
}; };
@ -54,6 +56,64 @@ struct Progress {
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub(crate) struct ScanState(Arc<Mutex<Progress>>); pub(crate) struct ScanState(Arc<Mutex<Progress>>);
/// Shared repeated-snapshot state for the live terminal screen.
#[derive(Debug, Clone)]
pub(crate) struct LiveState(Arc<Mutex<LiveProgress>>);
/// One coherent live snapshot and its control flags.
#[derive(Debug)]
struct LiveProgress {
/// Worker lifecycle.
status: ScanStatus,
/// Current operation or save result.
message: String,
/// Verbatim device identity.
info: String,
/// Failure retained for the error screen.
error: Option<String>,
/// Bounded raw history and derived traces.
trace: TraceBuffer,
/// Calculation selected by the terminal.
mode: TraceMode,
/// Monotonic renderer invalidation counter.
generation: u64,
/// Graceful cancellation requested by the terminal.
stop_requested: bool,
/// Visible trace captured for the next worker-side intermediate export.
pending_save: Option<Vec<Sample>>,
/// Save requested before the first complete sweep became available.
save_after_first: bool,
}
/// Renderer-owned copy of one derived live trace.
pub(crate) struct LiveSnapshot {
/// Monotonic state generation.
pub(crate) generation: u64,
/// Selected host-side calculation.
pub(crate) mode: TraceMode,
/// Complete sweeps incorporated in the calculation.
pub(crate) sweeps: u64,
/// Plot-ready `(MHz, dBm)` points.
pub(crate) data: Vec<(f64, f64)>,
}
impl Default for LiveState {
fn default() -> Self {
Self(Arc::new(Mutex::new(LiveProgress {
status: ScanStatus::Ready,
message: String::new(),
info: String::new(),
error: None,
trace: TraceBuffer::default(),
mode: TraceMode::Average4,
generation: 0,
stop_requested: false,
pending_save: None,
save_after_first: false,
})))
}
}
impl ScanState { impl ScanState {
/// Recover telemetry after a poisoned lock rather than panic in error rendering. /// Recover telemetry after a poisoned lock rather than panic in error rendering.
fn lock(&self) -> MutexGuard<'_, Progress> { fn lock(&self) -> MutexGuard<'_, Progress> {
@ -125,6 +185,169 @@ impl ScanState {
} }
} }
impl LiveState {
/// Recover shared live state after a poisoned worker lock.
fn lock(&self) -> MutexGuard<'_, LiveProgress> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Reset all bounded history and control flags for a new live run.
pub(crate) fn begin(&self) {
let mut state = self.lock();
*state = LiveProgress {
status: ScanStatus::Running,
message: "Opening live connection".into(),
info: String::new(),
error: None,
trace: TraceBuffer::default(),
mode: TraceMode::Average4,
generation: state.generation.saturating_add(1),
stop_requested: false,
pending_save: None,
save_after_first: false,
};
}
/// Adapt core acquisition events without exposing the terminal to the core.
fn report(&self, event: ScanEvent) {
let mut state = self.lock();
match event {
ScanEvent::Message(message) => state.message = message.into(),
ScanEvent::InstrumentInfo(info) => state.info = info,
ScanEvent::Progress(_) => {}
}
}
/// Incorporate one decoded complete sweep.
fn publish(&self, samples: Vec<Sample>) -> Result<(), tiny_wb::live::LiveTraceError> {
let mut state = self.lock();
state.trace.push(samples)?;
state.generation = state.generation.saturating_add(1);
state.message = format!("Live capture — {} sweeps", state.trace.sweeps());
Ok(())
}
/// Return a rendered trace only when samples or the selected mode changed.
pub(crate) fn snapshot_after(&self, generation: u64) -> Option<LiveSnapshot> {
let state = self.lock();
if state.generation == generation {
return None;
}
state.trace.trace(state.mode).map(|samples| LiveSnapshot {
generation: state.generation,
mode: state.mode,
sweeps: state.trace.sweeps(),
data: samples
.into_iter()
.map(|sample| (sample.frequency_mhz, sample.level_dbm))
.collect(),
})
}
/// Copy the selected calculation for worker-side CSV export.
fn samples(&self) -> Option<Vec<Sample>> {
let state = self.lock();
state.trace.trace(state.mode)
}
/// Select a host-side calculation without discarding its retained history.
pub(crate) fn set_mode(&self, mode: TraceMode) {
let mut state = self.lock();
if state.mode != mode {
state.mode = mode;
state.generation = state.generation.saturating_add(1);
}
}
/// Current host-side calculation.
pub(crate) fn mode(&self) -> TraceMode {
self.lock().mode
}
/// Capture the visible trace for worker-side export after the current sweep.
pub(crate) fn request_save(&self) {
let mut state = self.lock();
if let Some(samples) = state.trace.trace(state.mode) {
state.pending_save = Some(samples);
state.message = "Save requested for the visible buffer".into();
} else {
state.save_after_first = true;
state.message = "Save requested; waiting for the first complete sweep".into();
}
}
/// Consume one captured intermediate export, deferring an early request.
fn take_save_request(&self) -> Option<Vec<Sample>> {
let mut state = self.lock();
if let Some(samples) = state.pending_save.take() {
return Some(samples);
}
if state.save_after_first {
if let Some(samples) = state.trace.trace(state.mode) {
state.save_after_first = false;
return Some(samples);
}
}
None
}
/// Request cancellation after the current sweep completes.
pub(crate) fn request_stop(&self) {
let mut state = self.lock();
state.stop_requested = true;
state.message = "Stopping after the current sweep".into();
}
/// Whether the worker should refrain from starting another snapshot.
fn should_stop(&self) -> bool {
self.lock().stop_requested
}
/// Report a successful intermediate export without stopping capture.
fn saved(&self, path: &std::path::Path) {
self.lock().message = format!("Saved {}; live capture continues", path.display());
}
/// Publish final export and recovery completion together.
fn complete(&self, path: Option<&std::path::Path>) {
let mut state = self.lock();
state.status = ScanStatus::Complete;
state.message = path.map_or_else(
|| "Live capture stopped before the first complete sweep".into(),
|path| format!("Saved {} and stopped live capture", path.display()),
);
}
/// Record a worker failure for the terminal error screen.
pub(crate) fn fail(&self, error: impl std::fmt::Display) {
let mut state = self.lock();
state.error = Some(error.to_string());
state.status = ScanStatus::Failed;
}
/// Current live worker lifecycle.
pub(crate) fn status(&self) -> ScanStatus {
self.lock().status
}
/// Current live operation or save result.
pub(crate) fn message(&self) -> String {
self.lock().message.clone()
}
/// Device identification text received by the live worker.
pub(crate) fn info(&self) -> String {
self.lock().info.clone()
}
/// Live worker failure, when present.
pub(crate) fn error(&self) -> Option<String> {
self.lock().error.clone()
}
}
/// Open one port, acquire through the reusable core, then export valid samples. /// Open one port, acquire through the reusable core, then export valid samples.
pub(crate) fn run_scan( pub(crate) fn run_scan(
state: ScanState, state: ScanState,
@ -157,6 +380,58 @@ pub(crate) fn run_scan(
Ok(()) Ok(())
} }
/// Keep one connection configured while acquiring repeated complete snapshots.
pub(crate) fn run_live(
state: LiveState,
request: ScanRequest,
config: Config,
) -> Result<(), AppError> {
if state.status() == ScanStatus::Ready {
state.begin();
}
config.validate()?;
request
.validate()
.map_err(tiny_wb::acquisition::AcquisitionError::from)?;
let port = open_connection(&config)?;
let mut shell = Shell::new(port, config.serial.max_response_bytes);
let callback_state = state.clone();
let output = config.output.clone();
acquire_live(
&mut shell,
&request,
&config.scan,
&config.serial,
|| state.should_stop(),
move |samples| {
if let Err(error) = callback_state.publish(samples) {
callback_state.fail(error);
callback_state.request_stop();
return;
}
if let Some(samples) = callback_state.take_save_request() {
match save_csv(&samples, &output) {
Ok(path) => callback_state.saved(&path),
Err(error) => {
callback_state.fail(error);
callback_state.request_stop();
}
}
}
},
|event| state.report(event),
)?;
if let Some(error) = state.error() {
return Err(AppError::Live(error));
}
let saved = match state.samples() {
Some(samples) => Some(save_csv(&samples, &config.output)?),
None => None,
};
state.complete(saved.as_deref());
Ok(())
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -197,4 +472,36 @@ mod tests {
assert!(state.error().is_none()); assert!(state.error().is_none());
assert!(state.take_samples().is_err()); assert!(state.take_samples().is_err());
} }
#[test]
fn live_state_publishes_modes_and_control_requests_coherently() {
let state = LiveState::default();
state.begin();
state
.publish(vec![Sample {
frequency_mhz: 240.0,
level_dbm: -64.0,
}])
.unwrap();
let snapshot = state.snapshot_after(0).unwrap();
assert_eq!(snapshot.mode, TraceMode::Average4);
assert_eq!(snapshot.sweeps, 1);
assert_eq!(snapshot.data, vec![(240.0, -64.0)]);
assert!(state.snapshot_after(snapshot.generation).is_none());
state.set_mode(TraceMode::MaxHold);
assert_eq!(state.mode(), TraceMode::MaxHold);
assert!(state.snapshot_after(snapshot.generation).is_some());
state.request_save();
state
.publish(vec![Sample {
frequency_mhz: 240.0,
level_dbm: -20.0,
}])
.unwrap();
assert_eq!(state.take_save_request().unwrap()[0].level_dbm, -64.0);
assert!(state.take_save_request().is_none());
state.request_stop();
assert!(state.should_stop());
}
} }

View File

@ -21,7 +21,7 @@ use state::{
}; };
use std::{path::PathBuf, thread, time::Duration}; use std::{path::PathBuf, thread, time::Duration};
use strum::EnumCount; use strum::EnumCount;
use tiny_wb::{config::Config, protocol::ScanRequest}; use tiny_wb::{config::Config, live::TraceMode, protocol::ScanRequest};
impl App { impl App {
/// Construct UI state from already validated settings; no file I/O here. /// Construct UI state from already validated settings; no file I/O here.
@ -53,6 +53,10 @@ impl App {
), ),
repeat: NumericInput::new(config.repeat, 1, 1, config.scan.max_repeat), repeat: NumericInput::new(config.repeat, 1, 1, config.scan.max_repeat),
scan_state: ScanState::default(), scan_state: ScanState::default(),
live_state: scan::LiveState::default(),
live_enabled: false,
live_generation: 0,
live_exit_requested: false,
plot: None, plot: None,
last_scan: None, last_scan: None,
can_acquire: true, can_acquire: true,
@ -61,6 +65,13 @@ impl App {
} }
} }
/// Construct an acquisition UI whose confirmed settings launch live mode.
pub(crate) fn live(info: Vec<SerialPortInfo>, config: Config, config_path: PathBuf) -> Self {
let mut app = Self::new(info, config, config_path);
app.live_enabled = true;
app
}
/// Construct the renderer directly from an already parsed CSV plot. /// Construct the renderer directly from an already parsed CSV plot.
pub(crate) fn viewer(config: Config, source: PathBuf, data: Vec<(f64, f64)>) -> Self { pub(crate) fn viewer(config: Config, source: PathBuf, data: Vec<(f64, f64)>) -> Self {
let mut app = Self::new(Vec::new(), config, PathBuf::new()); let mut app = Self::new(Vec::new(), config, PathBuf::new());
@ -81,6 +92,7 @@ impl App {
self.scan_state.fail(error); self.scan_state.fail(error);
self.flow_state = AppState::Error; self.flow_state = AppState::Error;
} }
self.refresh_live();
let mut draw_error = None; let mut draw_error = None;
terminal.draw(|frame| { terminal.draw(|frame| {
draw_error = self.draw(frame).err(); draw_error = self.draw(frame).err();
@ -88,6 +100,9 @@ impl App {
if let Some(error) = draw_error { if let Some(error) = draw_error {
return Err(error.into()); return Err(error.into());
} }
if self.should_quit {
break;
}
let timeout = Duration::from_millis(self.config.ui.poll_interval_ms); let timeout = Duration::from_millis(self.config.ui.poll_interval_ms);
if event::poll(timeout)? { if event::poll(timeout)? {
if let Event::Key(key) = event::read()? { if let Event::Key(key) = event::read()? {
@ -96,9 +111,6 @@ impl App {
self.flow_state = AppState::Error; self.flow_state = AppState::Error;
}; };
}; };
if self.should_quit {
break;
}
} }
} }
Ok(()) Ok(())
@ -153,6 +165,9 @@ impl App {
if matches!(self.flow_state, AppState::Complete) { if matches!(self.flow_state, AppState::Complete) {
return self.handle_plot_key(key.code); return self.handle_plot_key(key.code);
} }
if matches!(self.flow_state, AppState::Live) {
return self.handle_live_key(key.code);
}
if self.handle_numeric_editor_key(key.code) { if self.handle_numeric_editor_key(key.code) {
return Ok(()); return Ok(());
} }
@ -171,6 +186,24 @@ impl App {
Ok(()) Ok(())
} }
/// Apply live processing, save and graceful-stop controls.
fn handle_live_key(&mut self, code: KeyCode) -> Result<(), UiError> {
match code {
KeyCode::Char('q') | KeyCode::Esc | KeyCode::Enter => {
self.live_exit_requested = true;
self.live_state.request_stop();
}
KeyCode::Char('s') => self.live_state.request_save(),
KeyCode::Char(key) => {
if let Some(mode) = TraceMode::from_key(key) {
self.live_state.set_mode(mode);
}
}
_ => {}
}
Ok(())
}
/// Give an active direct-entry editor exclusive use of keys and start one on a digit. /// Give an active direct-entry editor exclusive use of keys and start one on a digit.
fn handle_numeric_editor_key(&mut self, code: KeyCode) -> bool { fn handle_numeric_editor_key(&mut self, code: KeyCode) -> bool {
let input = match self.flow_state { let input = match self.flow_state {
@ -260,6 +293,7 @@ impl App {
}, },
AppState::Complete => (), AppState::Complete => (),
AppState::Scanning => (), AppState::Scanning => (),
AppState::Live => (),
AppState::Error => (), AppState::Error => (),
} }
} }
@ -299,6 +333,7 @@ impl App {
} }
AppState::Complete => None, AppState::Complete => None,
AppState::Scanning => None, AppState::Scanning => None,
AppState::Live => None,
AppState::Error => None, AppState::Error => None,
} { } {
self.flow_state = s; self.flow_state = s;
@ -322,6 +357,7 @@ impl App {
self.should_quit = true; self.should_quit = true;
} }
AppState::Scanning => {} AppState::Scanning => {}
AppState::Live => {}
AppState::Error => { AppState::Error => {
self.should_quit = true; self.should_quit = true;
} }
@ -343,7 +379,11 @@ impl App {
.map_err(tiny_wb::acquisition::AcquisitionError::from) .map_err(tiny_wb::acquisition::AcquisitionError::from)
.map_err(AppError::from)?; .map_err(AppError::from)?;
config.save(&self.config_path).map_err(AppError::from)?; config.save(&self.config_path).map_err(AppError::from)?;
self.launch_scan(request, config) if self.live_enabled {
self.launch_live(request, config)
} else {
self.launch_scan(request, config)
}
} }
/// Relaunch the exact request and settings used by the previous scan. /// Relaunch the exact request and settings used by the previous scan.
@ -369,6 +409,22 @@ impl App {
}); });
Ok(()) Ok(())
} }
/// Reset live history and start one persistent repeated-snapshot worker.
fn launch_live(&mut self, request: ScanRequest, config: Config) -> Result<(), UiError> {
self.live_state.begin();
self.live_generation = 0;
self.live_exit_requested = false;
self.flow_state = AppState::Live;
self.plot = None;
let live = self.live_state.clone();
thread::spawn(move || {
if let Err(error) = scan::run_live(live.clone(), request, config) {
live.fail(error);
}
});
Ok(())
}
/// Transfer completed samples once and keep rendering free of transitions. /// Transfer completed samples once and keep rendering free of transitions.
fn refresh_scan(&mut self) -> Result<(), UiError> { fn refresh_scan(&mut self) -> Result<(), UiError> {
if matches!(self.flow_state, AppState::Scanning) { if matches!(self.flow_state, AppState::Scanning) {
@ -384,6 +440,34 @@ impl App {
} }
Ok(()) Ok(())
} }
/// Copy at most one newly completed live trace into renderer-owned storage.
fn refresh_live(&mut self) {
if !matches!(self.flow_state, AppState::Live) {
return;
}
if let Some(snapshot) = self.live_state.snapshot_after(self.live_generation) {
self.live_generation = snapshot.generation;
let label = format!("Live {} — {} sweeps", snapshot.mode, snapshot.sweeps);
if let Some(plot) = self.plot.as_mut() {
plot.replace_data(label, snapshot.data);
} else {
self.plot = Some(Plot::new(label, snapshot.data));
}
}
match self.live_state.status() {
ScanStatus::Failed => {
self.scan_state.fail(
self.live_state
.error()
.unwrap_or_else(|| "live capture failed".into()),
);
self.flow_state = AppState::Error;
}
ScanStatus::Complete if self.live_exit_requested => self.should_quit = true,
ScanStatus::Ready | ScanStatus::Running | ScanStatus::Complete => {}
}
}
} }
/// Renderer action resolved from configured key names. /// Renderer action resolved from configured key names.
@ -608,6 +692,24 @@ mod tests {
assert!(matches!(viewer.flow_state, AppState::Complete)); assert!(matches!(viewer.flow_state, AppState::Complete));
} }
#[test]
fn live_keys_switch_mode_and_request_a_graceful_exit() {
let mut app = app();
app.flow_state = AppState::Live;
app.live_state.begin();
app.handle_start_keys(KeyEvent::new(KeyCode::Char('6'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.live_state.mode(), TraceMode::MinDecay);
app.handle_start_keys(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE))
.unwrap();
assert!(app.live_exit_requested);
assert!(
!app.should_quit,
"worker recovery and final save must finish first"
);
assert_eq!(app.live_state.message(), "Stopping after the current sweep");
}
#[test] #[test]
fn every_screen_renders_without_a_physical_terminal() { fn every_screen_renders_without_a_physical_terminal() {
for (width, height) in [(120, 40), (40, 10), (1, 1)] { for (width, height) in [(120, 40), (40, 10), (1, 1)] {
@ -623,6 +725,7 @@ mod tests {
AppState::SelectingScan(SelectedScan::Points), AppState::SelectingScan(SelectedScan::Points),
AppState::SelectingScan(SelectedScan::Repeat), AppState::SelectingScan(SelectedScan::Repeat),
AppState::Scanning, AppState::Scanning,
AppState::Live,
AppState::Complete, AppState::Complete,
AppState::Error, AppState::Error,
] { ] {

View File

@ -11,7 +11,7 @@ use strum::FromRepr;
use crate::{ use crate::{
error::{AppError, UiError}, error::{AppError, UiError},
scan::ScanState, scan::{LiveState, ScanState},
}; };
use tiny_wb::{config::Config, protocol::ScanRequest}; use tiny_wb::{config::Config, protocol::ScanRequest};
@ -45,6 +45,14 @@ pub(crate) struct App {
pub(crate) repeat: NumericInput, pub(crate) repeat: NumericInput,
/// Shared acquisition telemetry; request settings are passed separately. /// Shared acquisition telemetry; request settings are passed separately.
pub(crate) scan_state: ScanState, pub(crate) scan_state: ScanState,
/// Shared repeated-snapshot state used only by `--live` sessions.
pub(crate) live_state: LiveState,
/// Whether scans launched from the settings screen should run continuously.
pub(crate) live_enabled: bool,
/// Last live generation copied into the plot.
pub(crate) live_generation: u64,
/// Whether the UI should exit after live recovery and final export.
pub(crate) live_exit_requested: bool,
/// Validated settings retained when the selection is saved. /// Validated settings retained when the selection is saved.
pub(crate) config: Config, pub(crate) config: Config,
/// Explicit settings path selected at startup. /// Explicit settings path selected at startup.
@ -78,6 +86,18 @@ impl Plot {
viewport, viewport,
} }
} }
/// Replace samples without resetting a compatible live viewport.
pub(crate) fn replace_data(&mut self, label: impl Into<String>, data: Vec<(f64, f64)>) {
let replacement = FrequencyViewport::from_samples(&data);
if self.viewport.full_min != replacement.full_min
|| self.viewport.full_max != replacement.full_max
{
self.viewport = replacement;
}
self.label = label.into();
self.data = data;
}
} }
/// Horizontal chart bounds with zoom and pan clamped to the source data. /// Horizontal chart bounds with zoom and pan clamped to the source data.
@ -289,6 +309,8 @@ pub(crate) enum AppState {
Complete, Complete,
/// Acquisition and export progress. /// Acquisition and export progress.
Scanning, Scanning,
/// Repeated complete snapshots displayed while acquisition continues.
Live,
/// Error window /// Error window
Error, Error,
} }

View File

@ -19,11 +19,82 @@ impl App {
AppState::SelectingConnection(_) => self.draw_config(frame), AppState::SelectingConnection(_) => self.draw_config(frame),
AppState::SelectingScan(_) => self.draw_final_config(frame), AppState::SelectingScan(_) => self.draw_final_config(frame),
AppState::Scanning => self.draw_progress(frame), AppState::Scanning => self.draw_progress(frame),
AppState::Live => self.draw_live(frame),
AppState::Complete => self.draw_end_window(frame), AppState::Complete => self.draw_end_window(frame),
AppState::Error => self.draw_error(frame), AppState::Error => self.draw_error(frame),
} }
} }
/// Render the newest complete live snapshot while the worker continues.
fn draw_live(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> {
let [_, main, _] = Layout::horizontal([
Constraint::Min(2),
Constraint::Percentage(96),
Constraint::Min(2),
])
.areas(frame.area());
let [status_area, graph_area, footer_area] = Layout::vertical([
Constraint::Length(4),
Constraint::Min(4),
Constraint::Length(2),
])
.areas(main);
let status = format!(
"{} — {}\n{}",
self.live_state.mode(),
self.live_state.message(),
self.live_state.info()
);
frame.render_widget(
Paragraph::new(status)
.wrap(Wrap { trim: true })
.block(Block::bordered().title("Live capture")),
status_area,
);
if let Some(plot) = self.plot.as_ref() {
let bounds = plot.viewport.bounds();
let span = bounds[1] - bounds[0];
let midpoint = (bounds[0] + bounds[1]) / 2.0;
let chart = Chart::new(vec![Dataset::default()
.marker(Marker::Dot)
.graph_type(GraphType::Scatter)
.style(Style::new().yellow())
.data(&plot.data)])
.x_axis(
Axis::default()
.title("Frequency (MHz)")
.bounds(bounds)
.labels([
format_frequency(bounds[0], span),
format_frequency(midpoint, span),
format_frequency(bounds[1], span),
]),
)
.y_axis(
Axis::default()
.title("Level (dBm)")
.bounds([self.config.ui.chart_min_dbm, self.config.ui.chart_max_dbm]),
);
frame.render_widget(chart, graph_area);
} else {
frame.render_widget(
Paragraph::new("Waiting for the first complete sweep…")
.centered()
.block(Block::bordered()),
graph_area,
);
}
frame.render_widget(
Paragraph::new(
"1 avg4 · 2 avg16 · 3 max hold · 4 max decay · 5 min hold · 6 min decay · s save · q stop+save",
)
.centered()
.wrap(Wrap { trim: true }),
footer_area,
);
Ok(())
}
/// Render scan settings with the focused field highlighted. /// Render scan settings with the focused field highlighted.
fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> { fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), UiError> {
let [_, spaced, _] = Layout::horizontal([ let [_, spaced, _] = Layout::horizontal([

13
task.md
View File

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