From fd9c820a59d575ab5f35fccefb39ea4f4deadc6c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 7 Oct 2026 10:03:05 +0200 Subject: [PATCH] feat: support tinySA Ultra+ ZS406 --- README.md | 8 +- config/default.toml | 4 + config/mock-ultra.toml | 3 +- docs/configuration.md | 15 ++-- docs/hardware-validation.md | 33 ++++++- docs/mock-device.md | 4 +- docs/roadmap.md | 8 +- docs/tiny-wb-operations.md | 10 ++- docs/tinysa-field-guide.md | 6 +- docs/ultra-support.md | 43 +++++---- docs/usb-protocol.md | 4 +- examples/validate-hardware.rs | 57 +++++++++--- scripts/test-hardware.sh | 4 +- src/acquisition.rs | 104 ++++++++++++++++++++-- src/config.rs | 19 ++-- src/device.rs | 163 ++++++++++++++++++++++++++++++++-- src/ui/mod.rs | 6 +- 17 files changed, 421 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 96d1313..3910535 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,11 @@ workflow and for Rust applications that need its reusable acquisition library. - tinySA Basic low and high inputs are supported through 960 MHz, subject to the instrument's path limits. -- tinySA Ultra and Ultra+ detection and acquisition are implemented for the - shared 0.1–800 MHz normal range, but still await physical hardware - qualification. +- tinySA Ultra-family detection and acquisition are implemented for the shared + 0.1–800 MHz normal range. A detected Ultra+ ZS406 additionally supports its + 0.1–900 MHz normal range and explicit opt-in Ultra mode through 5.4 GHz. +- ZS407 extended mode and harmonic-mode reception remain unsupported. Hardware + validation proves communications and framing, not RF frequency/level accuracy. See the [compatibility matrix](docs/tiny-wb-operations.md#compatibility-matrix) and [Ultra support scope](docs/ultra-support.md) before relying on a particular diff --git a/config/default.toml b/config/default.toml index 42fc06d..bc629dd 100644 --- a/config/default.toml +++ b/config/default.toml @@ -27,6 +27,10 @@ preferred_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"] # Detect Basic versus Ultra from version/info and apply the corresponding scan # profile. `basic` or `ultra` can require (but never fake) an expected family. device_model = "auto" +# Permit a detected ZS406 to enter Ultra mode for analyzer scans above its +# 900 MHz normal-mode ceiling, up to 5.4 GHz. This changes instrument state and +# acknowledges Ultra-mode alias/spur/LO-leakage limitations; it never enables RF output. +enable_ultra_mode = false # Select the detected model's native scanraw bias: Basic 128, Ultra 174. auto_zero_offset = true # Manual fallback used only when auto_zero_offset is false. The selected value diff --git a/config/mock-ultra.toml b/config/mock-ultra.toml index 7a2e980..4ae9bec 100644 --- a/config/mock-ultra.toml +++ b/config/mock-ultra.toml @@ -1,4 +1,5 @@ -# Synthetic Ultra identity/syntax; production supports the common 0.1–800 MHz range. +# Synthetic generic Ultra identity/syntax. Production additionally recognizes +# explicit ZS406 identity for normal scans through 900 MHz and opt-in Ultra mode. model = "ultra" echo = true read_chunk_bytes = 7 diff --git a/docs/configuration.md b/docs/configuration.md index 1bb4bf5..4cc81f5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -31,15 +31,16 @@ points = 10001 repeat = 1 ``` -Start/stop frequencies are **MHz**. The Basic envelope remains 0–960 MHz, -with stop at least 10 MHz; the protocol separately rejects spans that cannot -use one input path. Values must be ordered. The selected baud rate must be in -`serial.baudrates`; points and repeat must fit the configured bounds. +Start/stop frequencies are **MHz**. The shared entry envelope is 0–5,400 MHz, +with stop at least 10 MHz; detected model/revision policy applies before the +instrument is mutated. Basic remains limited to 960 MHz, generic Ultra to 800 +MHz, and ZS406 normal mode to 900 MHz. Values must be ordered. The selected baud +rate must be in `serial.baudrates`; points and repeat must fit the configured bounds. | Section | Settings and units | | --- | --- | | `serial` | Read timeout and command/settling/pre-scan delays in milliseconds; bounded text response size in bytes; baud-rate choices and preferred ports. | -| `scan` | Raw zero offset in dB, frequency/sample keyboard steps, sample/repeat limits, frequency-axis convention, and legacy pre-scan toggle. | +| `scan` | Raw zero offset in dB, explicit ZS406 Ultra-mode opt-in, frequency/sample keyboard steps, sample/repeat limits, frequency-axis convention, and legacy pre-scan toggle. | | `ui` | Event polling interval in milliseconds and finite increasing chart bounds in dBm. | | `output` | CSV directory, filename prefix, and optional column header. | | `logging` | Logger filter expression and destination directory. | @@ -47,7 +48,9 @@ use one input path. Values must be ordered. The selected baud rate must be in `scan.device_model = "auto"` detects the family before changing settings. `scan.auto_zero_offset = true` selects Basic 128 or Ultra 174 and verifies the `zero` readback. To retain a manual `scan.zero_offset`, set automatic selection -to false. See [support and migration](ultra-support.md). The wire record has no +to false. `scan.enable_ultra_mode = true` explicitly permits a detected ZS406 +to receive above 900 MHz through 5.4 GHz; it is false by default and never +enables generator output. See [support and migration](ultra-support.md). The wire record has no model-specific padding; see [level conversion](usb-protocol.md#level-conversion-and-zero). For example, this partial file changes the serial timeout and output format diff --git a/docs/hardware-validation.md b/docs/hardware-validation.md index a1a2ea2..c842f7d 100644 --- a/docs/hardware-validation.md +++ b/docs/hardware-validation.md @@ -2,7 +2,7 @@ This checklist qualifies one physical instrument and firmware build. A passing mock or CI run is not hardware evidence. Run the validator once with a tinySA -Basic and once with a tinySA Ultra; keep their reports separate. +Basic and once with each supported tinySA Ultra profile; keep reports separate. ## Before each run @@ -13,6 +13,7 @@ Basic and once with a tinySA Ultra; keep their reports separate. can open the USB serial port without running the validator as root. - [ ] If the front-panel configuration matters, save a preset. The validator changes repeat, raw zero offset, input mode, sweep limits, and pause state. + The ZS406 profile also enables Ultra mode, which firmware may retain. From the repository root, run exactly one command: @@ -26,6 +27,12 @@ For an Ultra, use: scripts/test-hardware.sh ultra ``` +For the ZS406 normal and non-harmonic Ultra ranges, use: + +```console +scripts/test-hardware.sh zs406 +``` + The script asks when to unplug and plug the instrument so it can detect the new serial port. If discovery is ambiguous, choose from the displayed ports. To skip discovery, pass `--port /dev/ttyACM0` or `--port COM7`. It builds the validator, @@ -76,6 +83,30 @@ or above 350 MHz, level accuracy, or frequency accuracy. Those require model-aware acquisition and a controlled reference source; do not infer them from this communications test. +## ZS406 range acceptance + +- [ ] The rear label says ZS406 and identity reports `ZS406` or hardware V0.4.6. +- [ ] `normal` (0.1–900 MHz) and `ultra` (900 MHz–5.4 GHz) each report `PASS` + and create 101-row CSV files with units headers. +- [ ] The report records `enable_ultra_mode=false` for `normal`, `true` for + `ultra`, and `raw_level_offset_db=174` for both. +- [ ] The live front-panel sweep resumes and the final `zs406-report.txt` records + affirmative operator confirmation. + +This validates identity, accepted sweep bounds, command ordering, binary +framing and finite decoded values across both ranges. With no controlled RF +source it does not establish frequency accuracy, level accuracy, sensitivity, +spur rejection or the authenticity of displayed signals. + +### Recorded ZS406 evidence + +The ZS406 acquisition profile was validated on physical hardware on 2026-10-07 +with hardware V0.4.6 and firmware `tinySA4_v1.4-197-gaa78ccc`. The 100 kHz–900 +MHz normal scan and 900 MHz–5.4 GHz Ultra scan each returned 101 finite samples, +confirmed the requested sweep boundaries, produced CSV output, and resumed the +front-panel sweep. The RF input was unconnected. This is communications, +range-acceptance and workflow evidence, not RF frequency or level calibration. + ## Failure record - [ ] Keep the generated report and any completed CSV; do not edit them. diff --git a/docs/mock-device.md b/docs/mock-device.md index 2a08ead..a778485 100644 --- a/docs/mock-device.md +++ b/docs/mock-device.md @@ -80,7 +80,9 @@ 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 automatic detection, native offset readback and low-input acquisition. Production Ultra scans are limited -to 0.1–800 MHz; the mock's larger synthetic range is not a production capability. +to its detected model/revision policy; the mock's larger synthetic range is not +a production capability. ZS406 limits are covered by identity-policy transcript +tests rather than inferred from this generic Ultra mock. See [support scope](ultra-support.md). Samples use the reviewed firmware's integer-divided, single-precision diff --git a/docs/roadmap.md b/docs/roadmap.md index fff5716..da79031 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -31,10 +31,10 @@ See [library integration](library.md) and [mock scope](mock-device.md). ## Priority 0 — trustworthy model-aware acquisition -Initial family detection, native-offset readback and common Ultra normal-range -planning are implemented; see [support status](ultra-support.md). The broader -P01–P04 acceptance gates below remain open pending revision-specific profiles -and hardware qualification. +Initial family/revision detection, native-offset readback, common Ultra +normal-range planning and the ZS406 non-harmonic Ultra profile are implemented; +see [support status](ultra-support.md). The broader P01–P04 acceptance gates +remain open pending further revision profiles and RF accuracy qualification. - [ ] P01 **Inventory and capability negotiation** (depends F01–F04). Capture `version`, `info`, `help` and matching firmware commit/build options for Basic diff --git a/docs/tiny-wb-operations.md b/docs/tiny-wb-operations.md index d16ee98..312781e 100644 --- a/docs/tiny-wb-operations.md +++ b/docs/tiny-wb-operations.md @@ -14,7 +14,9 @@ can represent it in the UI. | tinySA Basic crossing from 240–<350 MHz into 350–960 MHz | Implemented as high input | The whole scan is forced onto the high path; the low path is not stitched to it. | | Basic span starting below 240 MHz and ending at/above 350 MHz | Rejected | One physical path cannot cover it under the client's policy. Split it into scans. | | tinySA Ultra/Ultra+ 0.1–800 MHz | Implemented; awaiting hardware qualification | Family detection, `mode low input`, automatic `zero 174` and readback verification. | -| Ultra above 800 MHz | Rejected | Revision-specific extended/normal ceilings and unlock state are not negotiated. | +| Ultra+ ZS406 0.1–900 MHz | Hardware communications validated | Explicit ZS406/V0.4.6 identity permits the full normal-mode range; RF accuracy is not qualified. | +| Ultra+ ZS406 above 900 MHz through 5.4 GHz | Opt-in; hardware communications validated | Requires `scan.enable_ultra_mode = true`, sends `ultra on`, and verifies sweep readback. Expect slower scans, aliases/spurs and RF-port LO leakage. | +| ZS407 extended mode or any harmonic mode | Rejected | Their different ceilings and measurement behavior are not implemented. | | Generator control, live streaming, capture, calibration, firmware update | Out of scope | No corresponding application workflow exists. | At the exact 350 MHz boundary, the implementation's matching rules matter: @@ -86,8 +88,8 @@ configurable; Basic frequency limits remain fixed protocol rules. | Field | Unit | Default | Step | Bounds | | --- | --- | ---: | ---: | ---: | -| Start frequency | MHz | 240 | 10 | 0–960 | -| Stop frequency | MHz | 800 | 10 | 10–960 (Ultra acquisition capped at 800) | +| Start frequency | MHz | 240 | 10 | 0–5,400 (model checked after identity) | +| Stop frequency | MHz | 800 | 10 | 10–5,400 (model checked after identity) | | Points | samples | 10,001 | 100 | 101–1,000,001 | | Repeat | measurements/point | 1 | 1 | 1–1,000 | @@ -243,7 +245,7 @@ software bug; substitute a low-level known source or recorded serial fixture. ## Remaining engineering work -Revision-specific detection, Ultra ranges above 800 MHz, overall +ZS407 extended detection, harmonic ranges above 5.4 GHz, overall transaction deadlines, cancellation/abort, full instrument-state restoration, and richer output metadata remain open. Buffered framing, strict record-count validation, reusable core interfaces and hardware-free regression tests are diff --git a/docs/tinysa-field-guide.md b/docs/tinysa-field-guide.md index 9dcadd5..6fcfbe0 100644 --- a/docs/tinysa-field-guide.md +++ b/docs/tinysa-field-guide.md @@ -304,8 +304,10 @@ version installed on the instrument. ## How this maps to tiny-wb tiny-wb detects Basic/Ultra families and applies model-specific input commands -and native encoding offsets. Ultra support currently covers 0.1–800 MHz; -extended ranges and hardware qualification remain pending. See +and native encoding offsets. Generic Ultra support covers 0.1–800 MHz; a +detected ZS406 covers normal mode through 900 MHz and explicit opt-in Ultra mode +through 5.4 GHz. Harmonic reception, ZS407 extended mode and other extended +ranges remain unsupported; RF accuracy qualification remains pending. See [support scope](ultra-support.md) and the [compatibility matrix](tiny-wb-operations.md#compatibility-matrix). For the wire format and exact command behavior, continue with diff --git a/docs/ultra-support.md b/docs/ultra-support.md index 8a20580..5ce9890 100644 --- a/docs/ultra-support.md +++ b/docs/ultra-support.md @@ -6,20 +6,25 @@ The acquisition path reads `version`, `info`, and `help` before changing scan settings. Recognized Basic (`tinySA_v…`) and Ultra-family (`tinySA4_v…`) identities select different plans. Unknown or conflicting identities fail. Explicit `scan.device_model = "basic"` or `"ultra"` requires a matching detected family; -the default is `"auto"`. Family detection does not identify a hardware revision -or certify that an arbitrary firmware build implements every command correctly. +the default is `"auto"`. Explicit identity text also distinguishes ZS405, +ZS406 and ZS407; an unrecognized revision retains the conservative family +fallback. Detection does not certify that arbitrary firmware implements every +command correctly. | Family | Implemented acquisition range | Input command | Automatic raw bias | | --- | --- | --- | --- | | Basic | Existing low/high policy through 960 MHz | `mode low input` or `mode high input` | 128 dB | -| Ultra/Ultra+ | Common normal range 0.1–800 MHz | `mode low input` | 174 dB | +| Ultra family without identified revision | Common normal range 0.1–800 MHz | `mode low input` | 174 dB | +| Ultra+ ZS406 | Normal 0.1–900 MHz; opt-in Ultra through 5.4 GHz | `mode low input`; `ultra on` above 900 MHz | 174 dB | The [official comparison](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.Comparison) -lists 800 MHz normal range for ZS405 and 900 MHz for Ultra+ revisions. This -initial implementation deliberately uses their shared 800 MHz ceiling. -Extended/Ultra/harmonic ranges, revision detection, LNA control and mode-state -restoration are not implemented. Existing instrument processing settings and -Ultra-enable state are retained; no unlock or persistent-save command is sent. +lists 800 MHz normal range for ZS405 and 900 MHz for Ultra+ revisions. ZS406 is +recognized only from explicit `ZS406` or `HW Version:V0.4.6` evidence. Above +900 MHz, `scan.enable_ultra_mode = true` is required; acquisition sends +`ultra on` and verifies that `sweep` reads back the requested boundaries. The +client stops at 5.4 GHz before harmonic mixing. It does not send `saveconfig`, +but firmware may retain Ultra mode as device state. ZS407 extended mode, +harmonic mode, LNA control and complete mode-state restoration are not implemented. The [official Ultra console snapshot](https://tinysa.org/wiki/pmwiki.php?n=TinySA4.ConsoleCommands) documents the family version prefix and zero readback. The reviewed [mode handler](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c) @@ -41,22 +46,26 @@ existing `zero_offset` value. Previously saved offsets remain parseable but are ignored while automatic selection is enabled. No configuration is rewritten until the normal save workflow runs. -The terminal uses integer MHz inputs and a shared 960 MHz entry ceiling. +The terminal uses integer MHz inputs and a shared 5,400 MHz entry ceiling. Model-specific validation runs after identification in the acquisition worker; therefore out-of-profile input is rejected before mutation, but after the UI saves the selection. Use the library for sub-MHz settings. Dynamic UI bounds -and detection before the selection screen remain future work. +and detection before the selection screen remain future work. Existing partial +configuration files adopt `scan.enable_ultra_mode = false`, so this change does +not opt them into persistent instrument-state changes. ## Verification and qualification Regression tests cover model detection, conflicts, range/path selection, automatic native offsets, command inventory, readback failures, partial I/O and resume after scan failure. Run the [local gates](security-and-ci.md#local-verification) -and `cargo coverage`. The hardware validator now requires its selected family -to match detection before changing settings and exercises Ultra below 800 MHz. +and `cargo coverage`. The hardware validator requires its selected family to +match detection before changing settings. Its `zs406` profile separately checks +0.1–900 MHz normal reception and 900 MHz–5.4 GHz opt-in Ultra reception. -This is initial software support, not a claim of hardware-qualified first-tier -support. Existing Basic evidence predates the new `help`/`zero` readback flow; -rerun [hardware validation](hardware-validation.md) on both instruments. Ultra -RF level/frequency accuracy, Windows/macOS, Jenkins and publication have not -been verified by these synthetic tests. +The ZS406 normal and Ultra command paths were physically validated on 2026-10-07 +with firmware `tinySA4_v1.4-197-gaa78ccc`; see +[hardware validation](hardware-validation.md#recorded-zs406-evidence). This is +not RF accuracy qualification. Generic Ultra-family variants still need their +own hardware runs, and Ultra RF level/frequency accuracy, Windows/macOS, Jenkins +and publication have not been verified for this change. diff --git a/docs/usb-protocol.md b/docs/usb-protocol.md index 5b0ad2c..d556f07 100644 --- a/docs/usb-protocol.md +++ b/docs/usb-protocol.md @@ -257,7 +257,9 @@ or a later command fails. A failed recovery is included with the original error. There is no cancellation protocol or full state restoration, and process exit can prevent recovery. The offset requires readback; other settings are checked for recognizable command errors. Optional diagnostic queries require `help` -advertisement. See [model-specific planning](ultra-support.md). +advertisement. ZS406 Ultra acquisition additionally requires explicit opt-in, +an advertised `ultra` command and exact requested `sweep` boundary readback. +See [model-specific planning](ultra-support.md). The `scan` outmask value `101` remains outside the documented three-bit mask and its returned data is discarded. The legacy preparation is enabled by default diff --git a/examples/validate-hardware.rs b/examples/validate-hardware.rs index 4b5c494..dbc44de 100644 --- a/examples/validate-hardware.rs +++ b/examples/validate-hardware.rs @@ -23,6 +23,7 @@ use tiny_wb::{ enum Model { Basic, Ultra, + Zs406, } impl Model { @@ -30,6 +31,7 @@ impl Model { match value.to_ascii_lowercase().as_str() { "basic" => Some(Self::Basic), "ultra" => Some(Self::Ultra), + "zs406" => Some(Self::Zs406), _ => None, } } @@ -38,17 +40,18 @@ impl Model { match self { Self::Basic => "Basic", Self::Ultra => "Ultra", + Self::Zs406 => "ZS406", } } fn raw_level_offset_db(self) -> u16 { match self { Self::Basic => BASIC_RAW_LEVEL_OFFSET_DB, - Self::Ultra => ULTRA_RAW_LEVEL_OFFSET_DB, + Self::Ultra | Self::Zs406 => ULTRA_RAW_LEVEL_OFFSET_DB, } } - fn scans(self) -> [(&'static str, ScanRequest, bool); 2] { + fn scans(self) -> [(&'static str, ScanRequest, bool, bool); 2] { let low = ScanRequest { start_hz: 240_000_000, stop_hz: 300_000_000, @@ -61,11 +64,35 @@ impl Model { stop_hz: 400_000_000, ..low }, - // Ultra support is experimental. Stay on the shared low-input - // command path until model-aware extended ranges are implemented. + // Generic Ultra validation stays on the shared low-input path. Self::Ultra => low, + Self::Zs406 => ScanRequest { + start_hz: 900_000_000, + stop_hz: 5_400_000_000, + points: 101, + repeat: 1, + }, }; - [("legacy", low, true), ("direct", second, false)] + match self { + Self::Zs406 => [ + ( + "normal", + ScanRequest { + start_hz: 100_000, + stop_hz: 900_000_000, + points: 101, + repeat: 1, + }, + false, + false, + ), + ("ultra", second, false, true), + ], + Self::Basic | Self::Ultra => [ + ("legacy", low, true, false), + ("direct", second, false, false), + ], + } } } @@ -76,7 +103,7 @@ struct Arguments { } fn usage() -> &'static str { - "usage: validate-hardware [--port DEVICE] [--output DIRECTORY]" + "usage: validate-hardware [--port DEVICE] [--output DIRECTORY]" } fn parse_arguments(arguments: impl IntoIterator) -> Result { @@ -209,7 +236,7 @@ fn run() -> Result<(), Box> { port ); let mut identity = String::new(); - for (name, request, legacy_pre_scan) in arguments.model.scans() { + for (name, request, legacy_pre_scan, enable_ultra_mode) in arguments.model.scans() { println!( "Running {name} scan: {}–{} MHz, {} points...", request.start_hz / 1_000_000, @@ -224,8 +251,9 @@ fn run() -> Result<(), Box> { config.repeat = request.repeat; config.scan.device_model = match arguments.model { Model::Basic => ModelSelection::Basic, - Model::Ultra => ModelSelection::Ultra, + Model::Ultra | Model::Zs406 => ModelSelection::Ultra, }; + config.scan.enable_ultra_mode = enable_ultra_mode; config.scan.auto_zero_offset = true; config.scan.zero_offset = arguments.model.raw_level_offset_db(); config.scan.frequency_axis = FrequencyAxis::Firmware; @@ -257,12 +285,13 @@ fn run() -> Result<(), Box> { path.display() ); report.push_str(&format!( - "scan={name},start_hz={},stop_hz={},points={},raw_level_offset_db={},legacy_pre_scan={},csv={}\n", + "scan={name},start_hz={},stop_hz={},points={},raw_level_offset_db={},legacy_pre_scan={},enable_ultra_mode={},csv={}\n", request.start_hz, request.stop_hz, request.points, config.scan.zero_offset, legacy_pre_scan, + enable_ultra_mode, path.display() )); } @@ -294,6 +323,8 @@ fn run() -> Result<(), Box> { ); if arguments.model == Model::Ultra { println!("Ultra result covers only the shared 240–300 MHz low-input path; extended ranges remain unsupported."); + } else if arguments.model == Model::Zs406 { + println!("ZS406 result covers normal reception through 900 MHz and opt-in non-harmonic Ultra reception through 5.4 GHz; it does not establish RF accuracy."); } Ok(()) } @@ -324,12 +355,18 @@ mod tests { "mode high input" ); let ultra = Model::Ultra.scans(); - assert!(ultra.iter().all(|(_, request, _)| { + assert!(ultra.iter().all(|(_, request, _, enable_ultra_mode)| { request.stop_hz < 350_000_000 + && !enable_ultra_mode && DeviceModel::Ultra .plan(request) .is_ok_and(|plan| plan.input_command == "mode low input") })); + let zs406 = Model::Zs406.scans(); + assert_eq!(zs406[0].1.stop_hz, 900_000_000); + assert!(!zs406[0].3); + assert_eq!(zs406[1].1.stop_hz, 5_400_000_000); + assert!(zs406[1].3); assert!(ultra[0].2); assert!(!ultra[1].2); } diff --git a/scripts/test-hardware.sh b/scripts/test-hardware.sh index 36a76bd..5b57723 100755 --- a/scripts/test-hardware.sh +++ b/scripts/test-hardware.sh @@ -2,9 +2,9 @@ set -eu case "${1:-}" in - basic|ultra) ;; + basic|ultra|zs406) ;; *) - echo "usage: $0 [--port DEVICE] [--output DIRECTORY]" >&2 + echo "usage: $0 [--port DEVICE] [--output DIRECTORY]" >&2 exit 2 ;; esac diff --git a/src/acquisition.rs b/src/acquisition.rs index 86e2802..8d16308 100644 --- a/src/acquisition.rs +++ b/src/acquisition.rs @@ -73,6 +73,16 @@ pub enum AcquisitionError { /// Offset reported by the device, in dB. actual: u16, }, + /// Extended-mode sweep readback did not confirm the requested boundaries. + #[error("ZS406 did not confirm the requested Ultra sweep {requested_start}–{requested_stop} Hz; readback was {response:?}")] + SweepReadbackMismatch { + /// Requested lower boundary, in Hz. + requested_start: u64, + /// Requested upper boundary, in Hz. + requested_stop: u64, + /// Bounded prompt-stripped firmware response. + response: String, + }, /// Both acquisition and the subsequent resume attempt failed. #[error("{primary}; additionally, resume failed: {recovery}")] Recovery { @@ -89,7 +99,8 @@ pub enum AcquisitionError { /// Settings should come from a validated [`crate::config::Config`]. The request /// is structurally validated before I/O and checked against the detected model /// before mutation. Basic supports its existing low/high paths through 960 MHz. -/// Ultra-family support is restricted to the common normal 0.1–800 MHz range. +/// Ultra-family support defaults to the common normal 0.1–800 MHz range. A +/// detected ZS406 supports 900 MHz normally and opt-in Ultra mode to 5.4 GHz. pub fn acquire( shell: &mut Shell, request: &ScanRequest, @@ -120,12 +131,13 @@ pub fn acquire( actual: identity.model, }); } - let plan = identity.model.plan(request)?; + let plan = identity.plan(request, scan.enable_ultra_mode)?; let help = shell.command("help", delay, settle)?; for command in [ "repeat", "zero", "pause", "mode", "sweep", "scanraw", "resume", ] .into_iter() + .chain(plan.enable_ultra_mode.then_some("ultra")) .chain(scan.legacy_pre_scan.then_some("scan")) { if !advertises_command(&help, command) { @@ -135,9 +147,13 @@ pub fn acquire( }); } } + let revision = identity + .ultra_revision + .map(|revision| format!(" {revision}")) + .unwrap_or_default(); report(ScanEvent::InstrumentInfo(format!( - "Detected {} (native raw offset {} dB)\n{}{}", - identity.model, plan.native_zero_offset_db, identity.version, identity.info + "Detected {}{} (native raw offset {} dB)\n{}{}", + identity.model, revision, plan.native_zero_offset_db, identity.version, identity.info ))); for command in ["leveloffset", "vbat", "usart_cfg", "threads", "marker"] { if advertises_command(&help, command) { @@ -174,9 +190,21 @@ pub fn acquire( let result = (|| { shell.command_checked("pause", delay, settle)?; shell.command_checked(plan.input_command, delay, settle)?; + if plan.enable_ultra_mode { + shell.command_checked("ultra on", delay, settle)?; + } shell.command_checked(&format!("sweep start {}", request.start_hz), delay, settle)?; shell.command_checked(&format!("sweep stop {}", request.stop_hz), delay, settle)?; - shell.command_checked("sweep", delay, settle)?; + let sweep_response = shell.command_checked("sweep", delay, settle)?; + if plan.enable_ultra_mode + && parse_sweep_bounds(&sweep_response) != Some((request.start_hz, request.stop_hz)) + { + return Err(AcquisitionError::SweepReadbackMismatch { + requested_start: request.start_hz, + requested_stop: request.stop_hz, + response: sweep_response, + }); + } if scan.legacy_pre_scan { shell.command_checked( &format!("scan {} {} 290 101", request.start_hz, request.stop_hz), @@ -229,6 +257,16 @@ fn parse_zero_offset(response: &str) -> Option { }) } +fn parse_sweep_bounds(response: &str) -> Option<(u64, u64)> { + response.lines().find_map(|line| { + let values: Vec<_> = line + .split_whitespace() + .filter_map(|word| word.parse::().ok()) + .collect(); + (values.len() >= 2).then(|| (values[0], values[1])) + }) +} + #[cfg(test)] mod tests { use super::*; @@ -349,6 +387,11 @@ mod tests { Some(174) ); assert_eq!(parse_zero_offset("174 dBm"), None); + assert_eq!( + parse_sweep_bounds("sweep\r\n900000000 5400000000 450\r\n"), + Some((900_000_000, 5_400_000_000)) + ); + assert_eq!(parse_sweep_bounds("ok"), None); } #[test] @@ -405,4 +448,55 @@ mod tests { assert!(!written.contains("scanraw ")); } } + + #[test] + fn zs406_extended_scan_is_opt_in_and_verifies_sweep_readback() { + let request = ScanRequest { + start_hz: 900_000_000, + stop_hz: 5_400_000_000, + points: 2, + repeat: 1, + }; + let run = |enable_ultra_mode: bool, sweep: &str| { + let mut config = Config::default(); + config.scan.enable_ultra_mode = enable_ultra_mode; + config.scan.legacy_pre_scan = false; + config.serial.command_delay_ms = 0; + config.serial.settle_delay_ms = 0; + let input = format!( + "ch>tinySA4_v1.4-test\r\nHW Version:V0.4.6\r\nch>tinySA Ultra+ ZS406\r\nch>Commands: repeat zero pause mode ultra sweep scanraw resume\r\nch>ch>ch>174dBm\r\nch>ch>ch>ch>ch>ch>{sweep}\r\nch>{{x\0\x08x\0\x10}}ch>ch>" + ); + let commands = Arc::new(Mutex::new(Vec::new())); + let mut shell = Shell::new( + Transcript { + input: Cursor::new(input.into_bytes()), + commands: commands.clone(), + }, + 1024, + ); + let result = acquire(&mut shell, &request, &config.scan, &config.serial, |_| {}); + let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap(); + (result, written) + }; + + let (result, commands) = run(false, "900000000 5400000000 450"); + assert!(result + .unwrap_err() + .to_string() + .contains("enable_ultra_mode")); + assert!(!commands.contains("pause\r")); + + let (result, commands) = run(true, "900000000 5400000000 450"); + assert!(result.is_ok(), "{result:?}"); + assert!(commands.contains("mode low input\rultra on\r")); + assert!(commands.contains("scanraw 900000000 5400000000 2\r")); + + let (result, commands) = run(true, "900000000 900000000 450"); + assert!(matches!( + result, + Err(AcquisitionError::SweepReadbackMismatch { .. }) + )); + assert!(!commands.contains("scanraw ")); + assert!(commands.ends_with("resume\r")); + } } diff --git a/src/config.rs b/src/config.rs index 14f9e9f..6fce58c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -38,7 +38,7 @@ pub struct Config { pub port: String, /// Selected baud rate, which must occur in `serial.baudrates`. pub baudrate: u32, - /// Scan start in MHz, within the Basic 0–960 MHz envelope. + /// Scan start in MHz, within the application's 0–5,400 MHz envelope. pub start_frequency: usize, /// Scan stop in MHz, no lower than the start. pub stop_frequency: usize, @@ -130,6 +130,8 @@ pub enum ModelSelection { pub struct ScanConfig { /// Expected device family; `auto` still rejects unknown or conflicting identity. pub device_model: ModelSelection, + /// Explicitly permit ZS406 Ultra mode for analyzer scans above 900 MHz. + pub enable_ultra_mode: bool, /// Select the detected model's native raw-level offset. pub auto_zero_offset: bool, /// Offset sent with `zero` and subtracted from raw levels, in dB. @@ -249,9 +251,9 @@ impl Config { )?; require( self.start_frequency <= self.stop_frequency - && self.stop_frequency <= 960 + && self.stop_frequency <= 5_400 && self.stop_frequency >= 10, - "frequencies must be ordered in 0–960 MHz, with stop at least 10 MHz", + "frequencies must be ordered in 0–5400 MHz, with stop at least 10 MHz", )?; require( self.scan.min_points >= 2 @@ -269,7 +271,7 @@ impl Config { "repeat must be within 1..=scan.max_repeat, which cannot exceed 1000", )?; require( - (1..=960).contains(&self.scan.frequency_step_mhz) + (1..=5_400).contains(&self.scan.frequency_step_mhz) && (1..=self.scan.max_points).contains(&self.scan.points_step), "scan keyboard steps must be positive and within their bounds", )?; @@ -359,6 +361,7 @@ mod tests { let config = Config::from_toml("port = 'COM3'\nbaudrate = 57600\nstart_frequency = 20\nstop_frequency = 100\npoints = 101\nrepeat = 2").unwrap(); assert_eq!(config.port, "COM3"); assert_eq!(config.points, 101); + assert!(!config.scan.enable_ultra_mode); assert_eq!(config.serial, Config::default().serial); assert_eq!( Config::from_toml("[scan]\nfrequency_axis = 'inclusive'") @@ -367,6 +370,12 @@ mod tests { .frequency_axis, FrequencyAxis::Inclusive ); + let zs406 = Config::from_toml( + "start_frequency = 900\nstop_frequency = 5400\n[scan]\nenable_ultra_mode = true", + ) + .unwrap(); + assert!(zs406.scan.enable_ultra_mode); + assert_eq!(zs406.stop_frequency, 5_400); } #[test] @@ -389,7 +398,7 @@ mod tests { "broken", "pointz = 100", "points = 1", - "start_frequency = 961", + "start_frequency = 5401", "start_frequency = 900\nstop_frequency = 100", "repeat = 0", "[serial]\nbaudrates = []", diff --git a/src/device.rs b/src/device.rs index 9e4f4fc..224c55f 100644 --- a/src/device.rs +++ b/src/device.rs @@ -1,8 +1,8 @@ //! Device identity parsing and model-specific acquisition policy. //! //! Identification consumes explicit `version`/`info` evidence. This module -//! selects only acquisition behavior shared by the detected family; it does not -//! infer an Ultra hardware revision or unlock extended/harmonic modes. +//! selects acquisition behavior only from explicit family and hardware-revision +//! evidence. ZS406 Ultra mode is opt-in; harmonic mode remains unsupported. use crate::protocol::{ ProtocolError, ScanRequest, BASIC_MAX_HZ, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB, @@ -13,6 +13,10 @@ use std::fmt; pub const ULTRA_MIN_HZ: u64 = 100_000; /// Common normal-mode ceiling across supported Ultra family revisions, in Hz. pub const ULTRA_NORMAL_MAX_HZ: u64 = 800_000_000; +/// ZS406 normal-mode ceiling, in Hz. +pub const ZS406_NORMAL_MAX_HZ: u64 = 900_000_000; +/// Highest ZS406 frequency supported without harmonic mixing, in Hz. +pub const ZS406_ULTRA_MAX_HZ: u64 = 5_400_000_000; /// Device family established from console identity replies. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -23,6 +27,27 @@ pub enum DeviceModel { Ultra, } +/// Hardware revision established from the firmware's `version`/`info` text. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UltraRevision { + /// Original tinySA Ultra hardware. + Zs405, + /// First tinySA Ultra+ hardware, version V0.4.6. + Zs406, + /// Later tinySA Ultra+ hardware; retained on the conservative family range. + Zs407, +} + +impl fmt::Display for UltraRevision { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Zs405 => "ZS405", + Self::Zs406 => "ZS406", + Self::Zs407 => "ZS407", + }) + } +} + impl fmt::Display for DeviceModel { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(match self { @@ -37,6 +62,8 @@ impl fmt::Display for DeviceModel { pub struct DeviceIdentity { /// Detected device family. pub model: DeviceModel, + /// Ultra-family hardware revision, when the replies contain explicit evidence. + pub ultra_revision: Option, /// Verbatim prompt-stripped `version` response. pub version: String, /// Verbatim prompt-stripped `info` response. @@ -52,6 +79,8 @@ pub struct AcquisitionPlan { pub input_command: &'static str, /// Native raw-level encoding offset, in dB. pub native_zero_offset_db: u16, + /// Whether the acquisition must explicitly enable firmware Ultra mode. + pub enable_ultra_mode: bool, } /// Device identification failures occur before acquisition settings are changed. @@ -63,6 +92,9 @@ pub enum DeviceError { /// Basic and Ultra signatures occurred in the same identity exchange. #[error("conflicting device identity: replies identify both tinySA Basic and Ultra")] Conflicting, + /// More than one Ultra revision signature occurred in the identity exchange. + #[error("conflicting device identity: replies identify multiple tinySA Ultra revisions")] + ConflictingRevision, } impl DeviceIdentity { @@ -89,12 +121,85 @@ impl DeviceIdentity { (true, true) => return Err(DeviceError::Conflicting), (false, false) => return Err(DeviceError::Unknown), }; + let identity_lower = format!("{version_lower}\n{info_lower}"); + let revision_matches = [ + ( + UltraRevision::Zs405, + identity_lower.contains("zs405") || identity_lower.contains("hw version:v0.4.5.1"), + ), + ( + UltraRevision::Zs406, + identity_lower.contains("zs406") || identity_lower.contains("hw version:v0.4.6"), + ), + ( + UltraRevision::Zs407, + identity_lower.contains("zs407") + || identity_lower.contains("hw version:v0.5.3") + || identity_lower.contains("hw version:v0.5.4"), + ), + ]; + let mut revisions = revision_matches + .into_iter() + .filter_map(|(revision, matches)| matches.then_some(revision)); + let ultra_revision = revisions.next(); + if revisions.next().is_some() { + return Err(DeviceError::ConflictingRevision); + } + let ultra_revision = (model == DeviceModel::Ultra) + .then_some(ultra_revision) + .flatten(); Ok(Self { model, + ultra_revision, version, info, }) } + + /// Validate a request using detected revision evidence and explicit Ultra opt-in. + pub fn plan( + &self, + request: &ScanRequest, + allow_ultra_mode: bool, + ) -> Result { + if self.model == DeviceModel::Basic { + return self.model.plan(request); + } + request.validate()?; + if request.start_hz < ULTRA_MIN_HZ { + return Err(ProtocolError::InvalidRequest( + "tinySA Ultra frequencies must start at or above 0.1 MHz".into(), + )); + } + let normal_max_hz = match self.ultra_revision { + Some(UltraRevision::Zs406) => ZS406_NORMAL_MAX_HZ, + Some(UltraRevision::Zs405 | UltraRevision::Zs407) | None => ULTRA_NORMAL_MAX_HZ, + }; + let enable_ultra_mode = request.stop_hz > normal_max_hz; + if enable_ultra_mode { + if self.ultra_revision != Some(UltraRevision::Zs406) { + return Err(ProtocolError::InvalidRequest( + "extended acquisition currently requires an explicitly detected ZS406".into(), + )); + } + if !allow_ultra_mode { + return Err(ProtocolError::InvalidRequest( + "ZS406 scans above 900 MHz require scan.enable_ultra_mode = true".into(), + )); + } + if request.stop_hz > ZS406_ULTRA_MAX_HZ { + return Err(ProtocolError::InvalidRequest( + "ZS406 support stops at 5.4 GHz; harmonic mode is not supported".into(), + )); + } + } + Ok(AcquisitionPlan { + model: self.model, + input_command: "mode low input", + native_zero_offset_db: ULTRA_RAW_LEVEL_OFFSET_DB, + enable_ultra_mode, + }) + } } impl DeviceModel { @@ -133,6 +238,7 @@ impl DeviceModel { model: self, input_command, native_zero_offset_db, + enable_ultra_mode: false, }) } } @@ -159,11 +265,23 @@ mod tests { DeviceModel::Basic ); assert_eq!( - DeviceIdentity::detect("tinySA4_v1.4-200-gabc".into(), "tinySA Ultra+".into()) - .unwrap() - .model, + DeviceIdentity::detect( + "tinySA4_v1.4-200-gabc\r\nHW Version:V0.4.6".into(), + "tinySA Ultra+ ZS406".into() + ) + .unwrap() + .model, DeviceModel::Ultra ); + assert_eq!( + DeviceIdentity::detect( + "tinySA4_v1.4-200-gabc\r\nHW Version:V0.4.6".into(), + "tinySA Ultra+ ZS406".into() + ) + .unwrap() + .ultra_revision, + Some(UltraRevision::Zs406) + ); assert_eq!( DeviceIdentity::detect("version unknown".into(), "instrument".into()), Err(DeviceError::Unknown) @@ -195,4 +313,39 @@ mod tests { .plan(&request(100_000, 800_000_001)) .is_err()); } + + #[test] + fn zs406_plan_separates_normal_ultra_and_harmonic_ranges() { + let identity = DeviceIdentity::detect( + "tinySA4_v1.4-test\r\nHW Version:V0.4.6".into(), + "tinySA Ultra+ ZS406".into(), + ) + .unwrap(); + let normal = identity + .plan(&request(ULTRA_MIN_HZ, ZS406_NORMAL_MAX_HZ), false) + .unwrap(); + assert!(!normal.enable_ultra_mode); + assert!(identity + .plan(&request(900_000_000, ZS406_ULTRA_MAX_HZ), false) + .is_err()); + let ultra = identity + .plan(&request(900_000_000, ZS406_ULTRA_MAX_HZ), true) + .unwrap(); + assert!(ultra.enable_ultra_mode); + assert!(identity + .plan(&request(900_000_000, ZS406_ULTRA_MAX_HZ + 1), true) + .is_err()); + + let zs407 = DeviceIdentity::detect( + "tinySA4_v1.4-test\r\nHW Version:V0.5.4".into(), + "tinySA Ultra+ ZS407".into(), + ) + .unwrap(); + assert!(zs407 + .plan(&request(ULTRA_MIN_HZ, ULTRA_NORMAL_MAX_HZ), false) + .is_ok()); + assert!(zs407 + .plan(&request(ULTRA_MIN_HZ, ULTRA_NORMAL_MAX_HZ + 1), true) + .is_err()); + } } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 729d708..d0103dd 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -37,13 +37,13 @@ impl App { config.start_frequency, config.scan.frequency_step_mhz, 0, - 960, + 5_400, ), stop_frequency: NumericInput::new( config.stop_frequency, config.scan.frequency_step_mhz, 10, - 960, + 5_400, ), points: NumericInput::new( config.points, @@ -327,7 +327,7 @@ mod tests { assert!(matches!(app.next_step(), Err(UiError::NoPortSelected))); let mut app = self::app(); app.next_step().unwrap(); - app.start_frequency = NumericInput::new(900, 10, 0, 960); + app.start_frequency = NumericInput::new(900, 10, 0, 5_400); assert!(app.next_step().is_err()); assert_eq!(app.scan_state.status(), ScanStatus::Ready); }