feat: detect tinySA Ultra and apply model-aware scan decoding
Rust CI tiny-wb passed CI.
Gitea/tiny-wb/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-10-05 09:45:56 +02:00
parent 95e61dc5c3
commit 7558a24374
26 changed files with 841 additions and 205 deletions

View File

@ -8,11 +8,11 @@
sweep from a tinySA over its USB serial console and exports the result as CSV.
It is written in Rust and uses Ratatui for the interface.
The current implementation is primarily shaped around the original **tinySA
Basic** command set and its 0–960 MHz low/high input ranges. The tinySA Ultra
family uses much of the same console protocol, but model detection and the
Ultra frequency ranges are not implemented yet; see the compatibility notes
before connecting an Ultra or Ultra+.
The application detects tinySA Basic and Ultra families automatically. Basic
retains its low/high paths through 960 MHz; initial Ultra software support covers
the common 0.1–800 MHz normal range with automatic raw-offset selection and
readback. See [support scope and migration](docs/ultra-support.md) for hardware
qualification status and extended-range limitations.
## Documentation
@ -113,6 +113,18 @@ At a high level, `tiny-wb`:
5. decodes each level sample into dBm and writes `frequency_MHz,level_dBm`;
6. resumes the instrument sweep and plots the acquired points.
By default, point frequencies reproduce the reviewed firmware's `scanraw`
integer/single-precision calculation. The requested stop frequency is an upper
boundary and is normally not sampled. Existing configurations that explicitly
select `scan.frequency_axis = "inclusive"` retain the older endpoint-inclusive
labels; see [frequency assignment](docs/usb-protocol.md#frequency-assignment).
Raw `scanraw` levels also have a model-specific encoding bias: 128 dB for
tinySA Basic and 174 dB for tinySA Ultra. This is not record padding; both use
the same `x` plus little-endian `u16` record. Automatic detection selects and
confirms the native offset before acquisition. See
[level conversion and `zero`](docs/usb-protocol.md#level-conversion-and-zero).
For the exact command sequence and compatibility implications, read
[USB console and `scanraw` protocol](docs/usb-protocol.md) and
[tiny-wb compatibility and operations](docs/tiny-wb-operations.md).

View File

@ -3,7 +3,7 @@
port = ""
baudrate = 115200
start_frequency = 240
stop_frequency = 960
stop_frequency = 800
points = 10001
repeat = 1
@ -24,15 +24,22 @@ baudrates = [19200, 38400, 57600, 115200, 230400, 460800, 921600, 1843200, 20000
preferred_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]
[scan]
# Sent with `zero`; the decoder uses this same offset.
# 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"
# 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
# is sent with `zero`; the decoder must use that same value.
zero_offset = 128
frequency_step_mhz = 10
points_step = 100
min_points = 101
max_points = 1000001
max_repeat = 1000
# Retain historical endpoint labels. `firmware` uses span / points instead.
frequency_axis = "inclusive"
# Match scanraw's integer-truncated span / points mapping. Use `inclusive` only
# to reproduce CSV files created by older tiny-wb releases.
frequency_axis = "firmware"
# Retain the historical preparatory text scan until hardware confirms removal.
legacy_pre_scan = true

View File

@ -1,4 +1,4 @@
# Synthetic Ultra identity/syntax. This does NOT enable Ultra support in the UI.
# Synthetic Ultra identity/syntax; production supports the common 0.1–800 MHz range.
model = "ultra"
echo = true
read_chunk_bytes = 7

View File

@ -12,7 +12,8 @@ widgets, port discovery, worker threads, or the application's working directory.
| `src/config.rs` | Typed settings, recursive partial overrides, legacy-key compatibility and validation. |
| `config/default.toml` | Authoritative embedded defaults, with units and comments. |
| `src/storage.rs` | Same-directory atomic replacement for saved configuration. |
| `src/protocol.rs` | Basic input-path rules, scan request validation and pure raw-frame decoding. |
| `src/protocol.rs` | Structural scan validation, wire invariants and pure raw-frame decoding. |
| `src/device.rs` | Family identification, model-specific ranges, input paths and native offsets. |
| `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. |
@ -49,8 +50,13 @@ embedded defaults + runtime overrides -> validated Config
`ScanRequest` carries Hz, sample count and repeat count. `Sample` carries MHz
and dBm. Units are converted at the UI/core boundary, not inside widgets or
file naming. The selected zero offset is both sent to the instrument and used
by the decoder. Frequency labeling is an explicit policy; inclusive labels
remain the default for compatibility.
by the decoder. Frequency labeling is an explicit policy; the default mirrors
the reviewed firmware's integer/single-precision `scanraw` calculation, while
legacy endpoint-inclusive labels remain available for compatibility.
Protocol constants record the native raw-level biases (Basic 128, Ultra 174).
`device.rs` detects the family and validates its acquisition plan. Both the
application and validator select the native bias automatically and confirm
the readback. See [support scope](ultra-support.md).
The core reports `ScanEvent` values. `ScanState` adapts them to one
`Arc<Mutex<Progress>>`; completion publishes samples, filename, status and 100%
@ -78,10 +84,10 @@ Process termination or release-mode panic abort cannot be recovered by a guard.
## Acquisition and protocol boundary
1. Validate the Basic range and sample/repeat limits before opening/using a port.
1. Validate structural request and sample/repeat limits before using a port.
2. Synchronize with stale input, allowing an idle timeout only during this step.
3. Query `version`, `info` and the existing diagnostic commands.
4. Set `repeat` and the configured raw zero offset, then query markers.
3. Query `version`/`info`, validate the detected model's range, check `help`, and run advertised diagnostics.
4. Set `repeat` and the selected raw zero offset, then verify its readback.
5. Attempt `pause`, select input mode, and configure the display sweep.
6. Optionally retain the historical `scan START STOP 290 101` preparation.
7. Request `scanraw`, consume exactly the expected framed record count, then

View File

@ -44,6 +44,12 @@ use one input path. Values must be ordered. The selected baud rate must be in
| `output` | CSV directory, filename prefix, and optional column header. |
| `logging` | Logger filter expression and destination directory. |
`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
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
while retaining the default scan selection:
@ -63,10 +69,14 @@ file, flush, and rename. The old configuration survives validation or write
failure. TOML formatting and comments are not preserved; retain comments in a
separate template if needed. The configuration file's parent must exist.
`scan.frequency_axis = "inclusive"` preserves the historical CSV frequency
labels (`span / (points - 1)`). `"firmware"` uses `span / points`, matching the
reviewed upstream implementation. Neither changes the request or proves which
firmware is connected. See [frequency assignment](usb-protocol.md#frequency-assignment).
`scan.frequency_axis = "firmware"` is the default. It reproduces the reviewed
`scanraw` integer division, single-precision multiplication and conversion back
to integer Hz. `"inclusive"` preserves the legacy tiny-wb labels
(`span / (points - 1)`) and includes the requested stop frequency. Neither
setting changes the request or proves RF frequency accuracy. Existing saved
files that explicitly contain `frequency_axis = "inclusive"` keep their old
labels; partial configurations that omit the key adopt the corrected default.
See [frequency assignment](usb-protocol.md#frequency-assignment).
The preparatory `scan START STOP 290 101` remains enabled by default with
`scan.legacy_pre_scan = true` for compatibility. Its undocumented output mask

View File

@ -44,6 +44,7 @@ front-panel sweep resumed.
checking it.
- [ ] The final `basic-report.txt` records both CSV paths and
`operator_confirmed=y` (or `yes`).
- [ ] Each report entry records `raw_level_offset_db=128`.
## Ultra acceptance and limit
@ -56,9 +57,11 @@ front-panel sweep resumed.
checking it.
- [ ] The final `ultra-report.txt` records both CSV paths and
`operator_confirmed=y` (or `yes`).
- [ ] Each report entry records `raw_level_offset_db=174`.
A passing Ultra run validates only the shared low-input command path below
350 MHz, including `zero 128`, binary framing, CSV export, and best-effort
350 MHz, including the native `zero 174` encoding, binary framing, CSV export,
and best-effort
resume. It does not validate Ultra mode, harmonic mode, LNA behavior, ranges at
or above 350 MHz, level accuracy, or frequency accuracy. Those require
model-aware acquisition and a controlled reference source; do not infer them

View File

@ -78,13 +78,14 @@ cargo test --locked --no-default-features --features mock --lib --test mock_devi
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.
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.
See [support scope](ultra-support.md).
Samples use `start + index * (stop - start) / points`, a triangular peak above
a configured floor, and `round((dBm + zero_offset) * 32)` clamped to `u16`.
Samples use the reviewed firmware's integer-divided, single-precision
`scanraw` point frequencies, 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.

View File

@ -31,6 +31,11 @@ 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.
- [ ] P01 **Inventory and capability negotiation** (depends F01–F04). Capture
`version`, `info`, `help` and matching firmware commit/build options for Basic
and each supported Ultra revision. Create a versioned command/capability

View File

@ -1,7 +1,8 @@
# Upstream source catalogue
This catalogue records the authoritative references used to build the local
guide. It was last checked on **2026-10-04**. Prefer these primary sources over
guide. The catalogue was checked on **2026-10-04**; the protocol and Ultra-support
pages record their targeted **2026-10-05** source review. Prefer these primary sources over
retailer listings, reposted manuals, videos, and forum recollections.
## Official overview and model data
@ -80,5 +81,6 @@ When sources disagree:
The local docs intentionally record two known conflicts: the wiki's textual
“MSB LSB” description versus firmware's little-endian byte writes, and
endpoint-inclusive intuition versus the reviewed firmware's `span / points`
`scanraw` step. Both are explained in [the protocol guide](usb-protocol.md).
endpoint-inclusive intuition versus the reviewed firmware's integer-divided,
single-precision `scanraw` step. Both are explained in
[the protocol guide](usb-protocol.md).

View File

@ -13,7 +13,7 @@ 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. |
| Protocol | Basic mode boundaries, point/repeat validation, truncated/extra records, alignment, closing brace, binary delimiter bytes, little-endian levels, Basic/Ultra raw offsets, both frequency-axis conventions, and firmware integer/single-precision frequency rounding. |
| Transport | One-byte/fragmented reads, multiple responses in one read, retained bytes after prompts, partial writes, invalid command lines, EOF, timeout, response size limits and raw-body framing. |
| Acquisition | Exact command ordering, optional legacy pre-scan, progress completion, successful decoding, resume after malformed frames, and preservation of acquisition plus recovery errors. |
| UI/startup | Missing/stale ports, numeric overflow and clamping, configured baud rates, navigation, one-time result transfer, every screen on small/headless terminals, and invalid config before terminal startup. |

View File

@ -13,9 +13,8 @@ can represent it in the UI.
| tinySA Basic high input, range wholly from 350 to 960 MHz | Implemented | The client sends `mode high input`; the RF path itself is less accurate and more overload-prone than low input. |
| 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+ below 350 MHz | Experimental, not declared supported | `mode low input` and `zero 128` are plausible, but the client neither detects nor tests the model. |
| tinySA Ultra/Ultra+ at or above 350 MHz | Not supported | The client sends Basic-only `mode high input`; Ultra has no such high input mode. |
| Ultra mode above the normal range | Not supported | UI stops at 960 MHz and never negotiates Ultra state/capabilities. |
| 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. |
| 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:
@ -88,7 +87,7 @@ configurable; Basic frequency limits remain fixed protocol rules.
| Field | Unit | Default | Step | Bounds |
| --- | --- | ---: | ---: | ---: |
| Start frequency | MHz | 240 | 10 | 0–960 |
| Stop frequency | MHz | 960 | 10 | 10–960 |
| Stop frequency | MHz | 800 | 10 | 10–960 (Ultra acquisition capped at 800) |
| Points | samples | 10,001 | 100 | 101–1,000,001 |
| Repeat | measurements/point | 1 | 1 | 1–1,000 |
@ -201,18 +200,23 @@ are handled by the buffered transport.
### Trace is shifted in frequency
The default `inclusive` labeling uses `points - 1` intervals, while the reviewed
firmware uses a `span / points` step. Verify with a known carrier and record the
firmware version before choosing `scan.frequency_axis = "firmware"`. This setting
changes CSV/chart labels; it does not change the instrument request.
The default `firmware` labeling reproduces the reviewed `scanraw` integer and
single-precision arithmetic. If a saved configuration selects `inclusive`, it
uses `points - 1` intervals and can shift later labels by nearly one firmware
step. Remove that override or choose `scan.frequency_axis = "firmware"`, then
verify with a known narrow carrier and record the firmware version. The setting
changes CSV/chart labels; it does not change the instrument request or calibrate
the analyzer.
### Levels are wrong by about 46 dB
That is the difference between Ultra's documented default raw offset (174) and
Basic's (128). tiny-wb sends `zero 128`; a 46 dB shift suggests the firmware
did not accept/apply that command or the reply was not validated. Stop treating
the result as calibrated data and capture `version`, `info`, and the `zero`
command response.
Basic's (128). The application and hardware validator now select the detected
family's native offset automatically and verify its readback. A 46 dB shift
suggests that the configured command/decoder offset does not match the firmware
value. Stop treating the result as calibrated data and capture `version`,
`info`, and the `zero` command response. This bias is numeric encoding, not
model-specific record padding.
### Unexpected harmonics or spurs
@ -239,7 +243,7 @@ software bug; substitute a low-level known source or recorded serial fixture.
## Remaining engineering work
Model/capability detection, Ultra-specific command/range support, overall
Revision-specific detection, Ultra ranges above 800 MHz, 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
@ -250,4 +254,4 @@ needed; see [architecture](architecture.md#extension-points-and-remaining-limits
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.
app supports the common Ultra normal range; see [support scope](ultra-support.md).

View File

@ -303,11 +303,10 @@ version installed on the instrument.
## How this maps to tiny-wb
tiny-wb currently chooses `mode low input` below 350 MHz and `mode high input`
above that, limits the UI to 960 MHz, and does not inspect the model. That is a
Basic-oriented policy. Ultra supports `mode [low] input`, has no Basic-style
high input, and needs capability-driven ranges. Until model support is added,
use [the compatibility matrix and cautions](tiny-wb-operations.md#compatibility-matrix).
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
[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
[USB console and `scanraw` protocol](usb-protocol.md).

62
docs/ultra-support.md Normal file
View File

@ -0,0 +1,62 @@
# Basic and Ultra acquisition support
Implemented 2026-10-05; synthetic verification is separate from hardware qualification.
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.
| 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 |
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.
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)
accepts `mode low input` for Ultra. Sources checked 2026-10-05.
Required commands must appear in `help`. Optional diagnostics run only when
advertised. After setting the selected bias with `zero N`, acquisition queries
`zero` and requires a matching `NdBm` readback. A missing or mismatched readback
fails before scanning. The decoder uses this confirmed value. Both families
share the same binary record layout; see [protocol](usb-protocol.md).
## Configuration migration
New defaults select `device_model = "auto"`, `auto_zero_offset = true`, and
240–800 MHz, usable by both families. Saved frequencies remain unchanged;
an old 960 MHz stop is rejected on Ultra with an actionable range error.
To preserve a custom raw bias, set `auto_zero_offset = false` alongside the
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.
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.
## 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.
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.

View File

@ -103,6 +103,11 @@ Thus the framed body length is `1 + 3 * points + 1` bytes. Each level is a
place as “MSB LSB,” the firmware source writes `val & 0xff` first and
`val >> 8` second. The repository correctly unpacks the value as little-endian.
The `x` byte is a per-record alignment marker, not padding. Basic and Ultra use
the same braces, marker, two-byte value and exact body length; there is no
model-specific padding in the documented or reviewed `scanraw` format. Their
model-specific difference is the numeric level bias described below.
Payload bytes are arbitrary. A payload byte can equal `{`, `}`, `x`, `c`, `h`,
or `>`. Framing logic must only interpret `{` before the records, `x` at every
three-byte record boundary, and `}` after exactly the requested record count
@ -111,7 +116,8 @@ text tokens is unsafe.
## Level conversion and `zero`
The documented default conversion is:
The [official USB interface](https://tinysa.org/wiki/pmwiki.php?n=Main.USBInterface)
documents these native conversions:
```text
Basic dBm = raw_u16 / 32 - 128
@ -122,21 +128,23 @@ This is a fixed-point value with 1/32 dB numeric steps. The detector itself has
coarser effective resolution, so the encoding precision is not the same as
measurement accuracy.
Upstream firmware calculates the transmitted integer from the measured value
plus `config.ext_zero_level`; the `zero N` command changes that offset. tiny-wb
defaults to `zero 128` before every acquisition. `scan.zero_offset` supplies both
the command and decoder offset; with the default it uses:
The reviewed [firmware defaults](https://github.com/Ho-Ro/tinySA/blob/main/main.c#L1099-L1200)
set `config.ext_zero_level` to 128 for Basic and 174 for Ultra. The
[`scanraw` implementation](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c#L1221-L1267)
adds that offset to the measured value, and the
[`zero` handler](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c#L602-L609)
lets `zero N` replace it. tiny-wb detects the family and selects its native
offset automatically, then requires matching `zero` readback before scanning.
For Basic this gives:
```text
dBm = raw_u16 / 32 - 128
```
That normalizes the wire representation to a Basic-style offset and can make
the conversion work on firmware honoring `zero`, including Ultra. A robust
client should still detect the model, verify the command response, and bind the
decoder offset to the value it successfully configured. If `zero 128` is
rejected or ignored, applying 128 to an Ultra default frame produces a 46 dB
error.
Ultra uses 174. Manual normalization is still available with
`scan.auto_zero_offset = false`; readback must agree with `scan.zero_offset`.
A mismatch would shift levels by 46 dB between native defaults, so acquisition
now rejects missing or mismatched readback. See [support and migration](ultra-support.md).
### Worked record
@ -154,31 +162,41 @@ Suppose the three bytes are:
## Frequency assignment
The upstream `cmd_scanraw` implementation calculates:
The official USB command page specifies the `scanraw` request and record count,
but does not define a point-to-frequency formula. The upstream
[`cmd_scanraw` implementation](https://github.com/Ho-Ro/tinySA/blob/main/sa_cmd.c#L1221-L1263),
reviewed on 2026-10-05, is the byte-level authority used here. Its C expression
has three relevant conversions:
```text
firmware_step = (stop - start) / points
frequency[i] = start + firmware_step * i for i = 0 .. points-1
integer_step_hz = integer_divide(stop_hz - start_hz, points)
firmware_step_hz = float32(integer_step_hz)
frequency_hz[i] = start_hz + truncate_to_freq_t(firmware_step_hz * float32(i))
for i = 0 .. points - 1
```
The arithmetic includes floating/intermediate and integer-frequency details
that vary with the firmware's `freq_t`, but the denominator is visibly
`points`, not `points - 1` in the reviewed source. Therefore the last measured
point is one nominal step below stop.
The denominator is `points`, not `points - 1`. Integer division discards any
remainder before the assignment to the 32-bit `float`; multiplication can then
round at large values before conversion back to `freq_t`. For example, a
0–10 Hz, three-point request measures nominally at 0, 3, and 6 Hz. The requested
stop is an upper boundary and the final point is normally roughly one step below
it. tiny-wb's `firmware` axis reproduces these conversions, including the
single-precision rounding.
tiny-wb preserves historical output labels by default (`scan.frequency_axis = "inclusive"`):
The default is now `scan.frequency_axis = "firmware"`. The compatibility-only
`inclusive` setting retains labels produced by older tiny-wb releases:
```text
host_step = (stop - start) / (points - 1)
frequency[i] = start + host_step * i
```
This labels the endpoints inclusively and disagrees with the reviewed firmware.
The discrepancy grows linearly through a sweep to almost one firmware step at
the last point. `scan.frequency_axis = "firmware"` selects the reviewed firmware
denominator instead. Before changing the setting, capture a known narrow carrier
with the target firmware and retain the `version` string; firmware behavior may
change. Both conventions have synthetic regression tests, not hardware proof.
`inclusive` labels both requested endpoints and disagrees with the reviewed
firmware. The discrepancy grows linearly through a sweep to almost one firmware
step at the last point. Existing saved configuration remains compatible because
an explicit `inclusive` value is still accepted. Record the connected device's
`version` when validating a narrow carrier: the synthetic tests establish source
parity, not RF frequency accuracy or behavior of every firmware revision.
## Prompt and synchronization behavior
@ -209,13 +227,15 @@ are decimal Hz):
```text
version
info
help
leveloffset
vbat
usart_cfg
threads
repeat REPEAT
zero 128
marker
repeat REPEAT
zero MODEL_OFFSET
zero
pause
mode LOW_OR_HIGH input
sweep start START
@ -235,8 +255,9 @@ The pure decoder requires the exact record count, alignment and closing brace.
After attempting `pause`, acquisition attempts `resume` even if frame decoding
or a later command fails. A failed recovery is included with the original error.
There is no cancellation protocol or full state restoration, and process exit
can prevent recovery. Device command acceptance is not explicitly acknowledged
beyond a prompt.
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).
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

View File

@ -12,10 +12,10 @@ use std::{
};
use tiny_wb::{
acquisition::{acquire, ScanEvent},
config::{Config, FrequencyAxis, OutputConfig},
config::{Config, FrequencyAxis, ModelSelection, OutputConfig},
connection::open_connection,
export::save_csv,
protocol::{Sample, ScanRequest},
protocol::{Sample, ScanRequest, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB},
transport::Shell,
};
@ -41,6 +41,13 @@ impl Model {
}
}
fn raw_level_offset_db(self) -> u16 {
match self {
Self::Basic => BASIC_RAW_LEVEL_OFFSET_DB,
Self::Ultra => ULTRA_RAW_LEVEL_OFFSET_DB,
}
}
fn scans(self) -> [(&'static str, ScanRequest, bool); 2] {
let low = ScanRequest {
start_hz: 240_000_000,
@ -215,6 +222,12 @@ fn run() -> Result<(), Box<dyn Error>> {
config.stop_frequency = (request.stop_hz / 1_000_000) as usize;
config.points = request.points;
config.repeat = request.repeat;
config.scan.device_model = match arguments.model {
Model::Basic => ModelSelection::Basic,
Model::Ultra => ModelSelection::Ultra,
};
config.scan.auto_zero_offset = true;
config.scan.zero_offset = arguments.model.raw_level_offset_db();
config.scan.frequency_axis = FrequencyAxis::Firmware;
config.scan.legacy_pre_scan = legacy_pre_scan;
config.validate()?;
@ -244,10 +257,11 @@ fn run() -> Result<(), Box<dyn Error>> {
path.display()
);
report.push_str(&format!(
"scan={name},start_hz={},stop_hz={},points={},legacy_pre_scan={},csv={}\n",
"scan={name},start_hz={},stop_hz={},points={},raw_level_offset_db={},legacy_pre_scan={},csv={}\n",
request.start_hz,
request.stop_hz,
request.points,
config.scan.zero_offset,
legacy_pre_scan,
path.display()
));
@ -294,15 +308,27 @@ fn main() {
#[cfg(test)]
mod tests {
use super::*;
use tiny_wb::device::DeviceModel;
#[test]
fn plans_keep_ultra_on_the_shared_low_input_path() {
assert_eq!(Model::Basic.raw_level_offset_db(), 128);
assert_eq!(Model::Ultra.raw_level_offset_db(), 174);
let basic = Model::Basic.scans();
assert_eq!(basic[0].1.input_mode().unwrap().as_str(), "low");
assert_eq!(basic[1].1.input_mode().unwrap().as_str(), "high");
assert_eq!(
DeviceModel::Basic.plan(&basic[0].1).unwrap().input_command,
"mode low input"
);
assert_eq!(
DeviceModel::Basic.plan(&basic[1].1).unwrap().input_command,
"mode high input"
);
let ultra = Model::Ultra.scans();
assert!(ultra.iter().all(|(_, request, _)| {
request.stop_hz < 350_000_000 && request.input_mode().unwrap().as_str() == "low"
request.stop_hz < 350_000_000
&& DeviceModel::Ultra
.plan(request)
.is_ok_and(|plan| plan.input_command == "mode low input")
}));
assert!(ultra[0].2);
assert!(!ultra[1].2);

View File

@ -26,7 +26,7 @@ try:
return data
assert response() == b'ch>'
client.sendall(b'version\r')
assert b'Basic' in response()
assert b'tinySA_v1.4-mock' in response()
client.sendall(b'mode high input\r')
assert b'error:' not in response()
client.sendall(b'scanraw 240000000 360000000 4\r')

View File

@ -3,10 +3,12 @@
//! 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.
//! state restoration. Identity and the required command inventory are checked
//! before model-specific settings are changed.
use crate::{
config::{ScanConfig, SerialConfig},
config::{ModelSelection, ScanConfig, SerialConfig},
device::{DeviceError, DeviceIdentity, DeviceModel},
protocol::{self, ProtocolError, Sample, ScanRequest},
transport::{Shell, TransportError},
};
@ -38,6 +40,39 @@ pub enum AcquisitionError {
/// An identification reply contained no content.
#[error("the instrument returned an empty version or info reply")]
MissingIdentity,
/// Identity did not unambiguously identify a supported device family.
#[error(transparent)]
Device(#[from] DeviceError),
/// A configured family expectation did not match the detected device.
#[error("configured model {expected} does not match detected {actual}")]
UnexpectedModel {
/// Family required by configuration.
expected: DeviceModel,
/// Family established from device replies.
actual: DeviceModel,
},
/// The device does not advertise a command required by this scan plan.
#[error("{model} firmware does not advertise required command {command:?}")]
MissingCommand {
/// Detected family.
model: DeviceModel,
/// Required console command verb.
command: &'static str,
},
/// The firmware did not return a parseable raw-level offset after setting it.
#[error("could not confirm the raw-level offset after configuring zero {requested}")]
MissingZeroReadback {
/// Offset sent to the device, in dB.
requested: u16,
},
/// The raw-level offset readback differed from the requested decoder value.
#[error("raw-level offset readback is {actual} dB after requesting {requested} dB")]
ZeroReadbackMismatch {
/// Offset sent to the device, in dB.
requested: u16,
/// Offset reported by the device, in dB.
actual: u16,
},
/// Both acquisition and the subsequent resume attempt failed.
#[error("{primary}; additionally, resume failed: {recovery}")]
Recovery {
@ -49,11 +84,12 @@ pub enum AcquisitionError {
},
}
/// Execute a Basic acquisition and return validated samples without file I/O.
/// Detect the device, execute a supported acquisition and return decoded samples.
///
/// 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.
/// 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.
pub fn acquire<T: Read + Write>(
shell: &mut Shell<T>,
request: &ScanRequest,
@ -61,7 +97,7 @@ pub fn acquire<T: Read + Write>(
serial: &SerialConfig,
mut report: impl FnMut(ScanEvent),
) -> Result<Vec<Sample>, AcquisitionError> {
let mode = request.input_mode()?;
request.validate()?;
let delay = Duration::from_millis(serial.command_delay_ms);
let settle = Duration::from_millis(serial.settle_delay_ms);
report(ScanEvent::Message("Identifying instrument"));
@ -72,21 +108,72 @@ pub fn acquire<T: Read + Write>(
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}");
let identity = DeviceIdentity::detect(version, info)?;
let expected = match scan.device_model {
ModelSelection::Auto => None,
ModelSelection::Basic => Some(DeviceModel::Basic),
ModelSelection::Ultra => Some(DeviceModel::Ultra),
};
if let Some(expected) = expected.filter(|expected| *expected != identity.model) {
return Err(AcquisitionError::UnexpectedModel {
expected,
actual: identity.model,
});
}
let plan = identity.model.plan(request)?;
let help = shell.command("help", delay, settle)?;
for command in [
"repeat", "zero", "pause", "mode", "sweep", "scanraw", "resume",
]
.into_iter()
.chain(scan.legacy_pre_scan.then_some("scan"))
{
if !advertises_command(&help, command) {
return Err(AcquisitionError::MissingCommand {
model: identity.model,
command,
});
}
}
report(ScanEvent::InstrumentInfo(format!(
"Detected {} (native raw offset {} dB)\n{}{}",
identity.model, plan.native_zero_offset_db, identity.version, identity.info
)));
for command in ["leveloffset", "vbat", "usart_cfg", "threads", "marker"] {
if advertises_command(&help, command) {
let response = shell.command(command, delay, settle)?;
log::debug!("{command}: {response}");
}
}
report(ScanEvent::Message("Configuring scan"));
let zero_offset = if scan.auto_zero_offset {
plan.native_zero_offset_db
} else {
scan.zero_offset
};
shell.command_checked(&format!("repeat {}", request.repeat), delay, settle)?;
shell.command_checked(&format!("zero {}", scan.zero_offset), delay, settle)?;
shell.command("marker", delay, settle)?;
shell.command_checked(&format!("zero {zero_offset}"), delay, settle)?;
let zero_response = shell.command("zero", delay, settle)?;
match parse_zero_offset(&zero_response) {
Some(actual) if actual == zero_offset => {}
Some(actual) => {
return Err(AcquisitionError::ZeroReadbackMismatch {
requested: zero_offset,
actual,
});
}
None => {
return Err(AcquisitionError::MissingZeroReadback {
requested: zero_offset,
});
}
}
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_checked("pause", delay, settle)?;
shell.command_checked(&format!("mode {} input", mode.as_str()), delay, settle)?;
shell.command_checked(plan.input_command, 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)?;
@ -108,7 +195,7 @@ pub fn acquire<T: Read + Write>(
Ok(protocol::decode_frame(
&frame,
request,
scan.zero_offset,
zero_offset,
scan.frequency_axis,
)?)
})();
@ -128,6 +215,20 @@ pub fn acquire<T: Read + Write>(
}
}
fn advertises_command(help: &str, command: &str) -> bool {
help.split(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
.any(|word| word.eq_ignore_ascii_case(command))
}
fn parse_zero_offset(response: &str) -> Option<u16> {
response.split_whitespace().find_map(|word| {
word.trim_matches(|character: char| !character.is_ascii_alphanumeric() && character != '-')
.to_ascii_lowercase()
.strip_suffix("dbm")
.and_then(|value| value.parse().ok())
})
}
#[cfg(test)]
mod tests {
use super::*;
@ -177,9 +278,11 @@ mod tests {
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());
let mut input = b"ch>tinySA_v1.4-test\r\nch>tinySA\r\nch>Commands: repeat zero pause mode sweep scan scanraw resume leveloffset vbat usart_cfg threads marker\r\nch>".to_vec();
// Five optional diagnostics, repeat, zero mutation/readback, pause, mode and sweep commands.
input.extend_from_slice(b"okch>".repeat(7).as_slice());
input.extend_from_slice(b"usage: zero {level}\r\n128dBm\r\nch>");
input.extend_from_slice(b"okch>".repeat(5 + usize::from(legacy)).as_slice());
input.extend_from_slice(frame);
input.extend_from_slice(b"ch>");
if resume {
@ -209,8 +312,9 @@ mod tests {
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!(commands, "version\rinfo\rhelp\rleveloffset\rvbat\rusart_cfg\rthreads\rmarker\rrepeat 1\rzero 128\rzero\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)));
assert!(events.iter().any(|event| matches!(event, ScanEvent::InstrumentInfo(info) if info.contains("Detected tinySA Basic"))));
}
#[test]
@ -235,4 +339,70 @@ mod tests {
assert!(matches!(result, Err(AcquisitionError::Recovery { .. })));
assert!(commands.ends_with("resume\r"));
}
#[test]
fn help_and_zero_readback_parsers_are_token_bounded() {
assert!(advertises_command("Commands: scan scanraw zero", "scan"));
assert!(!advertises_command("Commands: scanraw", "scan"));
assert_eq!(
parse_zero_offset("usage: zero {level}\r\n174dBm\r\n"),
Some(174)
);
assert_eq!(parse_zero_offset("174 dBm"), None);
}
#[test]
fn failed_detection_capabilities_and_readback_stop_before_scan() {
for (version, info, help, zero, expected) in [
("unknown", "unknown", "", "", "unsupported device"),
("tinySA_v1", "tinySA Ultra", "", "", "conflicting"),
(
"tinySA4_v1",
"tinySA Ultra",
"repeat",
"",
"required command",
),
(
"tinySA4_v1",
"tinySA Ultra",
"repeat zero pause mode sweep scanraw resume",
"128dBm",
"readback is 128",
),
(
"tinySA4_v1",
"tinySA Ultra",
"repeat zero pause mode sweep scanraw resume",
"unknown",
"could not confirm",
),
] {
let config = Config::from_toml(
"[scan]\nlegacy_pre_scan=false\n[serial]\ncommand_delay_ms=0\nsettle_delay_ms=0",
)
.unwrap();
let commands = Arc::new(Mutex::new(Vec::new()));
let input = format!("ch>{version}\r\nch>{info}\r\nch>{help}\r\nch>ch>ch>{zero}\r\nch>");
let mut shell = Shell::new(
Transcript {
input: Cursor::new(input.into_bytes()),
commands: commands.clone(),
},
1024,
);
let request = ScanRequest {
start_hz: 100_000_000,
stop_hz: 800_000_000,
points: 2,
repeat: 1,
};
let error =
acquire(&mut shell, &request, &config.scan, &config.serial, |_| {}).unwrap_err();
assert!(error.to_string().contains(expected), "{error}");
let written = String::from_utf8(commands.lock().unwrap().clone()).unwrap();
assert!(!written.contains("pause\r"));
assert!(!written.contains("scanraw "));
}
}
}

View File

@ -106,17 +106,34 @@ pub struct SerialConfig {
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FrequencyAxis {
/// Preserve historical CSV labels, including the requested stop frequency.
/// Preserve legacy tiny-wb labels, including the requested stop frequency.
Inclusive,
/// Match the reviewed firmware's `span / points` calculation.
/// Match the reviewed `scanraw` integer and single-precision calculation.
Firmware,
}
/// Scan settings; Basic model frequency limits remain protocol invariants.
/// Optional identity expectation; acquisition always detects the connected family.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ModelSelection {
/// Accept either recognized family and apply its profile automatically.
Auto,
/// Require a detected tinySA Basic.
Basic,
/// Require a detected tinySA Ultra/Ultra+ family device.
Ultra,
}
/// Scan settings; model-specific frequency limits are enforced by device plans.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ScanConfig {
/// Expected device family; `auto` still rejects unknown or conflicting identity.
pub device_model: ModelSelection,
/// 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.
/// Used only when `auto_zero_offset` is false.
pub zero_offset: u16,
/// Keyboard step for frequencies, in MHz.
pub frequency_step_mhz: usize,
@ -335,10 +352,21 @@ mod tests {
#[test]
fn defaults_and_legacy_settings_are_supported() {
Config::default().validate().unwrap();
assert_eq!(
Config::default().scan.frequency_axis,
FrequencyAxis::Firmware
);
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_eq!(config.serial, Config::default().serial);
assert_eq!(
Config::from_toml("[scan]\nfrequency_axis = 'inclusive'")
.unwrap()
.scan
.frequency_axis,
FrequencyAxis::Inclusive
);
}
#[test]
@ -371,6 +399,7 @@ mod tests {
"[scan]\nmin_points = 0",
"[scan]\nfrequency_step_mhz = 0",
"[scan]\nzero_offset = 2048",
"[scan]\ndevice_model = 'unknown'",
"[scan]\nfrequency_axis = 'unknown'",
"[ui]\nchart_min_dbm = nan",
"[ui]\nchart_min_dbm = 1.0",

198
src/device.rs Normal file
View File

@ -0,0 +1,198 @@
//! 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.
use crate::protocol::{
ProtocolError, ScanRequest, BASIC_MAX_HZ, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB,
};
use std::fmt;
/// Lowest documented Ultra analyzer frequency, in Hz.
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;
/// Device family established from console identity replies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceModel {
/// Original 2.8-inch tinySA with low and high input paths.
Basic,
/// tinySA Ultra/Ultra+ family, restricted here to the common normal range.
Ultra,
}
impl fmt::Display for DeviceModel {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Basic => "tinySA Basic",
Self::Ultra => "tinySA Ultra family",
})
}
}
/// Identity replies retained together with the detected family.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceIdentity {
/// Detected device family.
pub model: DeviceModel,
/// Verbatim prompt-stripped `version` response.
pub version: String,
/// Verbatim prompt-stripped `info` response.
pub info: String,
}
/// A validated model-specific command and decoding plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AcquisitionPlan {
/// Detected device family.
pub model: DeviceModel,
/// Model-correct console command selecting the input path.
pub input_command: &'static str,
/// Native raw-level encoding offset, in dB.
pub native_zero_offset_db: u16,
}
/// Device identification failures occur before acquisition settings are changed.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DeviceError {
/// Neither reply contained a recognized model signature.
#[error("unsupported device identity; expected tinySA_v… or tinySA4_v… in version/info")]
Unknown,
/// Basic and Ultra signatures occurred in the same identity exchange.
#[error("conflicting device identity: replies identify both tinySA Basic and Ultra")]
Conflicting,
}
impl DeviceIdentity {
/// Detect a Basic or Ultra family from `version` and `info` replies.
///
/// Basic firmware uses a `tinySA_v…` version token; Ultra-family firmware
/// uses `tinySA4_v…`. Explicit Basic/Ultra names in `info` are also accepted.
/// Shared source URLs and generic `tinySA` substrings are not sufficient.
pub fn detect(version: String, info: String) -> Result<Self, DeviceError> {
let version_lower = version.to_ascii_lowercase();
let info_lower = info.to_ascii_lowercase();
let ultra = version_lower
.split_whitespace()
.any(|token| token.starts_with("tinysa4_v"))
|| info_lower.contains("tinysa ultra");
let basic = version_lower
.split_whitespace()
.any(|token| token.starts_with("tinysa_v"))
|| info_lower.contains("tinysa basic")
|| info_lower.lines().any(|line| line.trim() == "tinysa");
let model = match (basic, ultra) {
(true, false) => DeviceModel::Basic,
(false, true) => DeviceModel::Ultra,
(true, true) => return Err(DeviceError::Conflicting),
(false, false) => return Err(DeviceError::Unknown),
};
Ok(Self {
model,
version,
info,
})
}
}
impl DeviceModel {
/// Validate a request against this family and choose its input command.
pub fn plan(self, request: &ScanRequest) -> Result<AcquisitionPlan, ProtocolError> {
request.validate()?;
let (input_command, native_zero_offset_db) = match self {
Self::Basic => {
if request.stop_hz > BASIC_MAX_HZ {
return Err(ProtocolError::InvalidRequest(
"tinySA Basic frequencies must be within 0–960 MHz".into(),
));
}
let command = if request.stop_hz < 350_000_000 {
"mode low input"
} else if request.start_hz >= 240_000_000 {
"mode high input"
} else {
return Err(ProtocolError::InvalidRequest(
"a Basic span crossing 350 MHz must start at or above 240 MHz".into(),
));
};
(command, BASIC_RAW_LEVEL_OFFSET_DB)
}
Self::Ultra => {
if request.start_hz < ULTRA_MIN_HZ || request.stop_hz > ULTRA_NORMAL_MAX_HZ {
return Err(ProtocolError::InvalidRequest(
"tinySA Ultra first-tier support is limited to the common 0.1–800 MHz normal range; extended and harmonic modes are not enabled"
.into(),
));
}
("mode low input", ULTRA_RAW_LEVEL_OFFSET_DB)
}
};
Ok(AcquisitionPlan {
model: self,
input_command,
native_zero_offset_db,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn request(start_hz: u64, stop_hz: u64) -> ScanRequest {
ScanRequest {
start_hz,
stop_hz,
points: 101,
repeat: 1,
}
}
#[test]
fn identity_requires_unambiguous_family_evidence() {
assert_eq!(
DeviceIdentity::detect("tinySA_v1.4-175-gabc".into(), "tinySA".into())
.unwrap()
.model,
DeviceModel::Basic
);
assert_eq!(
DeviceIdentity::detect("tinySA4_v1.4-200-gabc".into(), "tinySA Ultra+".into())
.unwrap()
.model,
DeviceModel::Ultra
);
assert_eq!(
DeviceIdentity::detect("version unknown".into(), "instrument".into()),
Err(DeviceError::Unknown)
);
assert_eq!(
DeviceIdentity::detect("tinySA_v1".into(), "tinySA Ultra".into()),
Err(DeviceError::Conflicting)
);
}
#[test]
fn model_plans_enforce_paths_ranges_and_native_offsets() {
let low = DeviceModel::Basic.plan(&request(0, 349_999_999)).unwrap();
assert_eq!(low.input_command, "mode low input");
assert_eq!(low.native_zero_offset_db, 128);
let high = DeviceModel::Basic
.plan(&request(240_000_000, 960_000_000))
.unwrap();
assert_eq!(high.input_command, "mode high input");
assert!(DeviceModel::Basic.plan(&request(0, 350_000_000)).is_err());
let ultra = DeviceModel::Ultra
.plan(&request(ULTRA_MIN_HZ, ULTRA_NORMAL_MAX_HZ))
.unwrap();
assert_eq!(ultra.input_command, "mode low input");
assert_eq!(ultra.native_zero_offset_db, 174);
assert!(DeviceModel::Ultra.plan(&request(0, 800_000_000)).is_err());
assert!(DeviceModel::Ultra
.plan(&request(100_000, 800_000_001))
.is_err());
}
}

View File

@ -13,10 +13,10 @@
//! use tiny_wb::{config::FrequencyAxis, export::write_csv, protocol::{decode_frame, ScanRequest}};
//!
//! let request = ScanRequest { start_hz: 240_000_000, stop_hz: 960_000_000, points: 2, repeat: 1 };
//! let samples = decode_frame(b"{x\x00\x08x\x00\x10}", &request, 128, FrequencyAxis::Inclusive)?;
//! let samples = decode_frame(b"{x\x00\x08x\x00\x10}", &request, 128, FrequencyAxis::Firmware)?;
//! let mut csv = Vec::new();
//! write_csv(&mut csv, &samples, true)?;
//! assert_eq!(String::from_utf8(csv)?, "frequency_MHz,level_dBm\n240,-64\n960,0\n");
//! assert_eq!(String::from_utf8(csv)?, "frequency_MHz,level_dBm\n240,-64\n600,0\n");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
@ -25,6 +25,7 @@
pub mod acquisition;
pub mod config;
pub mod connection;
pub mod device;
pub mod export;
/// Opt-in deterministic simulator and TCP server support.
#[cfg(feature = "mock")]

View File

@ -1,5 +1,8 @@
//! Bounded, stateful console simulation and an in-memory duplex stream.
use crate::protocol::{
firmware_frequency_hz, ScanRequest, BASIC_RAW_LEVEL_OFFSET_DB, ULTRA_RAW_LEVEL_OFFSET_DB,
};
use serde::{Deserialize, Serialize};
use std::{
collections::VecDeque,
@ -187,9 +190,9 @@ impl MockStream {
points: 101.min(config.max_points),
repeat: 1,
zero_offset: if config.model == MockModel::Basic {
128
BASIC_RAW_LEVEL_OFFSET_DB
} else {
174
ULTRA_RAW_LEVEL_OFFSET_DB
},
lna: false,
ultra: false,
@ -283,18 +286,14 @@ impl MockStream {
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(),
["version"] => match self.state.model {
MockModel::Basic => b"tinySA_v1.4-mock (synthetic)\r\n".to_vec(),
MockModel::Ultra => b"tinySA4_v1.4-mock (synthetic)\r\n".to_vec(),
},
["info"] => match self.state.model {
MockModel::Basic => b"tinySA\nmock; not real firmware\r\n".to_vec(),
MockModel::Ultra => b"tinySA Ultra mock; not real firmware\r\n".to_vec(),
},
["help"] => {
let extra = if self.state.model == MockModel::Ultra {
" lna ultra"
@ -345,6 +344,9 @@ impl MockStream {
}
_ => invalid(),
},
["zero"] => {
format!("usage: zero {{level}}\r\n{}dBm\r\n", self.state.zero_offset).into_bytes()
}
["sweep", "start" | "stop", value] => match value.parse::<u64>() {
Ok(value) if value <= self.max_hz() => {
if fields[1] == "start" {
@ -366,10 +368,14 @@ impl MockStream {
self.state.points = points;
let mut frame = Vec::with_capacity(points * 3 + 4);
frame.push(b'{');
let request = ScanRequest {
start_hz: start,
stop_hz: stop,
points,
repeat: self.state.repeat,
};
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 frequency = firmware_frequency_hz(&request, index) as f64;
let strength = (1.0
- (frequency - self.config.peak_frequency_hz as f64).abs()
/ self.config.peak_width_hz as f64)

View File

@ -1,12 +1,16 @@
//! Basic input selection and pure, length-checked `scanraw` decoding.
//! Model-independent request validation and 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.
/// Highest supported Basic frequency, in Hz.
pub const BASIC_MAX_HZ: u64 = 960_000_000;
/// Native `scanraw` level bias used by tinySA Basic firmware, in dB.
pub const BASIC_RAW_LEVEL_OFFSET_DB: u16 = 128;
/// Native `scanraw` level bias used by tinySA Ultra firmware, in dB.
pub const ULTRA_RAW_LEVEL_OFFSET_DB: u16 = 174;
/// Host allocation limit retained from the original UI.
pub const MAX_POINTS: usize = 1_000_001;
@ -32,17 +36,17 @@ pub struct ScanRequest {
pub repeat: usize,
}
/// The Basic's physical input path; this is not an Ultra capability model.
/// Legacy Basic input-path selection; use `DeviceModel::plan` for automatic models.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
/// Input path below 350 MHz.
/// Basic low input.
Low,
/// High path, also used for a span starting at/above 240 MHz and crossing 350 MHz.
/// Basic high input.
High,
}
impl InputMode {
/// Keyword used by the `mode ... input` shell command.
/// Console keyword identifying the Basic input path.
pub fn as_str(self) -> &'static str {
match self {
Self::Low => "low",
@ -82,41 +86,43 @@ pub enum ProtocolError {
}
impl ScanRequest {
/// Validate point/repeat bounds and choose the historical Basic input path.
/// Validate this request using the legacy Basic profile.
/// Ultra callers should use `DeviceModel::Ultra.plan` instead.
pub fn input_mode(&self) -> Result<InputMode, ProtocolError> {
let plan = crate::device::DeviceModel::Basic.plan(self)?;
Ok(if plan.input_command == "mode high input" {
InputMode::High
} else {
InputMode::Low
})
}
/// Validate model-independent ordering and point/repeat bounds.
pub fn validate(&self) -> Result<(), ProtocolError> {
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 {
if self.start_hz > self.stop_hz {
return Err(ProtocolError::InvalidRequest(
"frequencies must be ordered within 0–960 MHz".into(),
"start frequency must not exceed stop frequency".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(),
))
}
Ok(())
}
/// Exact framed byte count; validation happens before multiplication/allocation.
pub fn frame_len(&self) -> Result<usize, ProtocolError> {
self.input_mode()?;
self.validate()?;
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
/// `zero_offset` must match the `zero` command sent to the device. Frequency
/// labeling is explicit because legacy tiny-wb output and `scanraw` use
/// different arithmetic. Malformed/short/extra records are rejected before
/// callers can export a completed scan.
pub fn decode_frame(
frame: &[u8],
@ -142,11 +148,6 @@ pub fn decode_frame(
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;
// The exact frame length checked above guarantees no partial record remains.
frame[1..frame.len() - 1]
.as_chunks::<3>()
@ -161,7 +162,18 @@ pub fn decode_frame(
});
}
Ok(Sample {
frequency_mhz: (request.start_hz as f64 + index as f64 * step) / 1_000_000.0,
frequency_mhz: match axis {
FrequencyAxis::Inclusive => {
let intervals = request.points - 1;
(request.start_hz as f64
+ index as f64 * (request.stop_hz - request.start_hz) as f64
/ intervals as f64)
/ 1_000_000.0
}
FrequencyAxis::Firmware => {
firmware_frequency_hz(request, index) as f64 / 1_000_000.0
}
},
level_dbm: f64::from(u16::from_le_bytes([record[1], record[2]])) / 32.0
- f64::from(zero_offset),
})
@ -169,6 +181,18 @@ pub fn decode_frame(
.collect()
}
/// Reproduce the reviewed firmware's `scanraw` frequency expression.
///
/// The C implementation first performs integer division, converts that result
/// to a 32-bit `float`, multiplies it by the point index, then truncates the
/// product back to `freq_t` before adding `start`.
pub(crate) fn firmware_frequency_hz(request: &ScanRequest, index: usize) -> u64 {
debug_assert!(index < request.points);
let integer_step_hz = (request.stop_hz - request.start_hz) / request.points as u64;
let firmware_step_hz = integer_step_hz as f32;
request.start_hz + (firmware_step_hz * index as f32) as u64
}
#[cfg(test)]
mod tests {
use super::*;
@ -182,27 +206,21 @@ mod tests {
}
#[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
);
fn structural_request_boundaries_are_model_independent() {
assert!(ScanRequest {
start_hz: 100,
stop_hz: 99,
..request()
}
.validate()
.is_err());
assert!(ScanRequest {
start_hz: 0,
stop_hz: u64::MAX,
..request()
}
.validate()
.is_ok());
for points in [0, 1, MAX_POINTS + 1, usize::MAX] {
assert!(ScanRequest {
points,
@ -215,13 +233,13 @@ mod tests {
repeat: 0,
..request()
}
.input_mode()
.validate()
.is_err());
assert!(ScanRequest {
repeat: 1001,
..request()
}
.input_mode()
.validate()
.is_err());
}
@ -252,6 +270,33 @@ mod tests {
);
}
#[test]
fn firmware_axis_reproduces_integer_step_and_float_rounding() {
let request = ScanRequest {
start_hz: 0,
stop_hz: 10,
points: 3,
repeat: 1,
};
let samples =
decode_frame(b"{x\0\0x\0\0x\0\0}", &request, 0, FrequencyAxis::Firmware).unwrap();
assert_eq!(
samples
.iter()
.map(|sample| sample.frequency_mhz * 1_000_000.0)
.collect::<Vec<_>>(),
vec![0.0, 3.0, 6.0]
);
let request = ScanRequest {
start_hz: 0,
stop_hz: 100_000_002,
points: 2,
repeat: 1,
};
assert_eq!(firmware_frequency_hz(&request, 1), 50_000_000);
}
#[test]
fn truncated_extra_and_misaligned_frames_are_rejected_without_panics() {
let frame = b"{x\x00\x08x\x00\x10}";

View File

@ -128,7 +128,7 @@ pub(crate) fn run_scan(
}
config.validate()?;
request
.input_mode()
.validate()
.map_err(tiny_wb::acquisition::AcquisitionError::from)?;
let port = open_connection(&config)?;
let mut shell = Shell::new(port, config.serial.max_response_bytes);

View File

@ -233,7 +233,7 @@ impl App {
repeat: config.repeat,
};
request
.input_mode()
.validate()
.map_err(tiny_wb::acquisition::AcquisitionError::from)
.map_err(AppError::from)?;
config.save(&self.config_path).map_err(AppError::from)?;
@ -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(0, 10, 0, 960);
app.start_frequency = NumericInput::new(900, 10, 0, 960);
assert!(app.next_step().is_err());
assert_eq!(app.scan_state.status(), ScanStatus::Ready);
}

View File

@ -30,6 +30,11 @@ confirms their syntax and availability on the selected build.
## Current baseline
Update 2026-10-05: automatic family detection, offset readback and common Ultra
normal-range acquisition are now implemented. The table below is the planning
baseline; [current support status](docs/ultra-support.md) supersedes its missing
model-detection entry. Hardware and extended-range gates remain open.
| Area | Delivered | Still missing |
| --- | --- | --- |
| Library | Terminal-independent config, framing, Basic acquisition, CSV; optional serial/mock features | Model/session API and the remaining device operations |

View File

@ -122,31 +122,55 @@ fn faults_fail_acquisition_and_attempt_recovery() {
}
#[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);
}
fn rejected_pause_is_not_silent_success() {
let mut device = MockStream::new(MockConfig {
fault: MockFault::Reject,
fault_command: "pause".into(),
..MockConfig::default()
})
.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 acquisition_detects_ultra_and_uses_native_offset_without_high_mode() {
let mut device = MockStream::new(MockConfig {
model: MockModel::Ultra,
..MockConfig::default()
})
.unwrap();
let config = settings();
let samples = acquire(
&mut Shell::new(&mut device, 65536),
&request(),
&config.scan,
&config.serial,
|_| {},
)
.unwrap();
assert_eq!(samples.len(), request().points);
assert_eq!(device.state().zero_offset, 174);
assert_eq!(device.state().input, "input");
assert!(device
.state()
.commands
.iter()
.any(|command| command == "mode low input"));
assert!(!device
.state()
.commands
.iter()
.any(|command| command == "mode high input"));
}
#[test]
@ -159,7 +183,7 @@ fn ultra_profile_and_explicit_command_subset() {
.unwrap();
drain(&mut device);
assert_eq!(device.state().zero_offset, 174);
assert!(command(&mut device, "version").contains("Ultra"));
assert!(command(&mut device, "version").contains("tinySA4_v"));
assert!(command(&mut device, "help").contains("lna ultra"));
for cmd in [
"mode input",