Refactor radar system
This commit is contained in:
@@ -3,14 +3,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
from python_app.models.json_fields import (
|
||||
read_bool as _require_bool, read_int as _require_int, read_str as _require_str,
|
||||
)
|
||||
from python_app.models.run_config_schema import (
|
||||
MAX_COMBOS,
|
||||
ComboModel,
|
||||
ControlButtonModel,
|
||||
GprModel,
|
||||
RadarSweepModel,
|
||||
RingEndpointModel,
|
||||
RunConfigModel,
|
||||
SwitchModel,
|
||||
)
|
||||
|
||||
@@ -21,45 +27,6 @@ logger = logging.getLogger(__name__)
|
||||
# shared-memory mapping, so reject values the C++ side cannot represent.
|
||||
_UINT32_MAX = (1 << 32) - 1
|
||||
_RING_SEGMENT_MAX_BYTES = 1 << 40 # 1 TiB upper bound on a single ring mapping.
|
||||
# Defensive ceiling so a malformed combos string cannot expand into a list that
|
||||
# stalls the GUI or the downstream acquisition loop.
|
||||
_MAX_COMBOS = 4096
|
||||
|
||||
|
||||
def _require_int(payload: dict[str, Any], key: str, default: int) -> int:
|
||||
"""Read a strict JSON integer, treating an explicit ``null`` as 'use default'.
|
||||
|
||||
Accepts only a genuine JSON integer (not bool, not float, not numeric string),
|
||||
because silently truncating ``5.7`` or parsing ``"5"`` would hide a malformed
|
||||
config. Mirrors ``run_config_codec._read_int`` so every config integer reads
|
||||
identically.
|
||||
"""
|
||||
value = payload.get(key, default)
|
||||
if value is None: # explicit JSON null -> use the default, never coerce
|
||||
return default
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"{key} must be a JSON integer")
|
||||
return value
|
||||
|
||||
|
||||
def _require_str(payload: dict[str, Any], key: str, default: str) -> str:
|
||||
"""Read a string field, rejecting JSON arrays/objects with a named ValueError."""
|
||||
value = payload.get(key, default)
|
||||
if value is None: # explicit JSON null -> use the default, never coerce to "None"
|
||||
return default
|
||||
if isinstance(value, (dict, list)):
|
||||
raise ValueError(f"{key} must be a JSON string")
|
||||
return str(value)
|
||||
|
||||
|
||||
def _require_bool(payload: dict[str, Any], key: str, default: bool) -> bool:
|
||||
"""Read a boolean field, rejecting non-boolean JSON types with a named ValueError."""
|
||||
value = payload.get(key, default)
|
||||
if value is None: # explicit JSON null -> use the default
|
||||
return default
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(f"{key} must be a JSON boolean")
|
||||
return value
|
||||
|
||||
|
||||
def load_switch_payload(
|
||||
@@ -117,18 +84,79 @@ def validate_ring_endpoint(ring: RingEndpointModel) -> None:
|
||||
would exceed the maximum single mapping.
|
||||
"""
|
||||
ring_name = ring.name or "ring"
|
||||
for field, value in (("capacity", ring.capacity), ("slot_size_bytes", ring.slot_size_bytes)):
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"rings.{ring_name}.{field} must be an integer")
|
||||
if ring.capacity <= 0:
|
||||
raise ValueError(f"rings.{ring_name}.capacity must be > 0")
|
||||
if ring.slot_size_bytes <= 0:
|
||||
raise ValueError(f"rings.{ring_name}.slot_size_bytes must be > 0")
|
||||
if ring.slot_size_bytes > _UINT32_MAX:
|
||||
raise ValueError(f"rings.{ring_name}.slot_size_bytes exceeds the uint32 wire limit")
|
||||
if ring.slot_size_bytes % 8:
|
||||
raise ValueError(f"rings.{ring_name}.slot_size_bytes must be a multiple of 8")
|
||||
# Overflow-safe: compare against the ceiling without ever forming the full
|
||||
# product, so an oversized capacity cannot wrap a fixed-width index.
|
||||
if ring.capacity > _RING_SEGMENT_MAX_BYTES // ring.slot_size_bytes:
|
||||
if ring.capacity > (_RING_SEGMENT_MAX_BYTES - 64) // (ring.slot_size_bytes + 16):
|
||||
raise ValueError(
|
||||
f"rings.{ring_name} capacity * slot_size_bytes exceeds the maximum ring segment size"
|
||||
)
|
||||
if ring.capacity > _UINT32_MAX:
|
||||
raise ValueError(f"rings.{ring_name}.capacity exceeds the uint32 wire limit")
|
||||
|
||||
|
||||
def validate_acquisition_config(config: RunConfigModel) -> None:
|
||||
"""Reject unusable acquisition settings before starting processes or hardware.
|
||||
|
||||
Replay uses the recorded trace dimensions and needs no physical devices; its
|
||||
producer checks the actual payload size before publishing a frame.
|
||||
"""
|
||||
if config.radar.replay.dataset_dir:
|
||||
return
|
||||
mode = config.radar.driver_mode
|
||||
if mode not in ("mock", "native"):
|
||||
raise ValueError("radar.driver_mode must be mock or native")
|
||||
if config.radar.model not in (
|
||||
config.LIBREVNA_MODEL, config.LIBREVNA_MULTI_MODEL, config.KAMIL_ADC_MODEL,
|
||||
):
|
||||
raise ValueError(f"Unsupported radar model: {config.radar.model}")
|
||||
if mode != "native" and config.is_kamil_adc:
|
||||
raise ValueError(f"{config.radar.model} requires native driver mode")
|
||||
|
||||
for switch, physical_positions in (
|
||||
(config.input_switch, config.matrix_input_switch_positions),
|
||||
(config.output_switch, config.matrix_output_switch_positions),
|
||||
):
|
||||
context = f"switches.{switch.name or switch.radar_port}"
|
||||
if switch.driver_mode not in ("mock", "native"):
|
||||
raise ValueError(f"{context}.driver_mode must be mock or native")
|
||||
if switch.driver not in ("h7992", "hmc349a"):
|
||||
raise ValueError(f"{context}.driver must be h7992 or hmc349a")
|
||||
if switch.radar_port not in (1, 2):
|
||||
raise ValueError(f"{context}.radar_port must be 1 or 2")
|
||||
if not 0 <= switch.default_position < switch.positions:
|
||||
raise ValueError(f"{context}.default_position must be within switch positions")
|
||||
positions, switch_mode = switch.positions, switch.driver_mode
|
||||
if config.is_matrix_radar and physical_positions > 1:
|
||||
positions, switch_mode = physical_positions, mode
|
||||
if switch_mode == "native":
|
||||
limit = 4 if switch.driver == "h7992" else 2
|
||||
if not 1 <= positions <= limit:
|
||||
raise ValueError(f"{context}: native {switch.driver} supports 1..{limit} positions")
|
||||
if not switch.gpio_chip or switch.pin_a < 0 or (
|
||||
switch.driver == "h7992" and (switch.pin_b < 0 or switch.pin_b == switch.pin_a)
|
||||
):
|
||||
raise ValueError(f"{context}: GPIO chip and distinct nonnegative control pins are required")
|
||||
|
||||
points = config.radar.kamil_adc.band.points if config.is_kamil_adc else config.radar.sweep.points
|
||||
# RAW/PPR header, each combo's frequency/S11/S21 arrays and capture windows.
|
||||
minimum = 44 + len(config.combos) * (28 + 20 * points)
|
||||
for name in ("raw", "raw_tap", "preprocessed", "preprocessed_tap"):
|
||||
ring = getattr(config.rings, name)
|
||||
if name.endswith("_tap") and not ring.name:
|
||||
continue
|
||||
if ring.slot_size_bytes < minimum:
|
||||
raise ValueError(f"rings.{name}.slot_size_bytes must be at least {minimum} for this sweep")
|
||||
|
||||
|
||||
def validate_sweep_model(sweep: RadarSweepModel) -> None:
|
||||
@@ -143,9 +171,17 @@ def validate_sweep_model(sweep: RadarSweepModel) -> None:
|
||||
points = sweep.points
|
||||
if isinstance(points, bool) or not isinstance(points, int):
|
||||
raise ValueError("radar.sweep.points must be an integer")
|
||||
if points <= 0:
|
||||
raise ValueError("radar.sweep.points must be > 0")
|
||||
if float(sweep.stop_hz) <= float(sweep.start_hz):
|
||||
if not 0 < points <= _UINT32_MAX:
|
||||
raise ValueError("radar.sweep.points must be in [1, uint32 max]")
|
||||
for field in ("start_hz", "stop_hz", "if_bandwidth_hz", "power_dbm"):
|
||||
value = getattr(sweep, field)
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or abs(value) > 3.4e38 or not math.isfinite(value):
|
||||
raise ValueError(f"radar.sweep.{field} must be a finite float32 number")
|
||||
if sweep.start_hz < 0:
|
||||
raise ValueError("radar.sweep.start_hz must be >= 0")
|
||||
if sweep.if_bandwidth_hz <= 0:
|
||||
raise ValueError("radar.sweep.if_bandwidth_hz must be > 0")
|
||||
if sweep.stop_hz <= sweep.start_hz:
|
||||
raise ValueError("radar.sweep.stop_hz must be > radar.sweep.start_hz")
|
||||
|
||||
|
||||
@@ -167,12 +203,16 @@ def validate_gpr_model(
|
||||
if sweep is not None:
|
||||
validate_sweep_model(sweep)
|
||||
|
||||
if float(gpr.relative_permittivity) <= 0.0:
|
||||
if not math.isfinite(gpr.relative_permittivity) or float(gpr.relative_permittivity) <= 0.0:
|
||||
raise ValueError("gpr.relative_permittivity must be > 0")
|
||||
|
||||
seen_output_positions: set[int] = set()
|
||||
for entry in gpr.tx_geometry:
|
||||
output_pos = int(entry.output_pos)
|
||||
if any(not math.isfinite(value) or abs(value) > 3.4e38 for value in (entry.x_m, entry.y_m, entry.z_m)):
|
||||
raise ValueError("gpr.tx_geometry coordinates must be finite numbers")
|
||||
output_pos = entry.output_pos
|
||||
if isinstance(output_pos, bool) or not isinstance(output_pos, int):
|
||||
raise ValueError("gpr.tx_geometry output_pos must be an integer")
|
||||
if output_pos < 0 or output_pos >= int(output_switch_positions):
|
||||
raise ValueError("gpr.tx_geometry output_pos is out of range")
|
||||
if output_pos in seen_output_positions:
|
||||
@@ -181,7 +221,11 @@ def validate_gpr_model(
|
||||
|
||||
seen_input_positions: set[int] = set()
|
||||
for entry in gpr.rx_geometry:
|
||||
input_pos = int(entry.input_pos)
|
||||
if any(not math.isfinite(value) or abs(value) > 3.4e38 for value in (entry.x_m, entry.y_m, entry.z_m)):
|
||||
raise ValueError("gpr.rx_geometry coordinates must be finite numbers")
|
||||
input_pos = entry.input_pos
|
||||
if isinstance(input_pos, bool) or not isinstance(input_pos, int):
|
||||
raise ValueError("gpr.rx_geometry input_pos must be an integer")
|
||||
if input_pos < 0 or input_pos >= int(input_switch_positions):
|
||||
raise ValueError("gpr.rx_geometry input_pos is out of range")
|
||||
if input_pos in seen_input_positions:
|
||||
@@ -202,12 +246,18 @@ def validate_combos(
|
||||
config error that would otherwise produce missing or doubled traces downstream.
|
||||
"""
|
||||
seen: set[tuple[int, int]] = set()
|
||||
if len(combos) > MAX_COMBOS:
|
||||
raise ValueError(f"Too many combos: limit is {MAX_COMBOS}")
|
||||
for combo in combos:
|
||||
if not 0 <= int(combo.input) < int(input_positions):
|
||||
for field in ("input", "output"):
|
||||
value = getattr(combo, field)
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise ValueError(f"run.combos {field} must be an integer")
|
||||
if not 0 <= combo.input < input_positions:
|
||||
raise ValueError(
|
||||
f"run.combos input {combo.input} is out of range [0, {input_positions})"
|
||||
)
|
||||
if not 0 <= int(combo.output) < int(output_positions):
|
||||
if not 0 <= combo.output < output_positions:
|
||||
raise ValueError(
|
||||
f"run.combos output {combo.output} is out of range [0, {output_positions})"
|
||||
)
|
||||
@@ -222,7 +272,7 @@ def parse_combos_from_text(text: str) -> list[ComboModel]:
|
||||
|
||||
Returns an empty list for blank input. Raises ValueError (naming the
|
||||
offending pair) on malformed syntax, empty sides, non-integer values, more
|
||||
than ``_MAX_COMBOS`` entries, or a non-blank string that yields no combos.
|
||||
than ``MAX_COMBOS`` entries, or a non-blank string that yields no combos.
|
||||
"""
|
||||
cleaned = text.strip()
|
||||
if not cleaned:
|
||||
@@ -238,8 +288,8 @@ def parse_combos_from_text(text: str) -> list[ComboModel]:
|
||||
|
||||
# Cap the combo count so a pathological string cannot expand into a list
|
||||
# large enough to stall the GUI or the acquisition loop.
|
||||
if len(combos) >= _MAX_COMBOS:
|
||||
raise ValueError(f"Too many combos: limit is {_MAX_COMBOS}")
|
||||
if len(combos) >= MAX_COMBOS:
|
||||
raise ValueError(f"Too many combos: limit is {MAX_COMBOS}")
|
||||
|
||||
input_text, output_text = (side.strip() for side in pair.split(":", 1))
|
||||
# Reject empty sides and re-raise non-integer values naming the pair/side.
|
||||
|
||||
Reference in New Issue
Block a user