diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..2588efa --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,44 @@ +# Testing without a tinySA + +The library exposes configuration, protocol, transport, acquisition and CSV +boundaries independently of the terminal. Tests use small synthetic byte +transcripts rather than opening a serial device. They are regression checks, +not proof of behavior on a particular model or firmware. + +```console +cargo test --locked --all-targets --all-features +cargo test --locked --doc +``` + +| Boundary | Regression cases | +| --- | --- | +| Configuration | Embedded defaults, legacy flat keys, partial nested overrides, unknown/malformed values, numeric and path bounds, round trips, and failed replacement preservation. | +| Protocol | Basic mode boundaries, point/repeat validation, truncated/extra records, alignment, closing brace, binary delimiter bytes, little-endian levels, offset and both frequency-axis conventions. | +| Transport | One-byte/fragmented reads, multiple responses in one read, retained bytes after prompts, partial writes, invalid command lines, EOF, timeout, response size limits and raw-body framing. | +| Acquisition | Exact command ordering, optional legacy pre-scan, progress completion, successful decoding, resume after malformed frames, and preservation of acquisition plus recovery errors. | +| Export | Header/units, deterministic CSV values, propagated write failures and collision-safe output files. | + +`Shell` accepts `T: Read + Write`. To add a regression, provide a transcript +reader and capture its writes; vary read chunk size so a token may cross any +read boundary. Test both expected output and error behavior. Keep command side +effects outside logging macros because disabled log levels do not evaluate +format arguments. + +`decode_frame` receives exactly the framed body (`{`, records, `}`), without +shell echo or prompt. Use raw bytes in tests: converting binary through UTF-8 +can destroy the failure being reproduced. Check every truncated prefix when a +parser changes, and include payload bytes that equal framing characters. + +`write_csv` accepts a writer; use an in-memory vector or a writer that fails +partway through. Filesystem tests use separate temporary directories and clean +up after themselves. They must never write shared public assets. + +Run the coverage alias and badge tests as described in +[security and CI](security-and-ci.md). Keep the minimum tied to an actual +measurement over production code. Report test counts and hardware limitations +alongside percentages; a high line percentage does not test RF correctness. + +Hardware validation still requires a known model/version, safe RF input, and a +bounded capture of the real command/response sequence. In particular, verify +frequency-axis policy, the legacy preparatory scan, zero-offset acceptance and +resume behavior against the connected firmware before changing their defaults. diff --git a/src/acquisition.rs b/src/acquisition.rs new file mode 100644 index 0000000..ef26a94 --- /dev/null +++ b/src/acquisition.rs @@ -0,0 +1,238 @@ +//! Acquisition orchestration over an injected shell connection. +//! +//! This layer owns command ordering and progress, but not port discovery, files, +//! UI state or threads. After attempting `pause`, it always attempts `resume`, +//! preserving both failures when recovery also fails. This is not full device +//! state restoration or capability negotiation. + +use crate::{ + config::{ScanConfig, SerialConfig}, + protocol::{self, ProtocolError, Sample, ScanRequest}, + transport::{Shell, TransportError}, +}; +use std::{ + io::{Read, Write}, + time::Duration, +}; + +/// UI-neutral acquisition notifications. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ScanEvent { + /// Description of the active operation. + Message(&'static str), + /// Approximate completion percentage, from 0 through 100. + Progress(u8), + /// Unparsed version and information replies; not a verified model identity. + InstrumentInfo(String), +} + +/// Failure running a scan; no output file is created by this layer. +#[derive(Debug, thiserror::Error)] +pub enum AcquisitionError { + /// An I/O or shell framing failure. + #[error(transparent)] + Transport(#[from] TransportError), + /// Invalid request or malformed binary frame. + #[error(transparent)] + Protocol(#[from] ProtocolError), + /// An identification reply contained no content. + #[error("the instrument returned an empty version or info reply")] + MissingIdentity, + /// Both acquisition and the subsequent resume attempt failed. + #[error("{primary}; additionally, resume failed: {recovery}")] + Recovery { + /// Original acquisition failure. + #[source] + primary: Box, + /// Failure attempting to restart the instrument's normal sweep. + recovery: TransportError, + }, +} + +/// Execute a Basic acquisition and return validated samples without file I/O. +/// +/// Settings should come from a validated [`crate::config::Config`]. The request +/// is revalidated before any command. Version/info are retained verbatim; their +/// presence does not prove the device accepted all later commands. +pub fn acquire( + shell: &mut Shell, + request: &ScanRequest, + scan: &ScanConfig, + serial: &SerialConfig, + mut report: impl FnMut(ScanEvent), +) -> Result, AcquisitionError> { + let mode = request.input_mode()?; + let delay = Duration::from_millis(serial.command_delay_ms); + let settle = Duration::from_millis(serial.settle_delay_ms); + report(ScanEvent::Message("Identifying instrument")); + report(ScanEvent::Progress(5)); + shell.synchronize()?; + let version = shell.command("version", delay, settle)?; + let info = shell.command("info", delay, settle)?; + if version.trim().is_empty() || info.trim().is_empty() { + return Err(AcquisitionError::MissingIdentity); + } + report(ScanEvent::InstrumentInfo(format!("{version}{info}"))); + for command in ["leveloffset", "vbat", "usart_cfg", "threads"] { + let response = shell.command(command, delay, settle)?; + log::debug!("{command}: {response}"); + } + report(ScanEvent::Message("Configuring scan")); + shell.command(&format!("repeat {}", request.repeat), delay, settle)?; + shell.command(&format!("zero {}", scan.zero_offset), delay, settle)?; + shell.command("marker", delay, settle)?; + report(ScanEvent::Progress(20)); + // Pause may take effect even when its response times out, so recovery also + // covers failure receiving the pause response itself. + let result = (|| { + shell.command("pause", delay, settle)?; + shell.command(&format!("mode {} input", mode.as_str()), delay, settle)?; + shell.command(&format!("sweep start {}", request.start_hz), delay, settle)?; + shell.command(&format!("sweep stop {}", request.stop_hz), delay, settle)?; + shell.command("sweep", delay, settle)?; + if scan.legacy_pre_scan { + shell.command( + &format!("scan {} {} 290 101", request.start_hz, request.stop_hz), + Duration::from_millis(serial.scan_delay_ms), + settle, + )?; + } + report(ScanEvent::Message("Acquiring samples")); + shell.send(&format!( + "scanraw {} {} {}", + request.start_hz, request.stop_hz, request.points + ))?; + let frame = shell.read_frame(request, |received, expected| { + report(ScanEvent::Progress((20 + received * 75 / expected) as u8)) + })?; + Ok(protocol::decode_frame( + &frame, + request, + scan.zero_offset, + scan.frequency_axis, + )?) + })(); + let recovery = shell.command("resume", delay, settle); + match (result, recovery) { + (Ok(samples), Ok(_)) => { + report(ScanEvent::Message("Acquisition complete")); + report(ScanEvent::Progress(100)); + Ok(samples) + } + (Err(primary), Err(recovery)) => Err(AcquisitionError::Recovery { + primary: Box::new(primary), + recovery, + }), + (Err(error), Ok(_)) => Err(error), + (Ok(_), Err(error)) => Err(error.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::Config; + use std::{ + io::{self, Cursor}, + sync::{Arc, Mutex}, + }; + + /// Scripted replies plus shared command capture, independent of serialport. + struct Transcript { + input: Cursor>, + commands: Arc>>, + } + impl Read for Transcript { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + self.input.read(bytes) + } + } + impl Write for Transcript { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.commands.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + fn exercise( + frame: &[u8], + resume: bool, + legacy: bool, + ) -> ( + Result, AcquisitionError>, + String, + Vec, + ) { + let mut config = Config::default(); + config.serial.command_delay_ms = 0; + config.serial.settle_delay_ms = 0; + config.serial.scan_delay_ms = 0; + config.scan.legacy_pre_scan = legacy; + let request = ScanRequest { + start_hz: 240_000_000, + stop_hz: 960_000_000, + points: 2, + repeat: 1, + }; + let mut input = b"ch>version 1\rch>Basic\rch>".to_vec(); + // Four diagnostic queries, repeat/zero/marker, pause, mode and three sweep commands. + input.extend_from_slice(b"okch>".repeat(12 + usize::from(legacy)).as_slice()); + input.extend_from_slice(frame); + input.extend_from_slice(b"ch>"); + if resume { + input.extend_from_slice(b"okch>"); + } + let commands = Arc::new(Mutex::new(Vec::new())); + let mut shell = Shell::new( + Transcript { + input: Cursor::new(input), + commands: commands.clone(), + }, + 256, + ); + let mut events = Vec::new(); + let result = acquire( + &mut shell, + &request, + &config.scan, + &config.serial, + |event| events.push(event), + ); + let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap(); + (result, written, events) + } + + #[test] + fn full_acquisition_preserves_command_order_and_reports_progress() { + let (result, commands, events) = exercise(b"{x\0\x08x\0\x10}", true, true); + assert_eq!(result.unwrap().len(), 2); + assert_eq!(commands, "version\rinfo\rleveloffset\rvbat\rusart_cfg\rthreads\rrepeat 1\rzero 128\rmarker\rpause\rmode high input\rsweep start 240000000\rsweep stop 960000000\rsweep\rscan 240000000 960000000 290 101\rscanraw 240000000 960000000 2\rresume\r"); + assert_eq!(events.last(), Some(&ScanEvent::Progress(100))); + } + + #[test] + fn legacy_pre_scan_can_be_disabled() { + let (result, commands, _) = exercise(b"{x\0\x08x\0\x10}", true, false); + assert!(result.is_ok()); + assert!(!commands.contains("\rscan ")); + } + + #[test] + fn malformed_frames_still_resume_and_preserve_original_error() { + let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", true, true); + assert!(matches!( + result, + Err(AcquisitionError::Protocol(ProtocolError::Alignment { + index: 0, + .. + })) + )); + assert!(commands.ends_with("resume\r")); + let (result, commands, _) = exercise(b"{y\0\x08x\0\x10}", false, true); + assert!(matches!(result, Err(AcquisitionError::Recovery { .. }))); + assert!(commands.ends_with("resume\r")); + } +} diff --git a/src/export.rs b/src/export.rs new file mode 100644 index 0000000..cf50b1e --- /dev/null +++ b/src/export.rs @@ -0,0 +1,117 @@ +//! CSV serialization and collision-safe file creation, separate from decoding. + +use crate::{config::OutputConfig, protocol::Sample}; +use chrono::Local; +use std::{ + fs::{self, OpenOptions}, + io::{self, BufWriter, Write}, + path::PathBuf, +}; + +/// Write sample values to any writer, optionally with an explicit units header. +/// +/// The caller decides when/how to open and flush a file. Every write error is +/// propagated; decimal formatting uses Rust's locale-independent representation. +pub fn write_csv( + mut writer: impl Write, + samples: &[Sample], + include_header: bool, +) -> io::Result<()> { + if include_header { + writeln!(writer, "frequency_MHz,level_dBm")?; + } + for sample in samples { + writeln!(writer, "{},{}", sample.frequency_mhz, sample.level_dbm)?; + } + Ok(()) +} + +/// Save an already validated scan without overwriting any previous acquisition. +/// +/// Names use local time plus microseconds and a collision counter. A file is +/// reported only after flushing; failed writes remove the incomplete file. +/// Readers may see the in-progress file, so only the returned path means complete. +pub fn save_csv(samples: &[Sample], settings: &OutputConfig) -> io::Result { + fs::create_dir_all(&settings.directory)?; + let stamp = Local::now().format("%Y%m%d %H_%M_%S_%6f").to_string(); + for suffix in 0..100 { + let path = settings + .directory + .join(format!("{}_{stamp}_{suffix}.csv", settings.filename_prefix)); + let file = match OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + }; + let mut writer = BufWriter::new(file); + let result = write_csv(&mut writer, samples, settings.include_header) + .and_then(|()| writer.flush()) + .and_then(|()| writer.get_ref().sync_all()); + drop(writer); + if let Err(error) = result { + let _ = fs::remove_file(&path); + return Err(error); + } + return Ok(path); + } + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "could not allocate a unique scan filename", + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn csv_has_explicit_units_only_when_requested() { + let samples = [Sample { + frequency_mhz: 240.5, + level_dbm: -64.25, + }]; + let mut bytes = Vec::new(); + write_csv(&mut bytes, &samples, false).unwrap(); + assert_eq!(bytes, b"240.5,-64.25\n"); + bytes.clear(); + write_csv(&mut bytes, &samples, true).unwrap(); + assert_eq!(bytes, b"frequency_MHz,level_dBm\n240.5,-64.25\n"); + } + + #[test] + fn write_errors_are_propagated() { + struct Broken; + impl Write for Broken { + fn write(&mut self, _: &[u8]) -> io::Result { + Err(io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + assert_eq!( + write_csv(Broken, &[], true).unwrap_err().kind(), + io::ErrorKind::BrokenPipe + ); + } + + #[test] + fn scans_do_not_overwrite_each_other() { + let directory = std::env::temp_dir().join(format!("tiny-wb-export-{}", std::process::id())); + let settings = OutputConfig { + directory: directory.clone(), + filename_prefix: "test".into(), + include_header: false, + }; + let samples = [Sample { + frequency_mhz: 1.0, + level_dbm: -1.0, + }]; + let first = save_csv(&samples, &settings).unwrap(); + let second = save_csv(&samples, &settings).unwrap(); + assert_ne!(first, second); + assert_eq!(fs::read_to_string(first).unwrap(), "1,-1\n"); + assert_eq!(fs::read_to_string(second).unwrap(), "1,-1\n"); + fs::remove_dir_all(directory).unwrap(); + } +} diff --git a/src/lib.rs b/src/lib.rs index 8b57bbd..2fa0152 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,5 +5,9 @@ #![warn(missing_docs)] +pub mod acquisition; pub mod config; +pub mod export; +pub mod protocol; mod storage; +pub mod transport; diff --git a/src/protocol.rs b/src/protocol.rs new file mode 100644 index 0000000..d55bfae --- /dev/null +++ b/src/protocol.rs @@ -0,0 +1,279 @@ +//! Basic input selection and pure, length-checked `scanraw` decoding. +//! +//! Wire invariants live here: delimiters, little-endian 16-bit samples and +//! 1/32 dB scaling. No serial port, clock, file or terminal is accessed. + +use crate::config::FrequencyAxis; + +/// Highest supported Basic frequency, in Hz. Ultra is not negotiated yet. +pub const BASIC_MAX_HZ: u64 = 960_000_000; +/// Host allocation limit retained from the original UI. +pub const MAX_POINTS: usize = 1_000_001; + +/// One decoded observation; CSV and UI both consume these physical units. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Sample { + /// Frequency assigned by the selected host labeling convention, in MHz. + pub frequency_mhz: f64, + /// Level after subtracting the configured raw offset, in dBm. + pub level_dbm: f64, +} + +/// Validatable acquisition parameters, independent of UI widgets. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ScanRequest { + /// First requested frequency, in Hz. + pub start_hz: u64, + /// Requested upper boundary, in Hz. + pub stop_hz: u64, + /// Number of raw sample records. + pub points: usize, + /// Measurements per frequency (1–1,000). + pub repeat: usize, +} + +/// The Basic's physical input path; this is not an Ultra capability model. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InputMode { + /// Input path below 350 MHz. + Low, + /// High path, also used for a span starting at/above 240 MHz and crossing 350 MHz. + High, +} + +impl InputMode { + /// Keyword used by the `mode ... input` shell command. + pub fn as_str(self) -> &'static str { + match self { + Self::Low => "low", + Self::High => "high", + } + } +} + +/// Validation and frame errors, with bounded diagnostics rather than raw dumps. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum ProtocolError { + /// Invalid acquisition parameters or unsupported input span. + #[error("invalid scan request: {0}")] + InvalidRequest(String), + /// The supplied frame does not begin with `{`. + #[error("raw scan is missing its opening brace")] + MissingStart, + /// The frame length differs from the requested number of records. + #[error("raw frame has {actual} bytes; expected {expected}")] + Length { + /// Expected body length, including braces. + expected: usize, + /// Actual body length, including braces. + actual: usize, + }, + /// A record does not begin with the alignment byte `x`. + #[error("sample {index} has alignment byte 0x{found:02x}; expected 0x78")] + Alignment { + /// Zero-based sample index. + index: usize, + /// Received alignment byte. + found: u8, + }, + /// No closing brace occurs at the exact end of the requested records. + #[error("raw scan is missing its closing brace")] + MissingEnd, +} + +impl ScanRequest { + /// Validate point/repeat bounds and choose the historical Basic input path. + pub fn input_mode(&self) -> Result { + if !(2..=MAX_POINTS).contains(&self.points) || !(1..=1000).contains(&self.repeat) { + return Err(ProtocolError::InvalidRequest( + "points must be 2..=1000001 and repeat 1..=1000".into(), + )); + } + if self.start_hz > self.stop_hz || self.stop_hz > BASIC_MAX_HZ { + return Err(ProtocolError::InvalidRequest( + "frequencies must be ordered within 0–960 MHz".into(), + )); + } + if self.stop_hz < 350_000_000 { + Ok(InputMode::Low) + } else if self.start_hz >= 240_000_000 { + Ok(InputMode::High) + } else { + Err(ProtocolError::InvalidRequest( + "a span crossing 350 MHz must start at or above 240 MHz".into(), + )) + } + } + + /// Exact framed byte count; validation happens before multiplication/allocation. + pub fn frame_len(&self) -> Result { + self.input_mode()?; + Ok(self.points * 3 + 2) + } +} + +/// Decode exactly one raw body, including braces and excluding echo/prompt. +/// +/// `zero_offset` must match the `zero` command sent to the device. Endpoint +/// labeling is explicit because the historical host and reviewed firmware use +/// different denominators. Malformed/short/extra records are rejected before +/// callers can export a completed scan. +pub fn decode_frame( + frame: &[u8], + request: &ScanRequest, + zero_offset: u16, + axis: FrequencyAxis, +) -> Result, ProtocolError> { + let expected = request.frame_len()?; + if zero_offset > 2047 { + return Err(ProtocolError::InvalidRequest( + "zero offset must be 0..=2047".into(), + )); + } + if frame.first() != Some(&b'{') { + return Err(ProtocolError::MissingStart); + } + if frame.len() != expected { + return Err(ProtocolError::Length { + expected, + actual: frame.len(), + }); + } + if frame.last() != Some(&b'}') { + return Err(ProtocolError::MissingEnd); + } + let intervals = match axis { + FrequencyAxis::Inclusive => request.points - 1, + FrequencyAxis::Firmware => request.points, + }; + let step = (request.stop_hz - request.start_hz) as f64 / intervals as f64; + frame[1..frame.len() - 1] + .chunks_exact(3) + .enumerate() + .map(|(index, record)| { + if record[0] != b'x' { + return Err(ProtocolError::Alignment { + index, + found: record[0], + }); + } + Ok(Sample { + frequency_mhz: (request.start_hz as f64 + index as f64 * step) / 1_000_000.0, + level_dbm: f64::from(u16::from_le_bytes([record[1], record[2]])) / 32.0 + - f64::from(zero_offset), + }) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + fn request() -> ScanRequest { + ScanRequest { + start_hz: 240_000_000, + stop_hz: 960_000_000, + points: 2, + repeat: 1, + } + } + + #[test] + fn basic_modes_and_boundaries() { + for (start_hz, stop_hz, expected) in [ + (0, 349_999_999, Some(InputMode::Low)), + (0, 350_000_000, None), + (240_000_000, 350_000_000, Some(InputMode::High)), + (350_000_000, 960_000_000, Some(InputMode::High)), + (960_000_000, 960_000_000, Some(InputMode::High)), + (960_000_000, 960_000_001, None), + (100, 99, None), + ] { + assert_eq!( + ScanRequest { + start_hz, + stop_hz, + ..request() + } + .input_mode() + .ok(), + expected + ); + } + for points in [0, 1, MAX_POINTS + 1, usize::MAX] { + assert!(ScanRequest { + points, + ..request() + } + .frame_len() + .is_err()); + } + assert!(ScanRequest { + repeat: 0, + ..request() + } + .input_mode() + .is_err()); + assert!(ScanRequest { + repeat: 1001, + ..request() + } + .input_mode() + .is_err()); + } + + #[test] + fn little_endian_levels_offsets_and_both_axes() { + let frame = b"{x\x00\x08x\x00\x10}"; + let inclusive = decode_frame(frame, &request(), 128, FrequencyAxis::Inclusive).unwrap(); + assert_eq!( + inclusive, + vec![ + Sample { + frequency_mhz: 240.0, + level_dbm: -64.0 + }, + Sample { + frequency_mhz: 960.0, + level_dbm: 0.0 + } + ] + ); + let firmware = decode_frame(frame, &request(), 174, FrequencyAxis::Firmware).unwrap(); + assert_eq!( + firmware[1], + Sample { + frequency_mhz: 600.0, + level_dbm: -46.0 + } + ); + } + + #[test] + fn truncated_extra_and_misaligned_frames_are_rejected_without_panics() { + let frame = b"{x\x00\x08x\x00\x10}"; + for length in 0..frame.len() { + assert!( + decode_frame(&frame[..length], &request(), 128, FrequencyAxis::Inclusive).is_err() + ); + } + for frame in [ + b"{x\x00\x08x\x00\x10}extra".as_slice(), + b"{y\x00\x08x\x00\x10}", + b"{x\x00\x08x\x00\x10!", + b"{x\x00\x08} ", + ] { + assert!(decode_frame(frame, &request(), 128, FrequencyAxis::Inclusive).is_err()); + } + } + + #[test] + fn binary_delimiters_are_sample_data() { + let samples = decode_frame(b"{x{}xch}", &request(), 128, FrequencyAxis::Inclusive).unwrap(); + assert_eq!(samples.len(), 2); + assert_eq!( + samples[0].level_dbm, + f64::from(u16::from_le_bytes(*b"{}")) / 32.0 - 128.0 + ); + } +} diff --git a/src/transport.rs b/src/transport.rs new file mode 100644 index 0000000..45e31b9 --- /dev/null +++ b/src/transport.rs @@ -0,0 +1,272 @@ +//! Buffered mixed text/binary shell transport over any `Read + Write` stream. +//! +//! Prompt matching spans reads and retains bytes after the prompt. Raw frames +//! are consumed by exact record count before text prompt matching resumes. +//! Read timeouts are supplied by the underlying stream and remain errors. + +use crate::protocol::{ProtocolError, ScanRequest}; +use std::{ + io::{self, BufReader, Read, Write}, + thread, + time::Duration, +}; + +/// Console prompt outside binary frames. +const PROMPT: &[u8] = b"ch>"; + +/// Transport errors preserve their I/O or protocol source. +#[derive(Debug, thiserror::Error)] +pub enum TransportError { + /// Read/write/flush failed, including timeout or disconnect. + #[error("serial transport: {0}")] + Io(#[from] io::Error), + /// A response exceeded its configured memory bound. + #[error("serial response exceeds {0} bytes")] + ResponseTooLong(usize), + /// A command contains a terminator or is empty/non-ASCII. + #[error("a shell command must be one nonempty printable ASCII line")] + InvalidCommand, + /// An invalid scan request was rejected before reading. + #[error(transparent)] + Protocol(#[from] ProtocolError), +} + +/// A single buffered connection; do not bypass it to read from the same stream. +pub struct Shell { + /// Persistent buffering retains bytes beyond a prompt or raw frame. + stream: BufReader, + /// Upper bound for text and pre-frame echo, independent of raw sample size. + max_response_bytes: usize, +} + +impl Shell { + /// Wrap a serial stream or a deterministic in-memory transcript. + pub fn new(stream: T, max_response_bytes: usize) -> Self { + Self { + stream: BufReader::new(stream), + max_response_bytes, + } + } + + /// Write a complete shell command and carriage return, including partial writes. + pub fn send(&mut self, command: &str) -> Result<(), TransportError> { + if command.is_empty() || !command.bytes().all(|b| (b' '..=b'~').contains(&b)) { + return Err(TransportError::InvalidCommand); + } + self.stream.get_mut().write_all(command.as_bytes())?; + self.stream.get_mut().write_all(b"\r")?; + self.stream.get_mut().flush()?; + Ok(()) + } + + /// Read one prompt-terminated text response, excluding the prompt itself. + /// + /// A timeout or EOF before the complete prompt is an error, never success + /// with partial text. Bytes after the prompt remain buffered for the next call. + pub fn read_text(&mut self) -> Result, TransportError> { + let mut response = Vec::new(); + loop { + let mut byte = [0]; + self.stream.read_exact(&mut byte)?; + response.push(byte[0]); + if response.ends_with(PROMPT) { + response.truncate(response.len() - PROMPT.len()); + return Ok(response); + } + if response.len() >= self.max_response_bytes { + return Err(TransportError::ResponseTooLong(self.max_response_bytes)); + } + } + } + + /// Drain an optional stale response before the first request. + /// + /// Idle timeout is expected here only. Disconnects and oversized responses + /// remain errors. No subsequent command uses this relaxed timeout behavior. + pub fn synchronize(&mut self) -> Result<(), TransportError> { + match self.read_text() { + Ok(_) => Ok(()), + Err(TransportError::Io(error)) + if matches!( + error.kind(), + io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock + ) => + { + Ok(()) + } + Err(error) => Err(error), + } + } + + /// Send and consume one text command with configurable compatibility delays. + pub fn command( + &mut self, + command: &str, + delay: Duration, + settle: Duration, + ) -> Result { + self.send(command)?; + thread::sleep(delay); + let response = self.read_text()?; + thread::sleep(settle); + Ok(String::from_utf8_lossy(&response).into_owned()) + } + + /// Consume echo, an exact raw body, then its trailing shell prompt. + /// + /// Progress receives `(received_body_bytes, expected_body_bytes)`. A short + /// frame, missing closing brace or absent prompt fails rather than returning + /// a successful partial acquisition. No text token is searched inside samples. + pub fn read_frame( + &mut self, + request: &ScanRequest, + mut progress: impl FnMut(usize, usize), + ) -> Result, TransportError> { + let expected = request.frame_len()?; + let mut byte = [0]; + let mut prefix_len = 0; + loop { + self.stream.read_exact(&mut byte)?; + if byte[0] == b'{' { + break; + } + prefix_len += 1; + if prefix_len >= self.max_response_bytes { + return Err(TransportError::ResponseTooLong(self.max_response_bytes)); + } + } + let mut frame = vec![0; expected]; + frame[0] = b'{'; + let mut received = 1; + for chunk in frame[1..].chunks_mut(4096) { + self.stream.read_exact(chunk)?; + received += chunk.len(); + progress(received, expected); + } + if frame.last() != Some(&b'}') { + return Err(ProtocolError::MissingEnd.into()); + } + self.read_text()?; + Ok(frame) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + /// Simulate arbitrary read fragmentation and short writes without hardware. + struct Duplex { + input: Cursor>, + written: Vec, + chunk: usize, + } + impl Read for Duplex { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + let limit = buffer.len().min(self.chunk); + self.input.read(&mut buffer[..limit]) + } + } + impl Write for Duplex { + fn write(&mut self, bytes: &[u8]) -> io::Result { + let count = bytes.len().min(2); + self.written.extend_from_slice(&bytes[..count]); + Ok(count) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + fn shell(bytes: &[u8], chunk: usize) -> Shell { + Shell::new( + Duplex { + input: Cursor::new(bytes.to_vec()), + written: Vec::new(), + chunk, + }, + 256, + ) + } + + #[test] + fn prompts_span_reads_and_preserve_following_bytes() { + for chunk in 1..=20 { + let mut shell = shell(b"firstch>secondch>", chunk); + assert_eq!(shell.read_text().unwrap(), b"first"); + assert_eq!(shell.read_text().unwrap(), b"second"); + } + } + + #[test] + fn commands_use_complete_writes_and_reject_injected_lines() { + let mut shell = shell(b"replych>", 1); + assert_eq!( + shell + .command("version", Duration::ZERO, Duration::ZERO) + .unwrap(), + "reply" + ); + assert_eq!(shell.stream.get_ref().written, b"version\r"); + for command in ["", "scan\rresume", "scan\n", "\0"] { + assert!(shell.send(command).is_err()); + } + assert_eq!(shell.stream.get_ref().written, b"version\r"); + } + + #[test] + fn frame_is_length_delimited_and_next_response_is_retained() { + let request = ScanRequest { + start_hz: 0, + stop_hz: 10, + points: 2, + repeat: 1, + }; + for chunk in 1..=32 { + let mut shell = shell(b"scanraw echo\r\n{x{}xch}\r\nch>nextch>", chunk); + let mut last = (0, 0); + let frame = shell + .read_frame(&request, |received, total| last = (received, total)) + .unwrap(); + assert_eq!(frame, b"{x{}xch}"); + assert_eq!(last, (8, 8)); + assert_eq!(shell.read_text().unwrap(), b"next"); + } + } + + #[test] + fn eof_truncation_and_size_limits_are_errors() { + assert!(shell(b"missing prompt", 5).read_text().is_err()); + assert!(shell(&[b'a'; 257], 32).read_text().is_err()); + let request = ScanRequest { + start_hz: 0, + stop_hz: 10, + points: 2, + repeat: 1, + }; + for input in [b"{x12}".as_slice(), b"{x12x34}", b"{x12x34!ch>"] { + assert!(shell(input, 1).read_frame(&request, |_, _| {}).is_err()); + } + } + + #[test] + fn timeout_is_only_tolerated_during_initial_synchronization() { + struct Timeout; + impl Read for Timeout { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Err(io::ErrorKind::TimedOut.into()) + } + } + impl Write for Timeout { + fn write(&mut self, b: &[u8]) -> io::Result { + Ok(b.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + let mut shell = Shell::new(Timeout, 256); + assert!(shell.synchronize().is_ok()); + assert!(shell.read_text().is_err()); + } +}