feat: expose portable library connections and mock tinySA devices
This commit is contained in:
parent
8f9059aeff
commit
b0be23639f
43
Cargo.toml
43
Cargo.toml
|
|
@ -12,15 +12,46 @@ pkg-url = "{ repo }/releases/download/{ version }/{ name }-{ target }-v{ version
|
||||||
pkg-fmt = "tgz"
|
pkg-fmt = "tgz"
|
||||||
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
|
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["tui", "serial"]
|
||||||
|
# Core integrations can disable defaults to avoid terminal/native serial dependencies.
|
||||||
|
tui = ["dep:color-eyre", "dep:flexi_logger", "dep:ratatui", "dep:strum", "dep:winresource"]
|
||||||
|
serial = ["dep:serialport"]
|
||||||
|
mock = []
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "tiny_wb"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "tiny-wb"
|
||||||
|
path = "src/main.rs"
|
||||||
|
required-features = ["tui", "serial"]
|
||||||
|
|
||||||
|
[[test]]
|
||||||
|
name = "startup"
|
||||||
|
path = "tests/startup.rs"
|
||||||
|
required-features = ["tui", "serial"]
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "mock-tinysa-server"
|
||||||
|
path = "examples/mock-tinysa-server.rs"
|
||||||
|
required-features = ["mock"]
|
||||||
|
|
||||||
|
[[test]]
|
||||||
|
name = "mock_device"
|
||||||
|
path = "tests/mock_device.rs"
|
||||||
|
required-features = ["mock"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
chrono = "0.4.38"
|
chrono = "0.4.38"
|
||||||
color-eyre = "0.6.3"
|
color-eyre = { version = "0.6.3", optional = true }
|
||||||
flexi_logger = "0.29.0"
|
flexi_logger = { version = "0.29.0", optional = true }
|
||||||
log = "0.4.22"
|
log = "0.4.22"
|
||||||
ratatui = "=0.30.2"
|
ratatui = { version = "=0.30.2", optional = true }
|
||||||
serde = { version = "1.0.210", features = ["derive"] }
|
serde = { version = "1.0.210", features = ["derive"] }
|
||||||
serialport = "4.5.0"
|
serialport = { version = "4.5.0", optional = true }
|
||||||
strum = { version = "0.28.0", features = ["derive"] }
|
strum = { version = "0.28.0", features = ["derive"], optional = true }
|
||||||
thiserror = "2.0.21"
|
thiserror = "2.0.21"
|
||||||
toml = "0.8.19"
|
toml = "0.8.19"
|
||||||
|
|
||||||
|
|
@ -54,4 +85,4 @@ incremental = false
|
||||||
panic = "abort"
|
panic = "abort"
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
winresource = "=0.1.17"
|
winresource = { version = "=0.1.17", optional = true }
|
||||||
|
|
|
||||||
30
build.rs
30
build.rs
|
|
@ -1,23 +1,23 @@
|
||||||
use {
|
//! Application-only resources; library-only builds need neither Git nor windres.
|
||||||
std::{env, io},
|
|
||||||
winresource::WindowsResource,
|
|
||||||
};
|
|
||||||
|
|
||||||
use std::process::Command;
|
#[cfg(feature = "tui")]
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
fn main() -> io::Result<()> {
|
if std::env::var_os("CARGO_CFG_WINDOWS").is_some() {
|
||||||
if env::var_os("CARGO_CFG_WINDOWS").is_some() {
|
winresource::WindowsResource::new()
|
||||||
WindowsResource::new()
|
|
||||||
// This path can be absolute, or relative to your crate root.
|
|
||||||
.set_icon("assets/icon.ico")
|
.set_icon("assets/icon.ico")
|
||||||
.compile()?;
|
.compile()?;
|
||||||
}
|
}
|
||||||
|
// Source archives and path dependencies may not have Git installed/a checkout.
|
||||||
let output = Command::new("git")
|
let revision = std::process::Command::new("git")
|
||||||
.args(["rev-parse", "--short", "HEAD"])
|
.args(["rev-parse", "--short", "HEAD"])
|
||||||
.output()
|
.output()
|
||||||
.unwrap();
|
.ok()
|
||||||
let git_hash = String::from_utf8(output.stdout).unwrap();
|
.filter(|output| output.status.success())
|
||||||
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
|
.and_then(|output| String::from_utf8(output.stdout).ok())
|
||||||
|
.unwrap_or_else(|| "unknown".into());
|
||||||
|
println!("cargo:rustc-env=GIT_HASH={}", revision.trim());
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "tui"))]
|
||||||
|
fn main() {}
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,12 @@ stop_frequency = 960
|
||||||
points = 10001
|
points = 10001
|
||||||
repeat = 1
|
repeat = 1
|
||||||
|
|
||||||
|
[connection]
|
||||||
|
backend = "serial"
|
||||||
|
# Numeric socket address only; used by the TCP bridge/mock, not by native tinySA USB.
|
||||||
|
tcp_address = "127.0.0.1:7355"
|
||||||
|
tcp_timeout_ms = 3000
|
||||||
|
|
||||||
[serial]
|
[serial]
|
||||||
# Timeout for each blocking serial read, not a whole-scan deadline.
|
# Timeout for each blocking serial read, not a whole-scan deadline.
|
||||||
timeout_ms = 3000
|
timeout_ms = 3000
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
# Synthetic Basic; only the documented subset in docs/mock-device.md is implemented.
|
||||||
|
model = "basic"
|
||||||
|
echo = true
|
||||||
|
read_chunk_bytes = 7
|
||||||
|
write_chunk_bytes = 3
|
||||||
|
max_points = 10001
|
||||||
|
floor_dbm = -96.0
|
||||||
|
peak_dbm = -32.0
|
||||||
|
peak_frequency_hz = 300000000
|
||||||
|
peak_width_hz = 10000000
|
||||||
|
fault = "none"
|
||||||
|
fault_command = "scanraw"
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
# Run the standard TUI against the Basic mock server, without USB hardware.
|
||||||
|
points = 101
|
||||||
|
[connection]
|
||||||
|
backend = "tcp"
|
||||||
|
tcp_address = "127.0.0.1:7355"
|
||||||
|
tcp_timeout_ms = 3000
|
||||||
|
[serial]
|
||||||
|
command_delay_ms = 0
|
||||||
|
settle_delay_ms = 0
|
||||||
|
scan_delay_ms = 0
|
||||||
|
[scan]
|
||||||
|
frequency_axis = "firmware"
|
||||||
|
legacy_pre_scan = false
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
# Synthetic Ultra identity/syntax. This does NOT enable Ultra support in the UI.
|
||||||
|
model = "ultra"
|
||||||
|
echo = true
|
||||||
|
read_chunk_bytes = 7
|
||||||
|
write_chunk_bytes = 3
|
||||||
|
max_points = 10001
|
||||||
|
# Simulation ceiling only; detect real model/firmware capabilities separately.
|
||||||
|
ultra_max_hz = 6000000000
|
||||||
|
floor_dbm = -96.0
|
||||||
|
peak_dbm = -32.0
|
||||||
|
peak_frequency_hz = 1000000000
|
||||||
|
peak_width_hz = 10000000
|
||||||
|
fault = "none"
|
||||||
|
fault_command = "scanraw"
|
||||||
|
|
@ -14,11 +14,14 @@ widgets, port discovery, worker threads, or the application's working directory.
|
||||||
| `src/storage.rs` | Same-directory atomic replacement for saved configuration. |
|
| `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/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/transport.rs` | Buffered `Read + Write` shell I/O, complete command writes, text prompts and length-delimited raw frames. |
|
||||||
|
| `src/connection.rs` | Runtime serial/TCP adapter; native serial is optional. |
|
||||||
|
| `src/mock/` | Opt-in bounded device simulation and stream server. |
|
||||||
|
| `examples/mock-tinysa-server.rs` | Portable TCP listener for the mock, outside release binaries. |
|
||||||
| `src/acquisition.rs` | Command ordering, progress events, frame decoding and resume attempts. |
|
| `src/acquisition.rs` | Command ordering, progress events, frame decoding and resume attempts. |
|
||||||
| `src/export.rs` | CSV serialization to a writer and collision-safe file export. |
|
| `src/export.rs` | CSV serialization to a writer and collision-safe file export. |
|
||||||
| `src/main.rs` | Load configuration, start diagnostics, enumerate ports and manage terminal lifetime. |
|
| `src/main.rs` | Load configuration, start diagnostics, enumerate ports 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 serial port, 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. |
|
||||||
| `src/ui/state.rs` | UI state, configured port/baud choices and bounded numeric input. |
|
| `src/ui/state.rs` | UI state, configured port/baud choices and bounded numeric input. |
|
||||||
| `src/ui/view.rs` | Ratatui rendering and selection styling. |
|
| `src/ui/view.rs` | Ratatui rendering and selection styling. |
|
||||||
|
|
@ -34,9 +37,9 @@ embedded defaults + runtime overrides -> validated Config
|
||||||
|
|
|
|
||||||
ScanRequest (Hz) + selected Config
|
ScanRequest (Hz) + selected Config
|
||||||
|
|
|
|
||||||
serial worker
|
connection worker
|
||||||
|
|
|
|
||||||
Shell<SerialPort> -> acquisition
|
Shell<Connection> -> acquisition
|
||||||
|
|
|
|
||||||
decode_frame -> Vec<Sample>
|
decode_frame -> Vec<Sample>
|
||||||
|
|
|
|
||||||
|
|
@ -124,9 +127,9 @@ See [configuration](configuration.md) for settings, paths and exact behavior.
|
||||||
UI tests on Ratatui's in-memory backend. See [testing](testing.md).
|
UI tests on Ratatui's in-memory backend. See [testing](testing.md).
|
||||||
- Settings change policy and timing; wire delimiters, fixed-point scaling and
|
- Settings change policy and timing; wire delimiters, fixed-point scaling and
|
||||||
command grammar remain protocol invariants.
|
command grammar remain protocol invariants.
|
||||||
- Responses are still not parsed into explicit success/error acknowledgments;
|
- Known error/usage replies reject configuration commands, but responses are
|
||||||
an echo-only identity reply can appear nonempty. Prompt arrival is not proof
|
not a complete typed acknowledgement protocol. An echo-only identity can
|
||||||
that a mutating command was accepted.
|
appear nonempty; prompt arrival alone is not proof of acceptance.
|
||||||
- Serial timeouts are per-read idle timeouts, not a whole-transaction deadline.
|
- Serial timeouts are per-read idle timeouts, not a whole-transaction deadline.
|
||||||
Cancellation/abort and complete device-state restoration remain future work.
|
Cancellation/abort and complete device-state restoration remain future work.
|
||||||
Quitting during a scan can terminate the worker before its resume attempt.
|
Quitting during a scan can terminate the worker before its resume attempt.
|
||||||
|
|
@ -141,3 +144,6 @@ buffered framing instead of a separate direct `memchr` dependency. Transitive
|
||||||
`memchr` use elsewhere in the graph is unrelated. Serde/TOML handle settings;
|
`memchr` use elsewhere in the graph is unrelated. Serde/TOML handle settings;
|
||||||
serialport, Ratatui, chrono, log/flexi_logger, color-eyre and thiserror retain
|
serialport, Ratatui, chrono, log/flexi_logger, color-eyre and thiserror retain
|
||||||
their device, presentation, timestamp and error-reporting roles.
|
their device, presentation, timestamp and error-reporting roles.
|
||||||
|
|
||||||
|
Library consumers can omit terminal and serial dependencies; see [feature selection](library.md).
|
||||||
|
The [mock](mock-device.md) uses the same shell/acquisition code over memory or TCP.
|
||||||
|
|
|
||||||
|
|
@ -76,3 +76,13 @@ target instrument; hardware validation remains necessary.
|
||||||
Protocol delimiters, fixed-point scaling, command grammar and Basic input-path
|
Protocol delimiters, fixed-point scaling, command grammar and Basic input-path
|
||||||
limits remain code invariants. Configuration cannot turn a Basic-only client
|
limits remain code invariants. Configuration cannot turn a Basic-only client
|
||||||
into an Ultra-compatible one by increasing a numeric limit.
|
into an Ultra-compatible one by increasing a numeric limit.
|
||||||
|
|
||||||
|
## Connection backends
|
||||||
|
|
||||||
|
`[connection] backend = "serial"` preserves USB behavior. Select `"tcp"` with
|
||||||
|
`tcp_address = "127.0.0.1:7355"` and `tcp_timeout_ms = 3000` for an explicit
|
||||||
|
mock/bridge. The address must be numeric IPv4/IPv6 with a nonzero port; timeout
|
||||||
|
is 1–600,000 ms and applies to connect/read/write operations. All backend fields
|
||||||
|
are validated, including inactive ones. TCP bypasses USB enumeration and ignores
|
||||||
|
serial port/baud selections; protocol pacing still uses `[serial]` timing fields.
|
||||||
|
See the [mock client template](../config/mock-client.toml) and [mock guide](mock-device.md).
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,59 @@
|
||||||
|
# Rust library integration
|
||||||
|
|
||||||
|
The package builds both `tiny_wb` (Rust library) and `tiny-wb` (terminal app).
|
||||||
|
Rust 1.88 or newer is required. To integrate a checkout without terminal, serial,
|
||||||
|
libudev or Windows resource dependencies:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
tiny-wb = { path = "../tiny-wb", default-features = false }
|
||||||
|
```
|
||||||
|
|
||||||
|
| Cargo feature | Purpose |
|
||||||
|
| --- | --- |
|
||||||
|
| no features | Configuration, protocol, shell, Basic acquisition, CSV, TCP adapter |
|
||||||
|
| `serial` | Native USB/serial adapter |
|
||||||
|
| `tui` | Terminal dependencies and application build resources |
|
||||||
|
| `mock` | In-memory simulator and stream server; no additional dependencies |
|
||||||
|
| default | `tui` + `serial`, preserving the existing application |
|
||||||
|
|
||||||
|
The application requires both default features. Build only the library with
|
||||||
|
`cargo build --locked --lib --no-default-features`. This is a Rust API, not a
|
||||||
|
stable C ABI, shared-library binding or published crates.io compatibility promise.
|
||||||
|
Mock support is opt-in; the server is a Cargo example, preserving the existing
|
||||||
|
single-binary release artifact contract.
|
||||||
|
|
||||||
|
`Shell<T>` accepts any synchronous `Read + Write` stream. Use
|
||||||
|
`connection::open_connection(&config)` for configured serial/TCP connections,
|
||||||
|
or inject your own adapter. Transport deadlines belong to the adapter; an
|
||||||
|
arbitrary blocking `Read` implementation cannot be interrupted by the shell.
|
||||||
|
`acquisition::acquire` accepts a validated Basic `ScanRequest`, scan/timing
|
||||||
|
settings and a progress callback, and returns samples without opening files.
|
||||||
|
`export::write_csv` writes those samples to any writer.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use tiny_wb::{config::Config, connection::open_connection,
|
||||||
|
acquisition::acquire, protocol::ScanRequest, transport::Shell};
|
||||||
|
|
||||||
|
fn scan(config: &Config) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
config.validate()?;
|
||||||
|
let mut shell = Shell::new(open_connection(config)?, 65_536);
|
||||||
|
let request = ScanRequest {
|
||||||
|
start_hz: 240_000_000, stop_hz: 960_000_000, points: 101, repeat: 1,
|
||||||
|
};
|
||||||
|
let samples = acquire(&mut shell, &request, &config.scan, &config.serial, |_| {})?;
|
||||||
|
tiny_wb::export::write_csv(&mut std::io::stdout(), &samples, true)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Frequencies in requests are Hz; samples expose MHz and dBm. Keep the decoding
|
||||||
|
zero offset and frequency-axis convention explicit. Acquisition attempts
|
||||||
|
`resume` after every attempted pause and preserves both errors if recovery
|
||||||
|
fails. It does not restore all device settings. Known `error:`, `usage:` and
|
||||||
|
`unknown command` text replies reject configuration commands; this is not
|
||||||
|
universal firmware acknowledgement or automatic capability detection.
|
||||||
|
|
||||||
|
See [the mock guide](mock-device.md) for deterministic integration tests and
|
||||||
|
[the roadmap](roadmap.md) for the model-aware API still needed for Ultra.
|
||||||
|
Generate API documentation with `cargo doc --no-default-features --features mock --no-deps`.
|
||||||
|
|
@ -0,0 +1,123 @@
|
||||||
|
# Mock tinySA device
|
||||||
|
|
||||||
|
The optional `mock` feature provides a deterministic in-memory duplex stream
|
||||||
|
and a TCP server backed by the same device model. Standard `Read + Write`
|
||||||
|
keeps this portable without pseudo-terminal pairs, virtual COM drivers or
|
||||||
|
privileged serial setup. TCP is a mock/bridge transport, not a native tinySA
|
||||||
|
network feature. Simulated success is not hardware validation.
|
||||||
|
|
||||||
|
## Run the server and application
|
||||||
|
|
||||||
|
From the checkout, start the server:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo run --locked --no-default-features --features mock --example mock-tinysa-server -- --config config/mock-basic.toml
|
||||||
|
```
|
||||||
|
|
||||||
|
In a second terminal, copy the client template to a writable settings file
|
||||||
|
outside the checkout, then point `TINY_WB_CONFIG` at that copy:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp config/mock-client.toml /tmp/tiny-wb-mock-client.toml
|
||||||
|
TINY_WB_CONFIG=/tmp/tiny-wb-mock-client.toml cargo run --locked --bin tiny-wb
|
||||||
|
```
|
||||||
|
|
||||||
|
On Windows, copy the template to a chosen temporary file and set
|
||||||
|
`$env:TINY_WB_CONFIG` in PowerShell before running Cargo. The app saves settings
|
||||||
|
to this path; do not use the tracked template as the runtime file. The connection
|
||||||
|
screen offers `tcp://127.0.0.1:7355` without enumerating USB devices. Serial port
|
||||||
|
and baud selections have no effect on a TCP connection. Successful scans still
|
||||||
|
write CSV to the configured export directory.
|
||||||
|
|
||||||
|
Options: `--bind IP:port` (default `127.0.0.1:7355`), `--config FILE`, `--once`,
|
||||||
|
`--help`. Port zero asks the OS for a free port; the actual endpoint is printed.
|
||||||
|
Each accepted connection gets fresh state. The example serves one client at a
|
||||||
|
time; disconnected/error sessions allow the next client. `--once` exits after
|
||||||
|
one session, returning failure for session I/O errors. The library's
|
||||||
|
`serve_connection` lets integrations supply their own listener and concurrency.
|
||||||
|
Keep this unauthenticated test service on loopback.
|
||||||
|
|
||||||
|
## In-memory integration
|
||||||
|
|
||||||
|
Enable `mock` alongside `default-features = false` in the dependency entry:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use tiny_wb::{mock::{MockConfig, MockStream}, transport::Shell};
|
||||||
|
use std::time::Duration;
|
||||||
|
let mut device = MockStream::new(MockConfig::default()).unwrap();
|
||||||
|
{
|
||||||
|
let mut shell = Shell::new(&mut device, 65_536);
|
||||||
|
shell.synchronize().unwrap();
|
||||||
|
shell.command_checked("pause", Duration::ZERO, Duration::ZERO).unwrap();
|
||||||
|
}
|
||||||
|
assert!(device.state().paused);
|
||||||
|
```
|
||||||
|
|
||||||
|
`tests/mock_device.rs` runs production acquisition with one-byte reads/writes,
|
||||||
|
both echo modes, legacy preparation enabled/disabled, recovery faults, and a
|
||||||
|
real loopback TCP connection. Run without terminal or native serial dependencies:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo test --locked --no-default-features --features mock --lib --test mock_device
|
||||||
|
```
|
||||||
|
|
||||||
|
## Supported synthetic behavior
|
||||||
|
|
||||||
|
| Commands | Behavior |
|
||||||
|
| --- | --- |
|
||||||
|
| `version`, `info`, `help` | Explicitly synthetic identity and implemented subset |
|
||||||
|
| `pause`, `resume` | Observable sweep state |
|
||||||
|
| `mode low/high input` | Basic input paths; Basic low stop below 350 MHz, high start at least 240 MHz |
|
||||||
|
| `mode input`, `mode low input` | Ultra mock input syntax; high mode rejected |
|
||||||
|
| `repeat N`, `zero N` | Stored count and fixed-point offset |
|
||||||
|
| `sweep start/stop Hz`, `sweep` | Stored bounds and query |
|
||||||
|
| `scanraw start stop points` | Bounded deterministic binary spectrum |
|
||||||
|
| `scan start stop 290 101` | Current app's compatibility preparation only; no trace data |
|
||||||
|
| `leveloffset`, `vbat`, `usart_cfg`, `threads`, `marker` | Fixed diagnostic fixtures, not measurement implementations |
|
||||||
|
| `lna on/off`, `ultra on/off` | Ultra-only state toggles with no RF effect |
|
||||||
|
|
||||||
|
Other commands or invalid arguments return an explicit error. No calibration,
|
||||||
|
RF output, display capture, arbitrary firmware behavior or complete console
|
||||||
|
emulation is claimed. The Ultra profile exercises command differences; **the
|
||||||
|
production acquisition API and app remain Basic-oriented**. In particular,
|
||||||
|
requests above 960 MHz are still rejected by the production request validator,
|
||||||
|
and Basic high-input commands are rejected by the Ultra mock.
|
||||||
|
|
||||||
|
Samples use `start + index * (stop - start) / points`, a triangular peak above
|
||||||
|
a configured floor, and `round((dBm + zero_offset) * 32)` clamped to `u16`.
|
||||||
|
Frames contain `{`, repeated `x` plus little-endian `u16`, then `}` and a prompt.
|
||||||
|
Use the firmware frequency-axis setting for matching labels. There is no noise,
|
||||||
|
RF physics, timing model or amplitude change from LNA/repeat/Ultra toggles.
|
||||||
|
The mock Ultra ceiling is adjustable synthetic policy, not a model specification.
|
||||||
|
|
||||||
|
## Configuration and failures
|
||||||
|
|
||||||
|
[Basic](../config/mock-basic.toml) and [Ultra](../config/mock-ultra.toml) profiles
|
||||||
|
are partial TOML overrides of `MockConfig::default()`, separate from application
|
||||||
|
settings. Unknown keys and invalid bounds fail before accepting a session.
|
||||||
|
Public Rustdoc lists every field and unit. `session_timeout_ms` defaults to
|
||||||
|
30,000 and bounds server socket reads/writes; client timeouts are independent.
|
||||||
|
`read_chunk_bytes` and `write_chunk_bytes` exercise partial I/O. TCP may coalesce
|
||||||
|
chunks. Commands, frame allocations, pending responses and command history are
|
||||||
|
bounded; integrations must read responses instead of pipelining indefinitely.
|
||||||
|
|
||||||
|
`fault` is one of `none`, `reject`, `timeout`, `disconnect`, `missing_prompt`,
|
||||||
|
`truncated_frame`, `bad_alignment`. It fires once per session on the first
|
||||||
|
`fault_command` (default `scanraw`). Frame corruption requires `scanraw`.
|
||||||
|
Rejection/timeout/disconnect do not execute the command. Missing prompt and
|
||||||
|
frame corruption occur after execution. Timeout drops the response: an empty
|
||||||
|
in-memory read immediately returns `TimedOut`; a TCP client waits for its own
|
||||||
|
socket deadline. Disconnect yields EOF, then `BrokenPipe` on later writes.
|
||||||
|
|
||||||
|
Example fault override:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
fault = "truncated_frame"
|
||||||
|
fault_command = "scanraw"
|
||||||
|
read_chunk_bytes = 1
|
||||||
|
write_chunk_bytes = 1
|
||||||
|
```
|
||||||
|
|
||||||
|
Faults verify error handling and resume attempts, not reliable recovery from
|
||||||
|
all possible real firmware stream states. Hardware transcripts and per-firmware
|
||||||
|
acceptance tests remain [roadmap work](roadmap.md).
|
||||||
|
|
@ -43,3 +43,30 @@ Hardware validation still requires a known model/version, safe RF input, and a
|
||||||
bounded capture of the real command/response sequence. In particular, verify
|
bounded capture of the real command/response sequence. In particular, verify
|
||||||
frequency-axis policy, the legacy preparatory scan, zero-offset acceptance and
|
frequency-axis policy, the legacy preparatory scan, zero-offset acceptance and
|
||||||
resume behavior against the connected firmware before changing their defaults.
|
resume behavior against the connected firmware before changing their defaults.
|
||||||
|
|
||||||
|
## Library feature matrix and mock integration
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo test --locked --no-default-features --lib
|
||||||
|
cargo check --locked --no-default-features --features serial --lib
|
||||||
|
cargo test --locked --no-default-features --features mock --lib --test mock_device
|
||||||
|
```
|
||||||
|
|
||||||
|
The mock suite includes real loopback sockets, so the test environment must
|
||||||
|
permit localhost listeners. Tests use ephemeral ports, bounded socket timeouts
|
||||||
|
and fresh sessions. See [mock scope and faults](mock-device.md). No mock result
|
||||||
|
certifies device command compatibility or RF accuracy. Full hardware acceptance
|
||||||
|
is tracked in the [roadmap](roadmap.md).
|
||||||
|
|
||||||
|
Standalone example CLI and socket smoke test:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo build --locked --no-default-features --features mock --example mock-tinysa-server
|
||||||
|
python3 scripts/test-mock-server.py
|
||||||
|
```
|
||||||
|
|
||||||
|
With a custom `CARGO_TARGET_DIR`, pass its `debug/examples/mock-tinysa-server`
|
||||||
|
executable path to the script (append `.exe` on Windows). This checks argument
|
||||||
|
validation, dynamic-port binding, identity, binary scans and `--once` shutdown.
|
||||||
|
Local Linux validation on 2026-10-04 passed; Windows/macOS runtime, actual
|
||||||
|
hardware and Jenkins execution remain separate unverified acceptance checks.
|
||||||
|
|
|
||||||
|
|
@ -245,3 +245,9 @@ and richer output metadata remain open. Buffered framing, strict record-count
|
||||||
validation, reusable core interfaces and hardware-free regression tests are
|
validation, reusable core interfaces and hardware-free regression tests are
|
||||||
implemented. Real Basic/Ultra transcript fixtures and hardware checks are still
|
implemented. Real Basic/Ultra transcript fixtures and hardware checks are still
|
||||||
needed; see [architecture](architecture.md#extension-points-and-remaining-limits).
|
needed; see [architecture](architecture.md#extension-points-and-remaining-limits).
|
||||||
|
|
||||||
|
## Hardware-free operation
|
||||||
|
|
||||||
|
Use the [mock server](mock-device.md) with the TCP connection backend to run
|
||||||
|
the normal acquisition and CSV workflow without USB hardware. The production
|
||||||
|
app remains Basic-oriented; selecting the Ultra mock does not enable full Ultra support.
|
||||||
|
|
|
||||||
|
|
@ -279,3 +279,11 @@ Use a byte-oriented program and a bounded point count instead.
|
||||||
See [Project architecture](architecture.md#extension-points-and-remaining-limits) for
|
See [Project architecture](architecture.md#extension-points-and-remaining-limits) for
|
||||||
remaining implementation limits and [tiny-wb operations](tiny-wb-operations.md)
|
remaining implementation limits and [tiny-wb operations](tiny-wb-operations.md)
|
||||||
for what users can safely expect today.
|
for what users can safely expect today.
|
||||||
|
|
||||||
|
## Configuration command rejection
|
||||||
|
|
||||||
|
`Shell::command_checked` rejects text lines beginning with `error:`, `usage:`,
|
||||||
|
or `unknown command` (case-insensitive). Acquisition uses it for settings and
|
||||||
|
pause/resume; diagnostic queries retain raw replies. This catches known failure
|
||||||
|
forms, not every firmware-specific error or acknowledgement. Binary scan errors
|
||||||
|
still fail framing/timeout checks. Model-aware replies remain roadmap work.
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
//! Local TCP shell simulator. See docs/mock-device.md for scope and usage.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
io::{self, Write},
|
||||||
|
net::{SocketAddr, TcpListener},
|
||||||
|
path::PathBuf,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
use tiny_wb::mock::{serve_connection, MockConfig};
|
||||||
|
|
||||||
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let mut address: SocketAddr = "127.0.0.1:7355".parse()?;
|
||||||
|
let mut config_path: Option<PathBuf> = None;
|
||||||
|
let mut once = false;
|
||||||
|
let mut args = std::env::args().skip(1);
|
||||||
|
while let Some(arg) = args.next() {
|
||||||
|
match arg.as_str() {
|
||||||
|
"--bind" => address = args.next().ok_or("--bind requires IP:port")?.parse()?,
|
||||||
|
"--config" => {
|
||||||
|
config_path = Some(args.next().ok_or("--config requires a TOML path")?.into())
|
||||||
|
}
|
||||||
|
"--once" => once = true,
|
||||||
|
"--help" => {
|
||||||
|
println!("usage: mock-tinysa-server [--bind IP:port] [--config FILE] [--once]");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
_ => return Err(format!("unknown option: {arg}").into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let config = match config_path {
|
||||||
|
Some(path) => toml::from_str(&std::fs::read_to_string(path)?)?,
|
||||||
|
None => MockConfig::default(),
|
||||||
|
};
|
||||||
|
config.validate()?;
|
||||||
|
let listener = TcpListener::bind(address)?;
|
||||||
|
println!(
|
||||||
|
"Mock tinySA listening on {} ({:?}, synthetic)",
|
||||||
|
listener.local_addr()?,
|
||||||
|
config.model
|
||||||
|
);
|
||||||
|
io::stdout().flush()?;
|
||||||
|
for connection in listener.incoming() {
|
||||||
|
let stream = connection?;
|
||||||
|
stream.set_read_timeout(Some(Duration::from_millis(config.session_timeout_ms)))?;
|
||||||
|
stream.set_write_timeout(Some(Duration::from_millis(config.session_timeout_ms)))?;
|
||||||
|
stream.set_nodelay(true)?;
|
||||||
|
if let Err(error) = serve_connection(stream, config.clone()) {
|
||||||
|
eprintln!("mock session ended: {error}");
|
||||||
|
if once {
|
||||||
|
return Err(error.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if once {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,41 @@
|
||||||
|
"""Smoke-test the built mock server CLI over loopback; run from the repo root.
|
||||||
|
|
||||||
|
Build with cargo build --no-default-features --features mock --example
|
||||||
|
mock-tinysa-server. Optionally pass an executable path (for CARGO_TARGET_DIR).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
exe = sys.argv[1] if len(sys.argv) > 1 else 'target/debug/examples/mock-tinysa-server' + ('.exe' if os.name == 'nt' else '')
|
||||||
|
assert subprocess.run([exe, '--help'], capture_output=True, timeout=5).returncode == 0
|
||||||
|
assert subprocess.run([exe, '--unknown'], capture_output=True, timeout=5).returncode != 0
|
||||||
|
server = subprocess.Popen([exe, '--bind', '127.0.0.1:0', '--config', 'config/mock-basic.toml', '--once'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||||
|
try:
|
||||||
|
line = server.stdout.readline()
|
||||||
|
address = line.split()[4]
|
||||||
|
host, port = address.rsplit(':', 1)
|
||||||
|
with socket.create_connection((host, int(port)), timeout=3) as client:
|
||||||
|
def response():
|
||||||
|
data = b''
|
||||||
|
while not data.endswith(b'ch>'):
|
||||||
|
block = client.recv(4096)
|
||||||
|
assert block, 'unexpected EOF'
|
||||||
|
data += block
|
||||||
|
return data
|
||||||
|
assert response() == b'ch>'
|
||||||
|
client.sendall(b'version\r')
|
||||||
|
assert b'Basic' in response()
|
||||||
|
client.sendall(b'mode high input\r')
|
||||||
|
assert b'error:' not in response()
|
||||||
|
client.sendall(b'scanraw 240000000 360000000 4\r')
|
||||||
|
data = response()
|
||||||
|
frame = data[data.index(b'{'):]
|
||||||
|
assert frame[1] == ord('x') and frame[13] == ord('}')
|
||||||
|
assert server.wait(timeout=5) == 0, server.stderr.read()
|
||||||
|
print('Standalone mock server: CLI validation, dynamic port, synthetic identity, scanraw and --once lifecycle passed.')
|
||||||
|
finally:
|
||||||
|
if server.poll() is None:
|
||||||
|
server.kill()
|
||||||
|
server.wait()
|
||||||
|
|
@ -78,20 +78,20 @@ pub fn acquire<T: Read + Write>(
|
||||||
log::debug!("{command}: {response}");
|
log::debug!("{command}: {response}");
|
||||||
}
|
}
|
||||||
report(ScanEvent::Message("Configuring scan"));
|
report(ScanEvent::Message("Configuring scan"));
|
||||||
shell.command(&format!("repeat {}", request.repeat), delay, settle)?;
|
shell.command_checked(&format!("repeat {}", request.repeat), delay, settle)?;
|
||||||
shell.command(&format!("zero {}", scan.zero_offset), delay, settle)?;
|
shell.command_checked(&format!("zero {}", scan.zero_offset), delay, settle)?;
|
||||||
shell.command("marker", delay, settle)?;
|
shell.command("marker", delay, settle)?;
|
||||||
report(ScanEvent::Progress(20));
|
report(ScanEvent::Progress(20));
|
||||||
// Pause may take effect even when its response times out, so recovery also
|
// Pause may take effect even when its response times out, so recovery also
|
||||||
// covers failure receiving the pause response itself.
|
// covers failure receiving the pause response itself.
|
||||||
let result = (|| {
|
let result = (|| {
|
||||||
shell.command("pause", delay, settle)?;
|
shell.command_checked("pause", delay, settle)?;
|
||||||
shell.command(&format!("mode {} input", mode.as_str()), delay, settle)?;
|
shell.command_checked(&format!("mode {} input", mode.as_str()), delay, settle)?;
|
||||||
shell.command(&format!("sweep start {}", request.start_hz), delay, settle)?;
|
shell.command_checked(&format!("sweep start {}", request.start_hz), delay, settle)?;
|
||||||
shell.command(&format!("sweep stop {}", request.stop_hz), delay, settle)?;
|
shell.command_checked(&format!("sweep stop {}", request.stop_hz), delay, settle)?;
|
||||||
shell.command("sweep", delay, settle)?;
|
shell.command_checked("sweep", delay, settle)?;
|
||||||
if scan.legacy_pre_scan {
|
if scan.legacy_pre_scan {
|
||||||
shell.command(
|
shell.command_checked(
|
||||||
&format!("scan {} {} 290 101", request.start_hz, request.stop_hz),
|
&format!("scan {} {} 290 101", request.start_hz, request.stop_hz),
|
||||||
Duration::from_millis(serial.scan_delay_ms),
|
Duration::from_millis(serial.scan_delay_ms),
|
||||||
settle,
|
settle,
|
||||||
|
|
@ -112,7 +112,7 @@ pub fn acquire<T: Read + Write>(
|
||||||
scan.frequency_axis,
|
scan.frequency_axis,
|
||||||
)?)
|
)?)
|
||||||
})();
|
})();
|
||||||
let recovery = shell.command("resume", delay, settle);
|
let recovery = shell.command_checked("resume", delay, settle);
|
||||||
match (result, recovery) {
|
match (result, recovery) {
|
||||||
(Ok(samples), Ok(_)) => {
|
(Ok(samples), Ok(_)) => {
|
||||||
report(ScanEvent::Message("Acquisition complete"));
|
report(ScanEvent::Message("Acquisition complete"));
|
||||||
|
|
|
||||||
|
|
@ -46,6 +46,8 @@ pub struct Config {
|
||||||
pub points: usize,
|
pub points: usize,
|
||||||
/// Measurements per point.
|
/// Measurements per point.
|
||||||
pub repeat: usize,
|
pub repeat: usize,
|
||||||
|
/// Serial or TCP transport selection; TCP is useful for bridges and simulation.
|
||||||
|
pub connection: ConnectionConfig,
|
||||||
/// Serial timing, response limits and selection preferences.
|
/// Serial timing, response limits and selection preferences.
|
||||||
pub serial: SerialConfig,
|
pub serial: SerialConfig,
|
||||||
/// Acquisition and numeric input policy.
|
/// Acquisition and numeric input policy.
|
||||||
|
|
@ -58,6 +60,28 @@ pub struct Config {
|
||||||
pub logging: LoggingConfig,
|
pub logging: LoggingConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Transport selected by the application, without changing shell framing.
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Backend {
|
||||||
|
/// A native USB/serial port (requires the `serial` Cargo feature).
|
||||||
|
Serial,
|
||||||
|
/// A TCP bridge or mock server; tinySA hardware does not provide native TCP.
|
||||||
|
Tcp,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connection settings; read deadlines apply to individual I/O operations.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct ConnectionConfig {
|
||||||
|
/// Which connection adapter to open.
|
||||||
|
pub backend: Backend,
|
||||||
|
/// Numeric IPv4/IPv6 socket address used for TCP (no DNS lookup).
|
||||||
|
pub tcp_address: String,
|
||||||
|
/// TCP connect, read and write timeout, in milliseconds.
|
||||||
|
pub tcp_timeout_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
/// Serial settings, separate from the protocol's fixed byte grammar.
|
/// Serial settings, separate from the protocol's fixed byte grammar.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
|
|
@ -240,6 +264,17 @@ impl Config {
|
||||||
(1..=600_000).contains(&self.serial.timeout_ms),
|
(1..=600_000).contains(&self.serial.timeout_ms),
|
||||||
"serial.timeout_ms must be in 1..=600000",
|
"serial.timeout_ms must be in 1..=600000",
|
||||||
)?;
|
)?;
|
||||||
|
require(
|
||||||
|
(1..=600_000).contains(&self.connection.tcp_timeout_ms),
|
||||||
|
"connection.tcp_timeout_ms must be in 1..=600000",
|
||||||
|
)?;
|
||||||
|
require(
|
||||||
|
self.connection
|
||||||
|
.tcp_address
|
||||||
|
.parse::<std::net::SocketAddr>()
|
||||||
|
.is_ok_and(|address| address.port() != 0),
|
||||||
|
"connection.tcp_address must be a numeric IP:port with a nonzero port",
|
||||||
|
)?;
|
||||||
for delay in [
|
for delay in [
|
||||||
self.serial.command_delay_ms,
|
self.serial.command_delay_ms,
|
||||||
self.serial.settle_delay_ms,
|
self.serial.settle_delay_ms,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,136 @@
|
||||||
|
//! Optional physical serial and portable TCP adapters for the same shell codec.
|
||||||
|
//!
|
||||||
|
//! Integrations may instead supply their own `Read + Write` stream directly to
|
||||||
|
//! [`crate::transport::Shell`]. TCP means an explicit bridge or mock server,
|
||||||
|
//! not native network support on the instrument.
|
||||||
|
|
||||||
|
use crate::config::{Backend, Config, ConfigError};
|
||||||
|
use std::{
|
||||||
|
io::{self, Read, Write},
|
||||||
|
net::TcpStream,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// An error opening a configured connection, before any command is sent.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ConnectionError {
|
||||||
|
/// Settings failed validation.
|
||||||
|
#[error(transparent)]
|
||||||
|
Config(#[from] ConfigError),
|
||||||
|
/// The TCP connection or its timeout configuration failed.
|
||||||
|
#[error("TCP connection: {0}")]
|
||||||
|
Tcp(#[from] io::Error),
|
||||||
|
/// Native serial opening failed.
|
||||||
|
#[cfg(feature = "serial")]
|
||||||
|
#[error("serial connection: {0}")]
|
||||||
|
Serial(#[from] serialport::Error),
|
||||||
|
/// Native serial support was omitted from this library build.
|
||||||
|
#[error("enable the serial Cargo feature to open a USB/serial device")]
|
||||||
|
SerialFeatureDisabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A runtime-selected stream; the protocol layer only sees `Read + Write`.
|
||||||
|
pub enum Connection {
|
||||||
|
/// TCP socket with configured operation timeouts.
|
||||||
|
Tcp(TcpStream),
|
||||||
|
/// Native serial port with a configured read timeout.
|
||||||
|
#[cfg(feature = "serial")]
|
||||||
|
Serial(Box<dyn serialport::SerialPort>),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate settings and open the selected backend without sending commands.
|
||||||
|
///
|
||||||
|
/// TCP uses numeric addresses and bounded connect/read/write operations. Serial
|
||||||
|
/// is optional so library consumers do not require system libudev by default
|
||||||
|
/// when using `default-features = false`.
|
||||||
|
pub fn open_connection(config: &Config) -> Result<Connection, ConnectionError> {
|
||||||
|
config.validate()?;
|
||||||
|
match config.connection.backend {
|
||||||
|
Backend::Tcp => {
|
||||||
|
let address = config
|
||||||
|
.connection
|
||||||
|
.tcp_address
|
||||||
|
.parse()
|
||||||
|
.map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
|
||||||
|
let timeout = Duration::from_millis(config.connection.tcp_timeout_ms);
|
||||||
|
let stream = TcpStream::connect_timeout(&address, timeout)?;
|
||||||
|
stream.set_read_timeout(Some(timeout))?;
|
||||||
|
stream.set_write_timeout(Some(timeout))?;
|
||||||
|
stream.set_nodelay(true)?;
|
||||||
|
Ok(Connection::Tcp(stream))
|
||||||
|
}
|
||||||
|
Backend::Serial => {
|
||||||
|
#[cfg(feature = "serial")]
|
||||||
|
{
|
||||||
|
Ok(Connection::Serial(
|
||||||
|
serialport::new(&config.port, config.baudrate)
|
||||||
|
.timeout(Duration::from_millis(config.serial.timeout_ms))
|
||||||
|
.open()?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
#[cfg(not(feature = "serial"))]
|
||||||
|
{
|
||||||
|
Err(ConnectionError::SerialFeatureDisabled)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Read for Connection {
|
||||||
|
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||||
|
match self {
|
||||||
|
Self::Tcp(stream) => stream.read(buffer),
|
||||||
|
#[cfg(feature = "serial")]
|
||||||
|
Self::Serial(stream) => stream.read(buffer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Write for Connection {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||||
|
match self {
|
||||||
|
Self::Tcp(stream) => stream.write(bytes),
|
||||||
|
#[cfg(feature = "serial")]
|
||||||
|
Self::Serial(stream) => stream.write(bytes),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
match self {
|
||||||
|
Self::Tcp(stream) => stream.flush(),
|
||||||
|
#[cfg(feature = "serial")]
|
||||||
|
Self::Serial(stream) => stream.flush(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tcp_configuration_is_validated_before_connecting() {
|
||||||
|
for input in [
|
||||||
|
"[connection]\nbackend='udp'",
|
||||||
|
"[connection]\ntcp_address='localhost:7355'",
|
||||||
|
"[connection]\ntcp_address='127.0.0.1:0'",
|
||||||
|
"[connection]\ntcp_timeout_ms=0",
|
||||||
|
] {
|
||||||
|
assert!(Config::from_toml(input).is_err());
|
||||||
|
}
|
||||||
|
let mut config = Config::default();
|
||||||
|
config.connection.tcp_address = "invalid".into();
|
||||||
|
assert!(matches!(
|
||||||
|
open_connection(&config),
|
||||||
|
Err(ConnectionError::Config(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "serial"))]
|
||||||
|
#[test]
|
||||||
|
fn native_serial_requires_explicit_feature() {
|
||||||
|
assert!(matches!(
|
||||||
|
open_connection(&Config::default()),
|
||||||
|
Err(ConnectionError::SerialFeatureDisabled)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,9 @@ pub(crate) enum AppError {
|
||||||
/// Serial enumeration or opening failed.
|
/// Serial enumeration or opening failed.
|
||||||
#[error("serial connection: {0}")]
|
#[error("serial connection: {0}")]
|
||||||
Port(#[from] serialport::Error),
|
Port(#[from] serialport::Error),
|
||||||
|
/// Configured serial/TCP connection failed before acquisition.
|
||||||
|
#[error(transparent)]
|
||||||
|
Connection(#[from] tiny_wb::connection::ConnectionError),
|
||||||
/// Filesystem or terminal I/O failed.
|
/// Filesystem or terminal I/O failed.
|
||||||
#[error("I/O: {0}")]
|
#[error("I/O: {0}")]
|
||||||
Io(#[from] std::io::Error),
|
Io(#[from] std::io::Error),
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,10 @@
|
||||||
//! The core does not depend on terminal state. Parsers and writers accept data
|
//! 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.
|
//! or I/O interfaces so callers can test them without a connected instrument.
|
||||||
//!
|
//!
|
||||||
|
//! Disable default features for a library without terminal or native serial
|
||||||
|
//! dependencies. Enable `serial` for USB access or `mock` for deterministic
|
||||||
|
//! simulation. The application uses `tui` and `serial` by default.
|
||||||
|
//!
|
||||||
//! # Decode and export a recorded frame
|
//! # Decode and export a recorded frame
|
||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
|
|
@ -20,7 +24,11 @@
|
||||||
|
|
||||||
pub mod acquisition;
|
pub mod acquisition;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
|
pub mod connection;
|
||||||
pub mod export;
|
pub mod export;
|
||||||
|
/// Opt-in deterministic simulator and TCP server support.
|
||||||
|
#[cfg(feature = "mock")]
|
||||||
|
pub mod mock;
|
||||||
pub mod protocol;
|
pub mod protocol;
|
||||||
mod storage;
|
mod storage;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
|
|
|
||||||
10
src/main.rs
10
src/main.rs
|
|
@ -8,7 +8,7 @@ mod ui;
|
||||||
use error::AppError;
|
use error::AppError;
|
||||||
use flexi_logger::{FileSpec, Logger, WriteMode};
|
use flexi_logger::{FileSpec, Logger, WriteMode};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use tiny_wb::config::Config;
|
use tiny_wb::config::{Backend, Config};
|
||||||
|
|
||||||
/// Restore the terminal on ordinary errors and unwinding after initialization.
|
/// Restore the terminal on ordinary errors and unwinding after initialization.
|
||||||
struct TerminalSession;
|
struct TerminalSession;
|
||||||
|
|
@ -33,7 +33,13 @@ 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 ports = serialport::available_ports()?;
|
let ports = match config.connection.backend {
|
||||||
|
Backend::Serial => serialport::available_ports()?,
|
||||||
|
Backend::Tcp => vec![serialport::SerialPortInfo {
|
||||||
|
port_name: format!("tcp://{}", config.connection.tcp_address),
|
||||||
|
port_type: serialport::SerialPortType::Unknown,
|
||||||
|
}],
|
||||||
|
};
|
||||||
let _session = TerminalSession;
|
let _session = TerminalSession;
|
||||||
let terminal = ratatui::try_init()?;
|
let terminal = ratatui::try_init()?;
|
||||||
ui::App::new(ports, config, config_path).run(terminal)?;
|
ui::App::new(ports, config, config_path).run(terminal)?;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,500 @@
|
||||||
|
//! Bounded, stateful console simulation and an in-memory duplex stream.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
io::{self, Read, Write},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Synthetic identity and command differences, not hardware certification.
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum MockModel {
|
||||||
|
/// Basic low/high input syntax; initial raw offset 128 dB.
|
||||||
|
Basic,
|
||||||
|
/// Ultra input syntax, LNA/Ultra toggles; initial raw offset 174 dB.
|
||||||
|
Ultra,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One-shot fault applied to the first matching command in each new session.
|
||||||
|
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum MockFault {
|
||||||
|
/// Normal behavior.
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
/// Reject the command without changing device state.
|
||||||
|
Reject,
|
||||||
|
/// Drop the command and its response, making the next empty read time out.
|
||||||
|
Timeout,
|
||||||
|
/// Close the stream immediately without processing the command.
|
||||||
|
Disconnect,
|
||||||
|
/// Omit the trailing prompt after executing the command.
|
||||||
|
MissingPrompt,
|
||||||
|
/// Remove the end of a scanraw frame and its prompt.
|
||||||
|
TruncatedFrame,
|
||||||
|
/// Replace the first scanraw record's alignment byte.
|
||||||
|
BadAlignment,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Simulator policy, loadable from TOML independently of application settings.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(default, deny_unknown_fields)]
|
||||||
|
pub struct MockConfig {
|
||||||
|
/// Synthetic device identity.
|
||||||
|
pub model: MockModel,
|
||||||
|
/// Echo complete commands before responding.
|
||||||
|
pub echo: bool,
|
||||||
|
/// Maximum bytes returned per in-memory read (also server write chunk size).
|
||||||
|
pub read_chunk_bytes: usize,
|
||||||
|
/// Maximum bytes accepted per in-memory write, exercising complete writes.
|
||||||
|
pub write_chunk_bytes: usize,
|
||||||
|
/// TCP example read/write timeout, in milliseconds (1 through 600,000).
|
||||||
|
pub session_timeout_ms: u64,
|
||||||
|
/// Maximum command line size, before a terminator.
|
||||||
|
pub command_limit_bytes: usize,
|
||||||
|
/// Maximum requested scan points, bounding frame allocation.
|
||||||
|
pub max_points: usize,
|
||||||
|
/// Synthetic Ultra ceiling in Hz; not a hardware capability claim.
|
||||||
|
pub ultra_max_hz: u64,
|
||||||
|
/// Deterministic spectrum floor, in dBm.
|
||||||
|
pub floor_dbm: f64,
|
||||||
|
/// Triangular peak level, in dBm.
|
||||||
|
pub peak_dbm: f64,
|
||||||
|
/// Synthetic carrier center, in Hz.
|
||||||
|
pub peak_frequency_hz: u64,
|
||||||
|
/// Half-width of the triangular peak, in Hz.
|
||||||
|
pub peak_width_hz: u64,
|
||||||
|
/// One-shot response fault.
|
||||||
|
pub fault: MockFault,
|
||||||
|
/// Command verb on which to inject the fault, for example `scanraw`.
|
||||||
|
pub fault_command: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MockConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
model: MockModel::Basic,
|
||||||
|
echo: true,
|
||||||
|
read_chunk_bytes: 4096,
|
||||||
|
write_chunk_bytes: 4096,
|
||||||
|
session_timeout_ms: 30_000,
|
||||||
|
command_limit_bytes: 256,
|
||||||
|
max_points: 10001,
|
||||||
|
ultra_max_hz: 6_000_000_000,
|
||||||
|
floor_dbm: -96.0,
|
||||||
|
peak_dbm: -32.0,
|
||||||
|
peak_frequency_hz: 300_000_000,
|
||||||
|
peak_width_hz: 10_000_000,
|
||||||
|
fault: MockFault::None,
|
||||||
|
fault_command: "scanraw".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MockConfig {
|
||||||
|
/// Reject unbounded allocations, non-finite signal values and invalid fault settings.
|
||||||
|
pub fn validate(&self) -> io::Result<()> {
|
||||||
|
let valid = (1..=600_000).contains(&self.session_timeout_ms)
|
||||||
|
&& (1..=65536).contains(&self.read_chunk_bytes)
|
||||||
|
&& (1..=65536).contains(&self.write_chunk_bytes)
|
||||||
|
&& (16..=4096).contains(&self.command_limit_bytes)
|
||||||
|
&& (2..=1_000_001).contains(&self.max_points)
|
||||||
|
&& (960_000_000..=12_000_000_000).contains(&self.ultra_max_hz)
|
||||||
|
&& self.floor_dbm.is_finite()
|
||||||
|
&& self.peak_dbm.is_finite()
|
||||||
|
&& (-174.0..=100.0).contains(&self.floor_dbm)
|
||||||
|
&& (self.floor_dbm..=100.0).contains(&self.peak_dbm)
|
||||||
|
&& self.peak_frequency_hz <= 12_000_000_000
|
||||||
|
&& (1..=12_000_000_000).contains(&self.peak_width_hz)
|
||||||
|
&& !self.fault_command.is_empty()
|
||||||
|
&& self
|
||||||
|
.fault_command
|
||||||
|
.bytes()
|
||||||
|
.all(|b| b.is_ascii_lowercase() || b == b'_')
|
||||||
|
&& (!matches!(
|
||||||
|
self.fault,
|
||||||
|
MockFault::TruncatedFrame | MockFault::BadAlignment
|
||||||
|
) || self.fault_command == "scanraw");
|
||||||
|
if valid {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
"invalid mock configuration bounds or fault/command combination",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Observable simulated state. No field represents a physical measurement.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct MockState {
|
||||||
|
/// Synthetic model.
|
||||||
|
pub model: MockModel,
|
||||||
|
/// Whether normal sweeping is paused.
|
||||||
|
pub paused: bool,
|
||||||
|
/// Last selected input keyword (`low`, `high`, or `input`).
|
||||||
|
pub input: String,
|
||||||
|
/// Display sweep start, in Hz.
|
||||||
|
pub start_hz: u64,
|
||||||
|
/// Display sweep stop, in Hz.
|
||||||
|
pub stop_hz: u64,
|
||||||
|
/// Last requested raw scan sample count.
|
||||||
|
pub points: usize,
|
||||||
|
/// Measurement repeat count.
|
||||||
|
pub repeat: usize,
|
||||||
|
/// Offset used by raw fixed-point encoding, in dB.
|
||||||
|
pub zero_offset: u16,
|
||||||
|
/// Simulated LNA state (Ultra only; no RF effect).
|
||||||
|
pub lna: bool,
|
||||||
|
/// Simulated Ultra state (no RF effect).
|
||||||
|
pub ultra: bool,
|
||||||
|
/// Last 1,024 complete commands, oldest first; excludes overlong lines.
|
||||||
|
pub commands: VecDeque<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A deterministic `Read + Write` fake instrument with partial I/O support.
|
||||||
|
///
|
||||||
|
/// Empty reads return `TimedOut`, not EOF; a disconnect fault returns EOF and
|
||||||
|
/// rejects later writes. Responses are generated only when commands arrive.
|
||||||
|
/// Use `Shell::new(&mut mock, limit)` to inspect state after dropping the shell.
|
||||||
|
pub struct MockStream {
|
||||||
|
config: MockConfig,
|
||||||
|
state: MockState,
|
||||||
|
input: Vec<u8>,
|
||||||
|
output: VecDeque<u8>,
|
||||||
|
discarding: bool,
|
||||||
|
connected: bool,
|
||||||
|
fault_used: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MockStream {
|
||||||
|
/// Construct a fresh session with an initial shell prompt.
|
||||||
|
pub fn new(config: MockConfig) -> io::Result<Self> {
|
||||||
|
config.validate()?;
|
||||||
|
let state = MockState {
|
||||||
|
model: config.model,
|
||||||
|
paused: false,
|
||||||
|
input: if config.model == MockModel::Basic {
|
||||||
|
"low"
|
||||||
|
} else {
|
||||||
|
"input"
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
start_hz: 240_000_000,
|
||||||
|
stop_hz: 960_000_000,
|
||||||
|
points: 101.min(config.max_points),
|
||||||
|
repeat: 1,
|
||||||
|
zero_offset: if config.model == MockModel::Basic {
|
||||||
|
128
|
||||||
|
} else {
|
||||||
|
174
|
||||||
|
},
|
||||||
|
lna: false,
|
||||||
|
ultra: false,
|
||||||
|
commands: VecDeque::new(),
|
||||||
|
};
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
state,
|
||||||
|
input: Vec::new(),
|
||||||
|
output: VecDeque::from(b"ch>".to_vec()),
|
||||||
|
discarding: false,
|
||||||
|
connected: true,
|
||||||
|
fault_used: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read-only state and bounded command history, for assertions.
|
||||||
|
pub fn state(&self) -> &MockState {
|
||||||
|
&self.state
|
||||||
|
}
|
||||||
|
/// Whether a disconnect fault closed the simulated connection.
|
||||||
|
pub fn is_connected(&self) -> bool {
|
||||||
|
self.connected
|
||||||
|
}
|
||||||
|
/// Number of currently queued response bytes; used by the TCP adapter.
|
||||||
|
pub fn pending_bytes(&self) -> usize {
|
||||||
|
self.output.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bound pipelined responses as well as individual scan allocations.
|
||||||
|
fn enqueue(&mut self, bytes: &[u8]) -> io::Result<()> {
|
||||||
|
let limit = self.config.max_points * 3 + self.config.command_limit_bytes + 65536;
|
||||||
|
if self.output.len().saturating_add(bytes.len()) > limit {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::OutOfMemory,
|
||||||
|
"mock response queue limit exceeded; read responses before pipelining commands",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
self.output.extend(bytes);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(&mut self, command: &str) -> io::Result<()> {
|
||||||
|
if self.state.commands.len() == 1024 {
|
||||||
|
self.state.commands.pop_front();
|
||||||
|
}
|
||||||
|
self.state.commands.push_back(command.into());
|
||||||
|
let verb = command.split_whitespace().next().unwrap_or("");
|
||||||
|
let fault = if !self.fault_used && verb == self.config.fault_command {
|
||||||
|
self.fault_used = true;
|
||||||
|
self.config.fault
|
||||||
|
} else {
|
||||||
|
MockFault::None
|
||||||
|
};
|
||||||
|
match fault {
|
||||||
|
MockFault::Timeout => return Ok(()),
|
||||||
|
MockFault::Disconnect => {
|
||||||
|
self.connected = false;
|
||||||
|
self.output.clear();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
let mut response = if self.config.echo {
|
||||||
|
format!("{command}\r\n").into_bytes()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
let mut body = if fault == MockFault::Reject {
|
||||||
|
b"error: injected rejection\r\n".to_vec()
|
||||||
|
} else {
|
||||||
|
self.respond(command)
|
||||||
|
};
|
||||||
|
if fault == MockFault::BadAlignment && body.first() == Some(&b'{') {
|
||||||
|
body[1] = b'!';
|
||||||
|
}
|
||||||
|
if fault == MockFault::TruncatedFrame && body.first() == Some(&b'{') {
|
||||||
|
body.truncate(body.len().saturating_sub(4));
|
||||||
|
}
|
||||||
|
response.extend(body);
|
||||||
|
if !matches!(fault, MockFault::MissingPrompt | MockFault::TruncatedFrame) {
|
||||||
|
response.extend_from_slice(b"ch>");
|
||||||
|
}
|
||||||
|
self.enqueue(&response)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unsupported commands fail explicitly rather than inventing successful firmware behavior.
|
||||||
|
fn respond(&mut self, command: &str) -> Vec<u8> {
|
||||||
|
let fields: Vec<_> = command.split_whitespace().collect();
|
||||||
|
let ok = b"".to_vec();
|
||||||
|
let invalid = || b"error: unsupported command or invalid arguments in mock\r\n".to_vec();
|
||||||
|
match fields.as_slice() {
|
||||||
|
[] => ok,
|
||||||
|
["version"] => {
|
||||||
|
format!("tiny-wb mock {:?} 0.1 (synthetic)\r\n", self.state.model).into_bytes()
|
||||||
|
}
|
||||||
|
["info"] => format!(
|
||||||
|
"tinySA {} mock; not real firmware\r\n",
|
||||||
|
if self.state.model == MockModel::Basic {
|
||||||
|
"Basic"
|
||||||
|
} else {
|
||||||
|
"Ultra"
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.into_bytes(),
|
||||||
|
["help"] => {
|
||||||
|
let extra = if self.state.model == MockModel::Ultra {
|
||||||
|
" lna ultra"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
format!("Commands: version info help pause resume mode repeat zero sweep scan scanraw leveloffset vbat usart_cfg threads marker{extra}\r\n").into_bytes()
|
||||||
|
}
|
||||||
|
["pause"] => {
|
||||||
|
self.state.paused = true;
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
["resume"] => {
|
||||||
|
self.state.paused = false;
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
["mode", "low" | "high", "input"] if self.state.model == MockModel::Basic => {
|
||||||
|
self.state.input = fields[1].into();
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
["mode", "input"] | ["mode", "low", "input"]
|
||||||
|
if self.state.model == MockModel::Ultra =>
|
||||||
|
{
|
||||||
|
self.state.input = "input".into();
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
["lna", value] | ["ultra", value]
|
||||||
|
if self.state.model == MockModel::Ultra && matches!(*value, "on" | "off") =>
|
||||||
|
{
|
||||||
|
if fields[0] == "lna" {
|
||||||
|
self.state.lna = *value == "on";
|
||||||
|
} else {
|
||||||
|
self.state.ultra = *value == "on";
|
||||||
|
}
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
["repeat", value] => match value.parse::<usize>() {
|
||||||
|
Ok(value) if (1..=1000).contains(&value) => {
|
||||||
|
self.state.repeat = value;
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
_ => invalid(),
|
||||||
|
},
|
||||||
|
["zero", value] => match value.parse::<u16>() {
|
||||||
|
Ok(value) if value <= 2047 => {
|
||||||
|
self.state.zero_offset = value;
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
_ => invalid(),
|
||||||
|
},
|
||||||
|
["sweep", "start" | "stop", value] => match value.parse::<u64>() {
|
||||||
|
Ok(value) if value <= self.max_hz() => {
|
||||||
|
if fields[1] == "start" {
|
||||||
|
self.state.start_hz = value;
|
||||||
|
} else {
|
||||||
|
self.state.stop_hz = value;
|
||||||
|
}
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
_ => invalid(),
|
||||||
|
},
|
||||||
|
["sweep"] => format!(
|
||||||
|
"{} {} {}\r\n",
|
||||||
|
self.state.start_hz, self.state.stop_hz, self.state.points
|
||||||
|
)
|
||||||
|
.into_bytes(),
|
||||||
|
["scanraw", start, stop, points] => {
|
||||||
|
if let Some((start, stop, points)) = self.scan_arguments(start, stop, points) {
|
||||||
|
self.state.points = points;
|
||||||
|
let mut frame = Vec::with_capacity(points * 3 + 4);
|
||||||
|
frame.push(b'{');
|
||||||
|
for index in 0..points {
|
||||||
|
// The mock uses the reviewed firmware convention, span / points.
|
||||||
|
let frequency =
|
||||||
|
start as f64 + (stop - start) as f64 * index as f64 / points as f64;
|
||||||
|
let strength = (1.0
|
||||||
|
- (frequency - self.config.peak_frequency_hz as f64).abs()
|
||||||
|
/ self.config.peak_width_hz as f64)
|
||||||
|
.clamp(0.0, 1.0);
|
||||||
|
let level = self.config.floor_dbm
|
||||||
|
+ strength * (self.config.peak_dbm - self.config.floor_dbm);
|
||||||
|
let raw = ((level + f64::from(self.state.zero_offset)) * 32.0)
|
||||||
|
.round()
|
||||||
|
.clamp(0.0, 65535.0) as u16;
|
||||||
|
frame.push(b'x');
|
||||||
|
frame.extend(raw.to_le_bytes());
|
||||||
|
}
|
||||||
|
frame.extend_from_slice(b"}\r\n");
|
||||||
|
frame
|
||||||
|
} else {
|
||||||
|
invalid()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Compatibility-only preparation used by the current application. No trace is returned.
|
||||||
|
["scan", start, stop, "290", "101"]
|
||||||
|
if self.scan_arguments(start, stop, "2").is_some() =>
|
||||||
|
{
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
["leveloffset"] => b"leveloffset mock 0\r\n".to_vec(),
|
||||||
|
["vbat"] => b"4000 mV (mock)\r\n".to_vec(),
|
||||||
|
["usart_cfg"] => b"115200 (mock)\r\n".to_vec(),
|
||||||
|
["threads"] => b"mock: synchronous\r\n".to_vec(),
|
||||||
|
["marker"] => b"1 0 300000000 -32 (mock)\r\n".to_vec(),
|
||||||
|
_ => invalid(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn max_hz(&self) -> u64 {
|
||||||
|
if self.state.model == MockModel::Basic {
|
||||||
|
960_000_000
|
||||||
|
} else {
|
||||||
|
self.config.ultra_max_hz
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scan_arguments(&self, start: &str, stop: &str, points: &str) -> Option<(u64, u64, usize)> {
|
||||||
|
let (start, stop, points) = (
|
||||||
|
start.parse::<u64>().ok()?,
|
||||||
|
stop.parse::<u64>().ok()?,
|
||||||
|
points.parse::<usize>().ok()?,
|
||||||
|
);
|
||||||
|
if start > stop || stop > self.max_hz() || !(2..=self.config.max_points).contains(&points) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if self.state.model == MockModel::Basic {
|
||||||
|
let valid = match self.state.input.as_str() {
|
||||||
|
"low" => stop < 350_000_000,
|
||||||
|
"high" => start >= 240_000_000,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if !valid {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some((start, stop, points))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Read for MockStream {
|
||||||
|
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
|
||||||
|
if buffer.is_empty() {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
if self.output.is_empty() {
|
||||||
|
return if self.connected {
|
||||||
|
Err(io::ErrorKind::TimedOut.into())
|
||||||
|
} else {
|
||||||
|
Ok(0)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let count = buffer
|
||||||
|
.len()
|
||||||
|
.min(self.config.read_chunk_bytes)
|
||||||
|
.min(self.output.len());
|
||||||
|
for byte in &mut buffer[..count] {
|
||||||
|
*byte = self.output.pop_front().expect("queue length checked");
|
||||||
|
}
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Write for MockStream {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||||
|
if bytes.is_empty() {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
if !self.connected {
|
||||||
|
return Err(io::ErrorKind::BrokenPipe.into());
|
||||||
|
}
|
||||||
|
let count = bytes.len().min(self.config.write_chunk_bytes);
|
||||||
|
for (index, &byte) in bytes[..count].iter().enumerate() {
|
||||||
|
if matches!(byte, b'\r' | b'\n') {
|
||||||
|
if self.discarding {
|
||||||
|
self.discarding = false;
|
||||||
|
self.enqueue(b"error: command too long\r\nch>")?;
|
||||||
|
} else if !self.input.is_empty() {
|
||||||
|
let input = std::mem::take(&mut self.input);
|
||||||
|
match String::from_utf8(input) {
|
||||||
|
Ok(command) if command.bytes().all(|c| (b' '..=b'~').contains(&c)) => {
|
||||||
|
self.execute(&command)?
|
||||||
|
}
|
||||||
|
_ => self.enqueue(b"error: command must be printable ASCII\r\nch>")?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if !self.discarding {
|
||||||
|
if self.input.len() == self.config.command_limit_bytes {
|
||||||
|
self.input.clear();
|
||||||
|
self.discarding = true;
|
||||||
|
} else {
|
||||||
|
self.input.push(byte);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !self.connected {
|
||||||
|
return Ok(index + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(count)
|
||||||
|
}
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
//! Deterministic tinySA console simulation for tests and local integrations.
|
||||||
|
//!
|
||||||
|
//! Enable the `mock` feature. This is a command/state simulator, not an RF model
|
||||||
|
//! or an emulator of a specific firmware release. [`crate::mock::MockStream`] and the TCP
|
||||||
|
//! server share the same parser and device state; neither needs serial drivers.
|
||||||
|
|
||||||
|
//! # Inspect state after a command
|
||||||
|
//!
|
||||||
|
//! ```
|
||||||
|
//! use tiny_wb::{mock::{MockConfig, MockStream}, transport::Shell};
|
||||||
|
//! use std::time::Duration;
|
||||||
|
//! let mut device = MockStream::new(MockConfig::default())?;
|
||||||
|
//! {
|
||||||
|
//! let mut shell = Shell::new(&mut device, 65_536);
|
||||||
|
//! shell.synchronize()?;
|
||||||
|
//! shell.command_checked("pause", Duration::ZERO, Duration::ZERO)?;
|
||||||
|
//! }
|
||||||
|
//! assert!(device.state().paused);
|
||||||
|
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
mod device;
|
||||||
|
mod server;
|
||||||
|
|
||||||
|
pub use device::{MockConfig, MockFault, MockModel, MockState, MockStream};
|
||||||
|
pub use server::serve_connection;
|
||||||
|
|
@ -0,0 +1,40 @@
|
||||||
|
//! Stream server adapter; all command behavior comes from MockStream.
|
||||||
|
|
||||||
|
use super::{MockConfig, MockState, MockStream};
|
||||||
|
use std::io::{self, Read, Write};
|
||||||
|
|
||||||
|
/// Serve one connection until EOF or a configured disconnect fault.
|
||||||
|
///
|
||||||
|
/// The caller controls transport timeouts, listener lifecycle and concurrency.
|
||||||
|
/// Each call creates a fresh device. Response fragmentation follows mock read
|
||||||
|
/// chunk size, although TCP may coalesce writes on the network.
|
||||||
|
///
|
||||||
|
/// Returns final device state for assertions; I/O errors are propagated.
|
||||||
|
pub fn serve_connection(
|
||||||
|
mut stream: impl Read + Write,
|
||||||
|
config: MockConfig,
|
||||||
|
) -> io::Result<MockState> {
|
||||||
|
let mut device = MockStream::new(config)?;
|
||||||
|
let mut bytes = [0; 4096];
|
||||||
|
loop {
|
||||||
|
while device.pending_bytes() != 0 {
|
||||||
|
let count = device.read(&mut bytes)?;
|
||||||
|
stream.write_all(&bytes[..count])?;
|
||||||
|
}
|
||||||
|
stream.flush()?;
|
||||||
|
if !device.is_connected() {
|
||||||
|
return Ok(device.state().clone());
|
||||||
|
}
|
||||||
|
let count = match stream.read(&mut bytes) {
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
||||||
|
result => result?,
|
||||||
|
};
|
||||||
|
if count == 0 {
|
||||||
|
return Ok(device.state().clone());
|
||||||
|
}
|
||||||
|
let mut consumed = 0;
|
||||||
|
while consumed < count && device.is_connected() {
|
||||||
|
consumed += device.write(&bytes[consumed..count])?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -7,11 +7,11 @@ use crate::error::{AppError, UiError};
|
||||||
use std::{
|
use std::{
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::{Arc, Mutex, MutexGuard},
|
sync::{Arc, Mutex, MutexGuard},
|
||||||
time::Duration,
|
|
||||||
};
|
};
|
||||||
use tiny_wb::{
|
use tiny_wb::{
|
||||||
acquisition::{acquire, ScanEvent},
|
acquisition::{acquire, ScanEvent},
|
||||||
config::Config,
|
config::Config,
|
||||||
|
connection::open_connection,
|
||||||
export::save_csv,
|
export::save_csv,
|
||||||
protocol::ScanRequest,
|
protocol::ScanRequest,
|
||||||
transport::Shell,
|
transport::Shell,
|
||||||
|
|
@ -130,9 +130,7 @@ pub(crate) fn run_scan(
|
||||||
request
|
request
|
||||||
.input_mode()
|
.input_mode()
|
||||||
.map_err(tiny_wb::acquisition::AcquisitionError::from)?;
|
.map_err(tiny_wb::acquisition::AcquisitionError::from)?;
|
||||||
let port = serialport::new(&config.port, config.baudrate)
|
let port = open_connection(&config)?;
|
||||||
.timeout(Duration::from_millis(config.serial.timeout_ms))
|
|
||||||
.open()?;
|
|
||||||
let mut shell = Shell::new(port, config.serial.max_response_bytes);
|
let mut shell = Shell::new(port, config.serial.max_response_bytes);
|
||||||
let samples = acquire(
|
let samples = acquire(
|
||||||
&mut shell,
|
&mut shell,
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,14 @@ pub enum TransportError {
|
||||||
/// A command contains a terminator or is empty/non-ASCII.
|
/// A command contains a terminator or is empty/non-ASCII.
|
||||||
#[error("a shell command must be one nonempty printable ASCII line")]
|
#[error("a shell command must be one nonempty printable ASCII line")]
|
||||||
InvalidCommand,
|
InvalidCommand,
|
||||||
|
/// A checked command returned a recognizable rejection or usage response.
|
||||||
|
#[error("device rejected {command:?}: {response}")]
|
||||||
|
CommandRejected {
|
||||||
|
/// Command that was sent.
|
||||||
|
command: String,
|
||||||
|
/// Bounded text response from the device.
|
||||||
|
response: String,
|
||||||
|
},
|
||||||
/// An invalid scan request was rejected before reading.
|
/// An invalid scan request was rejected before reading.
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Protocol(#[from] ProtocolError),
|
Protocol(#[from] ProtocolError),
|
||||||
|
|
@ -112,6 +120,31 @@ impl<T: Read + Write> Shell<T> {
|
||||||
Ok(String::from_utf8_lossy(&response).into_owned())
|
Ok(String::from_utf8_lossy(&response).into_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Send a mutating command, rejecting recognizable error/usage responses.
|
||||||
|
///
|
||||||
|
/// This handles common shell responses, not every firmware-specific status.
|
||||||
|
/// Use `command` for informational queries that intentionally return usage.
|
||||||
|
pub fn command_checked(
|
||||||
|
&mut self,
|
||||||
|
command: &str,
|
||||||
|
delay: Duration,
|
||||||
|
settle: Duration,
|
||||||
|
) -> Result<String, TransportError> {
|
||||||
|
let response = self.command(command, delay, settle)?;
|
||||||
|
if response.lines().any(|line| {
|
||||||
|
let line = line.trim_start().to_ascii_lowercase();
|
||||||
|
line.starts_with("error:")
|
||||||
|
|| line.starts_with("usage:")
|
||||||
|
|| line.starts_with("unknown command")
|
||||||
|
}) {
|
||||||
|
return Err(TransportError::CommandRejected {
|
||||||
|
command: command.into(),
|
||||||
|
response,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
/// Consume echo, an exact raw body, then its trailing shell prompt.
|
/// Consume echo, an exact raw body, then its trailing shell prompt.
|
||||||
///
|
///
|
||||||
/// Progress receives `(received_body_bytes, expected_body_bytes)`. A short
|
/// Progress receives `(received_body_bytes, expected_body_bytes)`. A short
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,384 @@
|
||||||
|
//! Production acquisition exercised against stateful, synthetic instruments.
|
||||||
|
use std::{
|
||||||
|
io::{self, Read, Write},
|
||||||
|
net::TcpListener,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
use tiny_wb::{
|
||||||
|
acquisition::acquire,
|
||||||
|
config::{Backend, Config, FrequencyAxis},
|
||||||
|
connection::open_connection,
|
||||||
|
mock::{serve_connection, MockConfig, MockFault, MockModel, MockStream},
|
||||||
|
protocol::ScanRequest,
|
||||||
|
transport::Shell,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn settings() -> Config {
|
||||||
|
let mut config = Config::default();
|
||||||
|
config.serial.command_delay_ms = 0;
|
||||||
|
config.serial.settle_delay_ms = 0;
|
||||||
|
config.serial.scan_delay_ms = 0;
|
||||||
|
config.scan.frequency_axis = FrequencyAxis::Firmware;
|
||||||
|
config
|
||||||
|
}
|
||||||
|
fn request() -> ScanRequest {
|
||||||
|
ScanRequest {
|
||||||
|
start_hz: 240_000_000,
|
||||||
|
stop_hz: 360_000_000,
|
||||||
|
points: 4,
|
||||||
|
repeat: 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn drain(device: &mut MockStream) -> Vec<u8> {
|
||||||
|
let mut response = Vec::new();
|
||||||
|
let mut bytes = [0; 4096];
|
||||||
|
while device.pending_bytes() > 0 {
|
||||||
|
let count = device.read(&mut bytes).unwrap();
|
||||||
|
response.extend_from_slice(&bytes[..count]);
|
||||||
|
}
|
||||||
|
response
|
||||||
|
}
|
||||||
|
fn command(device: &mut MockStream, command: &str) -> String {
|
||||||
|
device
|
||||||
|
.write_all(format!("{command}\r\n").as_bytes())
|
||||||
|
.unwrap();
|
||||||
|
String::from_utf8_lossy(&drain(device)).into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn acquisition_survives_bytewise_io_and_restores_sweeping() {
|
||||||
|
for echo in [false, true] {
|
||||||
|
for legacy in [false, true] {
|
||||||
|
let mut device = MockStream::new(MockConfig {
|
||||||
|
echo,
|
||||||
|
read_chunk_bytes: 1,
|
||||||
|
write_chunk_bytes: 1,
|
||||||
|
..MockConfig::default()
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let mut config = settings();
|
||||||
|
config.scan.legacy_pre_scan = legacy;
|
||||||
|
let samples = acquire(
|
||||||
|
&mut Shell::new(&mut device, 65536),
|
||||||
|
&request(),
|
||||||
|
&config.scan,
|
||||||
|
&config.serial,
|
||||||
|
|_| {},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(samples.len(), 4);
|
||||||
|
assert_eq!(samples[2].level_dbm, -32.0);
|
||||||
|
assert_eq!(samples[0].level_dbm, -96.0);
|
||||||
|
assert!(!device.state().paused);
|
||||||
|
assert_eq!(device.state().repeat, 2);
|
||||||
|
assert_eq!(device.state().commands.back().unwrap(), "resume");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn faults_fail_acquisition_and_attempt_recovery() {
|
||||||
|
for fault in [
|
||||||
|
MockFault::Reject,
|
||||||
|
MockFault::Timeout,
|
||||||
|
MockFault::Disconnect,
|
||||||
|
MockFault::MissingPrompt,
|
||||||
|
MockFault::TruncatedFrame,
|
||||||
|
MockFault::BadAlignment,
|
||||||
|
] {
|
||||||
|
let mut device = MockStream::new(MockConfig {
|
||||||
|
fault,
|
||||||
|
..MockConfig::default()
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let config = settings();
|
||||||
|
let result = acquire(
|
||||||
|
&mut Shell::new(&mut device, 65536),
|
||||||
|
&request(),
|
||||||
|
&config.scan,
|
||||||
|
&config.serial,
|
||||||
|
|_| {},
|
||||||
|
);
|
||||||
|
assert!(result.is_err(), "{fault:?}");
|
||||||
|
if fault != MockFault::Disconnect {
|
||||||
|
assert!(!device.state().paused, "{fault:?}");
|
||||||
|
let result = acquire(
|
||||||
|
&mut Shell::new(&mut device, 65536),
|
||||||
|
&request(),
|
||||||
|
&config.scan,
|
||||||
|
&config.serial,
|
||||||
|
|_| {},
|
||||||
|
);
|
||||||
|
assert!(result.is_ok(), "one-shot {fault:?}: {result:?}");
|
||||||
|
} else {
|
||||||
|
assert!(!device.is_connected());
|
||||||
|
assert_eq!(device.read(&mut [0]).unwrap(), 0);
|
||||||
|
assert_eq!(
|
||||||
|
device.write(b"resume").unwrap_err().kind(),
|
||||||
|
io::ErrorKind::BrokenPipe
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejected_pause_and_ultra_high_mode_are_not_silent_successes() {
|
||||||
|
for mock in [
|
||||||
|
MockConfig {
|
||||||
|
fault: MockFault::Reject,
|
||||||
|
fault_command: "pause".into(),
|
||||||
|
..MockConfig::default()
|
||||||
|
},
|
||||||
|
MockConfig {
|
||||||
|
model: MockModel::Ultra,
|
||||||
|
..MockConfig::default()
|
||||||
|
},
|
||||||
|
] {
|
||||||
|
let mut device = MockStream::new(mock).unwrap();
|
||||||
|
let config = settings();
|
||||||
|
let error = acquire(
|
||||||
|
&mut Shell::new(&mut device, 65536),
|
||||||
|
&request(),
|
||||||
|
&config.scan,
|
||||||
|
&config.serial,
|
||||||
|
|_| {},
|
||||||
|
)
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(error.to_string().contains("reject"), "{error}");
|
||||||
|
assert!(!device.state().paused);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ultra_profile_and_explicit_command_subset() {
|
||||||
|
let mut device = MockStream::new(MockConfig {
|
||||||
|
model: MockModel::Ultra,
|
||||||
|
echo: false,
|
||||||
|
..MockConfig::default()
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
drain(&mut device);
|
||||||
|
assert_eq!(device.state().zero_offset, 174);
|
||||||
|
assert!(command(&mut device, "version").contains("Ultra"));
|
||||||
|
assert!(command(&mut device, "help").contains("lna ultra"));
|
||||||
|
for cmd in [
|
||||||
|
"mode input",
|
||||||
|
"mode low input",
|
||||||
|
"lna on",
|
||||||
|
"ultra on",
|
||||||
|
"sweep start 1000000000",
|
||||||
|
"sweep stop 2000000000",
|
||||||
|
] {
|
||||||
|
assert_eq!(command(&mut device, cmd), "ch>");
|
||||||
|
}
|
||||||
|
assert!(device.state().lna && device.state().ultra);
|
||||||
|
device
|
||||||
|
.write_all(b"scanraw 1000000000 2000000000 2\r")
|
||||||
|
.unwrap();
|
||||||
|
let frame = drain(&mut device);
|
||||||
|
assert_eq!(frame[0], b'{');
|
||||||
|
assert_eq!(frame[1], b'x');
|
||||||
|
assert_eq!(frame.len(), 13);
|
||||||
|
for cmd in ["lna off", "ultra off"] {
|
||||||
|
command(&mut device, cmd);
|
||||||
|
}
|
||||||
|
assert!(!device.state().lna && !device.state().ultra);
|
||||||
|
for cmd in [
|
||||||
|
"mode high input",
|
||||||
|
"lna auto",
|
||||||
|
"reset",
|
||||||
|
"scanraw 0 6000000001 2",
|
||||||
|
] {
|
||||||
|
assert!(command(&mut device, cmd).contains("error:"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_commands_do_not_mutate_measurement_state() {
|
||||||
|
let mut device = MockStream::new(MockConfig::default()).unwrap();
|
||||||
|
drain(&mut device);
|
||||||
|
for cmd in [
|
||||||
|
"repeat 0",
|
||||||
|
"repeat xyz",
|
||||||
|
"zero 2048",
|
||||||
|
"zero xyz",
|
||||||
|
"sweep start -1",
|
||||||
|
"sweep stop 960000001",
|
||||||
|
"scanraw 10 1 2",
|
||||||
|
"scanraw 0 350000000 2",
|
||||||
|
"scanraw 0 10 1",
|
||||||
|
"scanraw x 10 2",
|
||||||
|
"scanraw 0 10 10002",
|
||||||
|
"lna on",
|
||||||
|
] {
|
||||||
|
assert!(command(&mut device, cmd).contains("error:"), "{cmd}");
|
||||||
|
}
|
||||||
|
assert_eq!(device.state().repeat, 1);
|
||||||
|
assert_eq!(device.state().zero_offset, 128);
|
||||||
|
assert_eq!(device.state().start_hz, 240_000_000);
|
||||||
|
assert_eq!(device.state().stop_hz, 960_000_000);
|
||||||
|
command(&mut device, "mode high input");
|
||||||
|
assert!(command(&mut device, "scanraw 0 300000000 2").contains("error:"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn framing_limits_and_history_are_bounded() {
|
||||||
|
let mut device = MockStream::new(MockConfig {
|
||||||
|
command_limit_bytes: 16,
|
||||||
|
echo: false,
|
||||||
|
..MockConfig::default()
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(device.read(&mut []).unwrap(), 0);
|
||||||
|
assert_eq!(device.write(&[]).unwrap(), 0);
|
||||||
|
drain(&mut device);
|
||||||
|
assert_eq!(
|
||||||
|
device.read(&mut [0]).unwrap_err().kind(),
|
||||||
|
io::ErrorKind::TimedOut
|
||||||
|
);
|
||||||
|
assert!(command(&mut device, &"x".repeat(17)).contains("too long"));
|
||||||
|
device.write_all(b"\xff\r").unwrap();
|
||||||
|
assert!(String::from_utf8(drain(&mut device))
|
||||||
|
.unwrap()
|
||||||
|
.contains("ASCII"));
|
||||||
|
for _ in 0..1030 {
|
||||||
|
command(&mut device, "pause");
|
||||||
|
}
|
||||||
|
assert_eq!(device.state().commands.len(), 1024);
|
||||||
|
assert_eq!(command(&mut device, "resume"), "ch>");
|
||||||
|
let error = loop {
|
||||||
|
if let Err(error) = device.write_all(b"help\r") {
|
||||||
|
break error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assert_eq!(error.kind(), io::ErrorKind::OutOfMemory);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mock_templates_and_invalid_configuration() {
|
||||||
|
Config::from_toml(include_str!("../config/mock-client.toml")).unwrap();
|
||||||
|
for source in [
|
||||||
|
include_str!("../config/mock-basic.toml"),
|
||||||
|
include_str!("../config/mock-ultra.toml"),
|
||||||
|
] {
|
||||||
|
toml::from_str::<MockConfig>(source)
|
||||||
|
.unwrap()
|
||||||
|
.validate()
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
for source in [
|
||||||
|
"read_chunk_bytes=0",
|
||||||
|
"write_chunk_bytes=0",
|
||||||
|
"command_limit_bytes=1",
|
||||||
|
"max_points=1",
|
||||||
|
"ultra_max_hz=1",
|
||||||
|
"floor_dbm=nan",
|
||||||
|
"peak_dbm=-100.0",
|
||||||
|
"peak_width_hz=0",
|
||||||
|
"fault_command='BAD'",
|
||||||
|
"fault='bad_alignment'\nfault_command='pause'",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
MockStream::new(toml::from_str(source).unwrap()).is_err(),
|
||||||
|
"{source}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(toml::from_str::<MockConfig>("unknown=1").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tcp_backend_runs_real_acquisition_and_closes_cleanly() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let mut config = settings();
|
||||||
|
config.connection.backend = Backend::Tcp;
|
||||||
|
config.connection.tcp_address = listener.local_addr().unwrap().to_string();
|
||||||
|
let server = std::thread::spawn(move || {
|
||||||
|
let (socket, _) = listener.accept().unwrap();
|
||||||
|
socket
|
||||||
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||||
|
.unwrap();
|
||||||
|
socket
|
||||||
|
.set_write_timeout(Some(Duration::from_secs(5)))
|
||||||
|
.unwrap();
|
||||||
|
serve_connection(socket, MockConfig::default()).unwrap()
|
||||||
|
});
|
||||||
|
{
|
||||||
|
let mut shell = Shell::new(open_connection(&config).unwrap(), 65536);
|
||||||
|
let samples =
|
||||||
|
acquire(&mut shell, &request(), &config.scan, &config.serial, |_| {}).unwrap();
|
||||||
|
assert_eq!(samples.len(), 4);
|
||||||
|
assert_eq!(samples[2].level_dbm, -32.0);
|
||||||
|
}
|
||||||
|
assert!(!server.join().unwrap().paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stream_server_handles_interrupts_disconnects_and_io_errors() {
|
||||||
|
struct Duplex {
|
||||||
|
input: std::io::Cursor<Vec<u8>>,
|
||||||
|
output: Vec<u8>,
|
||||||
|
interrupt: bool,
|
||||||
|
fail_write: bool,
|
||||||
|
fail_read: bool,
|
||||||
|
}
|
||||||
|
impl Read for Duplex {
|
||||||
|
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
|
||||||
|
if std::mem::take(&mut self.interrupt) {
|
||||||
|
return Err(io::ErrorKind::Interrupted.into());
|
||||||
|
}
|
||||||
|
if self.fail_read {
|
||||||
|
return Err(io::ErrorKind::ConnectionReset.into());
|
||||||
|
}
|
||||||
|
self.input.read(bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Write for Duplex {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||||
|
if self.fail_write {
|
||||||
|
return Err(io::ErrorKind::BrokenPipe.into());
|
||||||
|
}
|
||||||
|
self.output.extend_from_slice(bytes);
|
||||||
|
Ok(bytes.len())
|
||||||
|
}
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let new_stream = || Duplex {
|
||||||
|
input: std::io::Cursor::new(b"pause\rresume\r".to_vec()),
|
||||||
|
output: Vec::new(),
|
||||||
|
interrupt: true,
|
||||||
|
fail_write: false,
|
||||||
|
fail_read: false,
|
||||||
|
};
|
||||||
|
let mut stream = new_stream();
|
||||||
|
let state = serve_connection(&mut stream, MockConfig::default()).unwrap();
|
||||||
|
assert!(!state.paused);
|
||||||
|
assert!(stream.output.starts_with(b"ch>"));
|
||||||
|
let state = serve_connection(
|
||||||
|
new_stream(),
|
||||||
|
MockConfig {
|
||||||
|
fault: MockFault::Disconnect,
|
||||||
|
fault_command: "pause".into(),
|
||||||
|
..MockConfig::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(state.commands.len(), 1);
|
||||||
|
let mut stream = new_stream();
|
||||||
|
stream.fail_write = true;
|
||||||
|
assert_eq!(
|
||||||
|
serve_connection(stream, MockConfig::default())
|
||||||
|
.unwrap_err()
|
||||||
|
.kind(),
|
||||||
|
io::ErrorKind::BrokenPipe
|
||||||
|
);
|
||||||
|
let mut stream = new_stream();
|
||||||
|
stream.fail_read = true;
|
||||||
|
assert_eq!(
|
||||||
|
serve_connection(stream, MockConfig::default())
|
||||||
|
.unwrap_err()
|
||||||
|
.kind(),
|
||||||
|
io::ErrorKind::ConnectionReset
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue