rtl-sdr-analyzer 3.0.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. rtl_sdr_analyzer/__init__.py +3 -0
  2. rtl_sdr_analyzer/__main__.py +6 -0
  3. rtl_sdr_analyzer/cli/__init__.py +0 -0
  4. rtl_sdr_analyzer/cli/app.py +588 -0
  5. rtl_sdr_analyzer/cli/config_overrides.py +42 -0
  6. rtl_sdr_analyzer/config/__init__.py +0 -0
  7. rtl_sdr_analyzer/config/loader.py +103 -0
  8. rtl_sdr_analyzer/config/models.py +109 -0
  9. rtl_sdr_analyzer/detection/__init__.py +11 -0
  10. rtl_sdr_analyzer/detection/detector.py +209 -0
  11. rtl_sdr_analyzer/detection/events.py +73 -0
  12. rtl_sdr_analyzer/dsp/__init__.py +17 -0
  13. rtl_sdr_analyzer/dsp/processor.py +241 -0
  14. rtl_sdr_analyzer/engine/__init__.py +15 -0
  15. rtl_sdr_analyzer/engine/event_bus.py +42 -0
  16. rtl_sdr_analyzer/engine/spectrum_engine.py +822 -0
  17. rtl_sdr_analyzer/engine/sweeper.py +302 -0
  18. rtl_sdr_analyzer/exporters/__init__.py +11 -0
  19. rtl_sdr_analyzer/exporters/base.py +33 -0
  20. rtl_sdr_analyzer/exporters/csv_exporter.py +65 -0
  21. rtl_sdr_analyzer/exporters/json_exporter.py +41 -0
  22. rtl_sdr_analyzer/logging_config.py +83 -0
  23. rtl_sdr_analyzer/py.typed +0 -0
  24. rtl_sdr_analyzer/recording/__init__.py +3 -0
  25. rtl_sdr_analyzer/recording/metadata.py +79 -0
  26. rtl_sdr_analyzer/recording/recorder.py +162 -0
  27. rtl_sdr_analyzer/sources/__init__.py +39 -0
  28. rtl_sdr_analyzer/sources/base.py +145 -0
  29. rtl_sdr_analyzer/sources/factory.py +139 -0
  30. rtl_sdr_analyzer/sources/replay.py +211 -0
  31. rtl_sdr_analyzer/sources/rtl_tcp.py +251 -0
  32. rtl_sdr_analyzer/sources/simulated.py +188 -0
  33. rtl_sdr_analyzer/sources/usb.py +656 -0
  34. rtl_sdr_analyzer/storage/__init__.py +4 -0
  35. rtl_sdr_analyzer/storage/database.py +302 -0
  36. rtl_sdr_analyzer/storage/stats.py +165 -0
  37. rtl_sdr_analyzer/visualization/__init__.py +5 -0
  38. rtl_sdr_analyzer/visualization/headless.py +82 -0
  39. rtl_sdr_analyzer/web/__init__.py +5 -0
  40. rtl_sdr_analyzer/web/app.py +159 -0
  41. rtl_sdr_analyzer/web/routes.py +540 -0
  42. rtl_sdr_analyzer/web/static/amstech-ui/README.md +134 -0
  43. rtl_sdr_analyzer/web/static/amstech-ui/componentes.css +178 -0
  44. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/LICENCIA-bricolage-grotesque.txt +93 -0
  45. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/LICENCIA-dm-mono.txt +93 -0
  46. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/LICENCIA-figtree.txt +93 -0
  47. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/bricolage-grotesque-latin-ext-opsz-normal.woff2 +0 -0
  48. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/bricolage-grotesque-latin-opsz-normal.woff2 +0 -0
  49. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/dm-mono-latin-400-normal.woff2 +0 -0
  50. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/dm-mono-latin-500-normal.woff2 +0 -0
  51. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/dm-mono-latin-ext-400-normal.woff2 +0 -0
  52. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/dm-mono-latin-ext-500-normal.woff2 +0 -0
  53. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-400-normal.woff2 +0 -0
  54. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-500-normal.woff2 +0 -0
  55. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-600-normal.woff2 +0 -0
  56. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-700-normal.woff2 +0 -0
  57. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-800-normal.woff2 +0 -0
  58. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-ext-400-normal.woff2 +0 -0
  59. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-ext-500-normal.woff2 +0 -0
  60. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-ext-600-normal.woff2 +0 -0
  61. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-ext-700-normal.woff2 +0 -0
  62. rtl_sdr_analyzer/web/static/amstech-ui/fuentes/figtree-latin-ext-800-normal.woff2 +0 -0
  63. rtl_sdr_analyzer/web/static/amstech-ui/fuentes.css +39 -0
  64. rtl_sdr_analyzer/web/static/amstech-ui/logo/avatar.svg +1 -0
  65. rtl_sdr_analyzer/web/static/amstech-ui/logo/favicon.svg +1 -0
  66. rtl_sdr_analyzer/web/static/amstech-ui/logo/marca-completa.svg +1 -0
  67. rtl_sdr_analyzer/web/static/amstech-ui/logo/sello-en.svg +1 -0
  68. rtl_sdr_analyzer/web/static/amstech-ui/logo/sello-noche.svg +1 -0
  69. rtl_sdr_analyzer/web/static/amstech-ui/logo/sello.svg +1 -0
  70. rtl_sdr_analyzer/web/static/amstech-ui/logo/thor-blanco.svg +1 -0
  71. rtl_sdr_analyzer/web/static/amstech-ui/logo/thor-noche.svg +1 -0
  72. rtl_sdr_analyzer/web/static/amstech-ui/logo/thor-plano.svg +1 -0
  73. rtl_sdr_analyzer/web/static/amstech-ui/logo/thor.svg +1 -0
  74. rtl_sdr_analyzer/web/static/amstech-ui/tokens.css +161 -0
  75. rtl_sdr_analyzer/web/static/css/studio.css +1353 -0
  76. rtl_sdr_analyzer/web/static/img/emblem.svg +22 -0
  77. rtl_sdr_analyzer/web/static/img/logo.svg +34 -0
  78. rtl_sdr_analyzer/web/static/index.html +574 -0
  79. rtl_sdr_analyzer/web/static/js/api.js +63 -0
  80. rtl_sdr_analyzer/web/static/js/i18n.js +311 -0
  81. rtl_sdr_analyzer/web/static/js/main.js +1248 -0
  82. rtl_sdr_analyzer/web/static/js/spectrum.js +509 -0
  83. rtl_sdr_analyzer/web/static/js/sweep.js +203 -0
  84. rtl_sdr_analyzer/web/static/js/theme-init.js +10 -0
  85. rtl_sdr_analyzer/web/static/js/waterfall.js +201 -0
  86. rtl_sdr_analyzer/web/ws.py +175 -0
  87. rtl_sdr_analyzer-3.0.0b1.dist-info/METADATA +235 -0
  88. rtl_sdr_analyzer-3.0.0b1.dist-info/RECORD +92 -0
  89. rtl_sdr_analyzer-3.0.0b1.dist-info/WHEEL +5 -0
  90. rtl_sdr_analyzer-3.0.0b1.dist-info/entry_points.txt +2 -0
  91. rtl_sdr_analyzer-3.0.0b1.dist-info/licenses/LICENSE +21 -0
  92. rtl_sdr_analyzer-3.0.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3 @@
1
+ """RTL-SDR Analyzer by AMSTech."""
2
+
3
+ __version__ = "3.0.0b1"
@@ -0,0 +1,6 @@
1
+ """Entry point for `python -m rtl_sdr_analyzer`."""
2
+
3
+ from rtl_sdr_analyzer.cli.app import app
4
+
5
+ if __name__ == "__main__":
6
+ app()
File without changes
@@ -0,0 +1,588 @@
1
+ """Typer CLI application for RTL-SDR Analyzer (AMSTech)."""
2
+
3
+ import logging
4
+ import sys
5
+ import threading
6
+ import webbrowser
7
+ from pathlib import Path
8
+
9
+ import typer
10
+ import uvicorn
11
+ from rich import box
12
+ from rich.console import Console
13
+ from rich.panel import Panel
14
+ from rich.progress import Progress, SpinnerColumn, TextColumn
15
+ from rich.table import Table
16
+
17
+ from rtl_sdr_analyzer import __version__
18
+ from rtl_sdr_analyzer.cli.config_overrides import build_cli_overrides
19
+ from rtl_sdr_analyzer.config.loader import load_settings
20
+ from rtl_sdr_analyzer.config.models import SourceMode
21
+ from rtl_sdr_analyzer.engine.event_bus import EventBus
22
+ from rtl_sdr_analyzer.engine.spectrum_engine import SpectrumEngine
23
+ from rtl_sdr_analyzer.engine.sweeper import FrequencySweeper, SweepConfig, SweepProgress
24
+ from rtl_sdr_analyzer.exporters.csv_exporter import CsvExporter
25
+ from rtl_sdr_analyzer.exporters.json_exporter import JsonExporter
26
+ from rtl_sdr_analyzer.logging_config import setup_logging
27
+ from rtl_sdr_analyzer.recording.recorder import IQRecorder
28
+ from rtl_sdr_analyzer.sources.base import SDRSourceError
29
+ from rtl_sdr_analyzer.sources.factory import create_source
30
+ from rtl_sdr_analyzer.sources.usb import get_usb_diagnostics
31
+ from rtl_sdr_analyzer.storage.database import EventStore
32
+ from rtl_sdr_analyzer.storage.stats import (
33
+ AMS_BRAND,
34
+ AMS_LINE,
35
+ AMS_MUTED,
36
+ AMS_OK,
37
+ AMS_TEXT,
38
+ AMS_THOR,
39
+ AMS_YELLOW,
40
+ StatsDashboard,
41
+ )
42
+ from rtl_sdr_analyzer.visualization.headless import HeadlessRunner
43
+ from rtl_sdr_analyzer.web.app import create_app
44
+
45
+ logger = logging.getLogger(__name__)
46
+ console = Console()
47
+
48
+ app = typer.Typer(
49
+ name="rtl-sdr-analyzer",
50
+ help="Real-time RF spectrum analyzer, signal detector, and wideband sweeper by AMSTech.",
51
+ no_args_is_help=False,
52
+ )
53
+
54
+ _config_option = typer.Option(None, "--config", "-c", help="Path to YAML configuration file")
55
+ _log_level_option = typer.Option(
56
+ "INFO", "--log-level", help="Logging level (DEBUG, INFO, WARNING, ERROR)"
57
+ )
58
+ _log_format_option = typer.Option("text", "--log-format", help="Log format: text or json")
59
+
60
+
61
+ def _version_callback(value: bool) -> None:
62
+ if value:
63
+ typer.echo(f"rtl-sdr-analyzer {__version__} (AMSTech)")
64
+ raise typer.Exit(0)
65
+
66
+
67
+ def _attach_exporter(
68
+ event_bus: EventBus,
69
+ export_format: str | None,
70
+ export_path: Path | None,
71
+ ) -> CsvExporter | JsonExporter | None:
72
+ if export_format and not export_path:
73
+ typer.echo("--export-path is required when --export-format is set", err=True)
74
+ raise typer.Exit(1)
75
+ if export_path and not export_format:
76
+ typer.echo("--export-format is required when --export-path is set", err=True)
77
+ raise typer.Exit(1)
78
+ if not export_format or not export_path:
79
+ return None
80
+ fmt = export_format.lower()
81
+ if fmt == "csv":
82
+ exporter: CsvExporter | JsonExporter = CsvExporter(output_path=export_path)
83
+ elif fmt == "json":
84
+ exporter = JsonExporter(output_path=export_path)
85
+ else:
86
+ typer.echo(f"Unknown export format: {export_format}", err=True)
87
+ raise typer.Exit(1)
88
+ event_bus.subscribe(exporter.export)
89
+ return exporter
90
+
91
+
92
+ def _launch_studio(
93
+ *,
94
+ config: Path | None = None,
95
+ source: SourceMode | None = None,
96
+ device: int | None = None,
97
+ lib_path: str | None = None,
98
+ replay_path: Path | None = None,
99
+ host: str | None = None,
100
+ port: int | None = None,
101
+ tcp_host: str | None = None,
102
+ tcp_port: int | None = None,
103
+ freq: float | None = None,
104
+ sample_rate: float | None = None,
105
+ fft_size: int | None = None,
106
+ gain: float | None = None,
107
+ db_path: Path | None = None,
108
+ open_browser: bool = False,
109
+ log_level: str = "INFO",
110
+ log_format: str = "text",
111
+ ) -> None:
112
+ setup_logging(level=log_level, json_format=(log_format == "json"))
113
+ overrides = build_cli_overrides(
114
+ source=source,
115
+ device=device,
116
+ lib_path=lib_path,
117
+ replay_path=str(replay_path) if replay_path else None,
118
+ web_host=host,
119
+ web_port=port,
120
+ tcp_host=tcp_host,
121
+ tcp_port=tcp_port,
122
+ freq=freq,
123
+ sample_rate=sample_rate,
124
+ fft_size=fft_size,
125
+ gain=gain,
126
+ db_path=str(db_path) if db_path else None,
127
+ )
128
+ settings = load_settings(config_path=config, cli_overrides=overrides)
129
+ store = EventStore(settings.storage.db_path) if settings.storage.db_path else None
130
+ engine = SpectrumEngine(settings=settings, store=store)
131
+ web_app = create_app(engine=engine, store=store, settings=settings)
132
+
133
+ url = f"http://{settings.web.host}:{settings.web.port}"
134
+ console.print(
135
+ Panel.fit(
136
+ f"[{AMS_TEXT}]Studio:[/{AMS_TEXT}] [bold {AMS_THOR}]{url}[/bold {AMS_THOR}]\n"
137
+ f"[{AMS_TEXT}]Source:[/{AMS_TEXT}] [bold {AMS_YELLOW}]{settings.source.mode}[/bold {AMS_YELLOW}] "
138
+ f"[{AMS_TEXT}]Center:[/{AMS_TEXT}] [bold {AMS_OK}]{settings.receiver.frequency / 1e6:.3f} MHz[/bold {AMS_OK}] "
139
+ f"[{AMS_TEXT}]Rate:[/{AMS_TEXT}] [{AMS_MUTED}]{settings.receiver.sample_rate / 1e6:.3f} MSPS[/{AMS_MUTED}]",
140
+ title=f"[bold {AMS_BRAND}]AMSTech · rtl-sdr-analyzer v{__version__}[/bold {AMS_BRAND}]",
141
+ border_style=AMS_BRAND,
142
+ box=box.ROUNDED,
143
+ )
144
+ )
145
+
146
+ if open_browser:
147
+ threading.Timer(0.9, lambda: webbrowser.open(url)).start()
148
+
149
+ uvicorn.run(
150
+ web_app,
151
+ host=settings.web.host,
152
+ port=settings.web.port,
153
+ log_level=log_level.lower(),
154
+ )
155
+
156
+
157
+ @app.callback(invoke_without_command=True)
158
+ def main_callback(
159
+ ctx: typer.Context,
160
+ version: bool = typer.Option(
161
+ False,
162
+ "--version",
163
+ "-V",
164
+ callback=_version_callback,
165
+ is_eager=True,
166
+ help="Show version and exit",
167
+ ),
168
+ ) -> None:
169
+ """Launch the AMSTech Web Studio when invoked without a subcommand."""
170
+ if ctx.invoked_subcommand is None:
171
+ # A double-clicked standalone build has no terminal to read a URL from: open it.
172
+ _launch_studio(open_browser=bool(getattr(sys, "frozen", False)))
173
+
174
+
175
+ @app.command()
176
+ def serve(
177
+ config: Path | None = _config_option,
178
+ source: SourceMode | None = typer.Option(
179
+ None, "--source", help="RF source: auto, usb, rtl_tcp, simulated, file"
180
+ ),
181
+ device: int | None = typer.Option(None, "--device", help="USB RTL-SDR device index"),
182
+ lib_path: str | None = typer.Option(
183
+ None, "--lib-path", help="Path to librtlsdr shared library"
184
+ ),
185
+ replay_path: Path | None = typer.Option(
186
+ None, "--replay", help="IQ file path for file replay mode"
187
+ ),
188
+ host: str | None = typer.Option(None, "--host", help="Web server bind host"),
189
+ port: int | None = typer.Option(None, "--port", help="Web server port"),
190
+ tcp_host: str | None = typer.Option(None, "--tcp-host", help="RTL-TCP server host"),
191
+ tcp_port: int | None = typer.Option(None, "--tcp-port", help="RTL-TCP server port"),
192
+ freq: float | None = typer.Option(None, "--freq", help="Center frequency in Hz"),
193
+ sample_rate: float | None = typer.Option(None, "--sample-rate", help="Sample rate in Hz"),
194
+ fft_size: int | None = typer.Option(None, "--fft-size", help="FFT size (power of 2)"),
195
+ gain: float | None = typer.Option(None, "--gain", help="Manual RF gain in dB"),
196
+ db_path: Path | None = typer.Option(None, "--db-path", help="SQLite database path"),
197
+ open_browser: bool = typer.Option(False, "--open", help="Open Web Studio in browser"),
198
+ log_level: str = _log_level_option,
199
+ log_format: str = _log_format_option,
200
+ ) -> None:
201
+ """Start the local AMSTech Web Studio (spectrum, waterfall, sweep, events)."""
202
+ _launch_studio(
203
+ config=config,
204
+ source=source,
205
+ device=device,
206
+ lib_path=lib_path,
207
+ replay_path=replay_path,
208
+ host=host,
209
+ port=port,
210
+ tcp_host=tcp_host,
211
+ tcp_port=tcp_port,
212
+ freq=freq,
213
+ sample_rate=sample_rate,
214
+ fft_size=fft_size,
215
+ gain=gain,
216
+ db_path=db_path,
217
+ open_browser=open_browser,
218
+ log_level=log_level,
219
+ log_format=log_format,
220
+ )
221
+
222
+
223
+ @app.command()
224
+ def devices(
225
+ lib_path: str | None = typer.Option(None, "--lib-path", help="Optional path to librtlsdr"),
226
+ ) -> None:
227
+ """List attached USB RTL-SDR dongles and librtlsdr library status."""
228
+ diag = get_usb_diagnostics(lib_path)
229
+ lib_status = (
230
+ f"[{AMS_OK}]{diag['library_path']}[/{AMS_OK}]"
231
+ if diag["library_found"]
232
+ else f"[{AMS_YELLOW}]Not found[/{AMS_YELLOW}] ({diag['message']})"
233
+ )
234
+ console.print(f"[{AMS_TEXT}]librtlsdr:[/{AMS_TEXT}] {lib_status}")
235
+
236
+ devs = diag["devices"]
237
+ if not devs:
238
+ console.print(f"[{AMS_MUTED}]No USB RTL-SDR devices detected.[/{AMS_MUTED}]")
239
+ return
240
+
241
+ table = Table(
242
+ title=f"[bold {AMS_BRAND}]Detected USB RTL-SDR Devices[/bold {AMS_BRAND}]",
243
+ box=box.ROUNDED,
244
+ border_style=AMS_LINE,
245
+ header_style=f"bold {AMS_THOR}",
246
+ )
247
+ table.add_column("Index", style=AMS_THOR, justify="right")
248
+ table.add_column("Name", style=AMS_TEXT)
249
+ table.add_column("Manufacturer", style=AMS_MUTED)
250
+ table.add_column("Product", style=AMS_MUTED)
251
+ table.add_column("Serial", style=AMS_YELLOW)
252
+
253
+ for d in devs:
254
+ table.add_row(
255
+ str(d["index"]),
256
+ str(d["name"]),
257
+ str(d.get("manufacturer") or "—"),
258
+ str(d.get("product") or "—"),
259
+ str(d.get("serial") or "—"),
260
+ )
261
+ console.print(table)
262
+
263
+
264
+ @app.command()
265
+ def analyze(
266
+ config: Path | None = _config_option,
267
+ source: SourceMode | None = typer.Option(
268
+ None, "--source", help="RF source: auto, usb, rtl_tcp, simulated, file"
269
+ ),
270
+ device: int | None = typer.Option(None, "--device", help="USB RTL-SDR device index"),
271
+ lib_path: str | None = typer.Option(None, "--lib-path", help="Path to librtlsdr"),
272
+ host: str | None = typer.Option(None, "--host", help="RTL-TCP server host"),
273
+ port: int | None = typer.Option(None, "--port", help="RTL-TCP server port"),
274
+ freq: float | None = typer.Option(None, "--freq", help="Center frequency in Hz"),
275
+ sample_rate: float | None = typer.Option(None, "--sample-rate", help="Sample rate in Hz"),
276
+ fft_size: int | None = typer.Option(None, "--fft-size", help="FFT size"),
277
+ gain: float | None = typer.Option(None, "--gain", help="Manual RF gain in dB"),
278
+ power_threshold: float | None = typer.Option(
279
+ None, "--power-threshold", help="Power threshold in dBFS"
280
+ ),
281
+ snr_threshold: float | None = typer.Option(None, "--snr-threshold", help="Minimum SNR in dB"),
282
+ bandwidth_threshold: float | None = typer.Option(
283
+ None, "--bandwidth-threshold", help="Minimum bandwidth in Hz"
284
+ ),
285
+ z_score_threshold: float | None = typer.Option(
286
+ None, "--z-score-threshold", help="Z-score threshold"
287
+ ),
288
+ detection_window: int | None = typer.Option(
289
+ None, "--detection-window", help="Baseline window frames"
290
+ ),
291
+ min_duration: float | None = typer.Option(
292
+ None, "--min-duration", help="Minimum event duration in seconds"
293
+ ),
294
+ test_mode: bool | None = typer.Option(
295
+ None, "--test-mode", help="Enable sensitive any-criterion detection"
296
+ ),
297
+ max_frames: int | None = typer.Option(
298
+ None, "--max-frames", help="Stop after N frames (optional)"
299
+ ),
300
+ export_format: str | None = typer.Option(
301
+ None, "--export-format", help="Event export format: csv or json"
302
+ ),
303
+ export_path: Path | None = typer.Option(None, "--export-path", help="Path for exported events"),
304
+ db_path: Path | None = typer.Option(None, "--db-path", help="SQLite database path"),
305
+ log_level: str = _log_level_option,
306
+ log_format: str = _log_format_option,
307
+ ) -> None:
308
+ """Run headless real-time spectrum analysis and signal detection."""
309
+ setup_logging(level=log_level, json_format=(log_format == "json"))
310
+
311
+ overrides = build_cli_overrides(
312
+ source=source,
313
+ device=device,
314
+ lib_path=lib_path,
315
+ host=host,
316
+ port=port,
317
+ freq=freq,
318
+ sample_rate=sample_rate,
319
+ fft_size=fft_size,
320
+ gain=gain,
321
+ power_threshold=power_threshold,
322
+ snr_threshold=snr_threshold,
323
+ bandwidth_threshold=bandwidth_threshold,
324
+ z_score_threshold=z_score_threshold,
325
+ detection_window=detection_window,
326
+ min_duration=min_duration,
327
+ test_mode=test_mode,
328
+ db_path=str(db_path) if db_path else None,
329
+ )
330
+ settings = load_settings(config_path=config, cli_overrides=overrides)
331
+ allow_sim = settings.source.mode in ("auto", "simulated")
332
+
333
+ try:
334
+ rf_source = create_source(settings, allow_simulated_fallback=allow_sim)
335
+ except SDRSourceError as exc:
336
+ typer.echo(f"Source error: {exc}", err=True)
337
+ raise typer.Exit(1)
338
+
339
+ event_bus = EventBus()
340
+ exporter = _attach_exporter(event_bus, export_format, export_path)
341
+ store = EventStore(settings.storage.db_path) if settings.storage.db_path else None
342
+ engine = SpectrumEngine(settings=settings, source=rf_source, store=store, event_bus=event_bus)
343
+
344
+ runner = HeadlessRunner(engine=engine, max_frames=max_frames, console=console)
345
+ try:
346
+ runner.run()
347
+ finally:
348
+ if exporter is not None:
349
+ exporter.close()
350
+
351
+
352
+ @app.command()
353
+ def record(
354
+ output: Path = typer.Argument(..., help="Output file path (.raw, .cu8, or .npz)"),
355
+ duration: float = typer.Option(10.0, "--duration", help="Recording duration in seconds"),
356
+ format: str = typer.Option("raw", "--format", help="Output format: raw or numpy"),
357
+ config: Path | None = _config_option,
358
+ source: SourceMode | None = typer.Option(
359
+ None, "--source", help="RF source: auto, usb, rtl_tcp, simulated"
360
+ ),
361
+ device: int | None = typer.Option(None, "--device", help="USB device index"),
362
+ lib_path: str | None = typer.Option(None, "--lib-path", help="Path to librtlsdr"),
363
+ host: str | None = typer.Option(None, "--host", help="RTL-TCP host"),
364
+ port: int | None = typer.Option(None, "--port", help="RTL-TCP port"),
365
+ freq: float | None = typer.Option(None, "--freq", help="Center frequency in Hz"),
366
+ sample_rate: float | None = typer.Option(None, "--sample-rate", help="Sample rate in Hz"),
367
+ gain: float | None = typer.Option(None, "--gain", help="Manual RF gain in dB"),
368
+ log_level: str = _log_level_option,
369
+ ) -> None:
370
+ """Record raw IQ samples to a file for offline analysis."""
371
+ setup_logging(level=log_level)
372
+ overrides = build_cli_overrides(
373
+ source=source,
374
+ device=device,
375
+ lib_path=lib_path,
376
+ host=host,
377
+ port=port,
378
+ freq=freq,
379
+ sample_rate=sample_rate,
380
+ gain=gain,
381
+ )
382
+ settings = load_settings(config_path=config, cli_overrides=overrides)
383
+ allow_sim = settings.source.mode == "simulated"
384
+
385
+ try:
386
+ rf_source = create_source(settings, allow_simulated_fallback=allow_sim)
387
+ with (
388
+ rf_source,
389
+ IQRecorder(
390
+ output_path=output,
391
+ format=format,
392
+ sample_rate=settings.receiver.sample_rate,
393
+ center_freq=settings.receiver.frequency,
394
+ gain=settings.receiver.gain,
395
+ ) as recorder,
396
+ ):
397
+ total = recorder.record(rf_source, duration=duration)
398
+ except KeyboardInterrupt:
399
+ logger.info("Recording interrupted.")
400
+ except Exception as exc:
401
+ typer.echo(f"Recording failed: {exc}", err=True)
402
+ raise typer.Exit(1)
403
+
404
+ typer.echo(f"Recording saved to {output} ({total:,} samples)")
405
+
406
+
407
+ @app.command()
408
+ def sweep(
409
+ start_freq: float = typer.Argument(..., help="Start frequency in Hz"),
410
+ end_freq: float = typer.Argument(..., help="End frequency in Hz"),
411
+ step: float | None = typer.Option(
412
+ None, "--step", help="Frequency step in Hz (default 80% of sample rate)"
413
+ ),
414
+ dwell: float = typer.Option(0.35, "--dwell", help="Dwell time per step in seconds"),
415
+ config: Path | None = _config_option,
416
+ source: SourceMode | None = typer.Option(
417
+ None, "--source", help="RF source: auto, usb, rtl_tcp, simulated"
418
+ ),
419
+ device: int | None = typer.Option(None, "--device", help="USB device index"),
420
+ lib_path: str | None = typer.Option(None, "--lib-path", help="Path to librtlsdr"),
421
+ host: str | None = typer.Option(None, "--host", help="RTL-TCP host"),
422
+ port: int | None = typer.Option(None, "--port", help="RTL-TCP port"),
423
+ sample_rate: float | None = typer.Option(None, "--sample-rate", help="Sample rate in Hz"),
424
+ fft_size: int | None = typer.Option(None, "--fft-size", help="FFT size"),
425
+ gain: float | None = typer.Option(None, "--gain", help="Manual RF gain in dB"),
426
+ power_threshold: float | None = typer.Option(
427
+ None, "--power-threshold", help="Peak power threshold in dBFS"
428
+ ),
429
+ snr_threshold: float | None = typer.Option(None, "--snr-threshold", help="Minimum SNR in dB"),
430
+ export_format: str | None = typer.Option(None, "--export-format", help="csv or json"),
431
+ export_path: Path | None = typer.Option(None, "--export-path", help="Export file path"),
432
+ db_path: Path | None = typer.Option(None, "--db-path", help="SQLite database path"),
433
+ log_level: str = _log_level_option,
434
+ ) -> None:
435
+ """Sweep a frequency range and report detected spectral peaks."""
436
+ setup_logging(level=log_level)
437
+ overrides = build_cli_overrides(
438
+ source=source,
439
+ device=device,
440
+ lib_path=lib_path,
441
+ host=host,
442
+ port=port,
443
+ sample_rate=sample_rate,
444
+ fft_size=fft_size,
445
+ gain=gain,
446
+ power_threshold=power_threshold,
447
+ snr_threshold=snr_threshold,
448
+ db_path=str(db_path) if db_path else None,
449
+ )
450
+ settings = load_settings(config_path=config, cli_overrides=overrides)
451
+ allow_sim = settings.source.mode in ("auto", "simulated")
452
+
453
+ event_bus = EventBus()
454
+ exporter = _attach_exporter(event_bus, export_format, export_path)
455
+ store: EventStore | None = None
456
+ if settings.storage.db_path:
457
+ store = EventStore(settings.storage.db_path)
458
+ store.init_schema()
459
+ store.start_session(
460
+ center_freq_mhz=0.5 * (start_freq + end_freq) / 1e6,
461
+ sample_rate_hz=settings.receiver.sample_rate,
462
+ )
463
+
464
+ try:
465
+ rf_source = create_source(settings, allow_simulated_fallback=allow_sim)
466
+ sweeper = FrequencySweeper(event_bus=event_bus, store=store)
467
+ sweep_cfg = SweepConfig(
468
+ start_freq_hz=start_freq,
469
+ end_freq_hz=end_freq,
470
+ step_hz=step,
471
+ dwell_seconds=dwell,
472
+ fft_size=min(8192, max(256, settings.receiver.fft_size)),
473
+ sample_rate_hz=settings.receiver.sample_rate,
474
+ power_threshold_db=settings.detector.power_threshold,
475
+ snr_threshold_db=settings.detector.snr_threshold,
476
+ )
477
+
478
+ with (
479
+ rf_source,
480
+ Progress(
481
+ SpinnerColumn(),
482
+ TextColumn("[progress.description]{task.description}"),
483
+ console=console,
484
+ transient=True,
485
+ ) as progress,
486
+ ):
487
+ task_id = progress.add_task("Sweeping…", total=None)
488
+
489
+ def _on_prog(p: SweepProgress) -> None:
490
+ progress.update(
491
+ task_id,
492
+ description=f"Sweeping {p.current_freq_mhz:.2f} MHz ({p.step_index}/{p.total_steps}) · {p.peaks_found} peaks",
493
+ )
494
+
495
+ result = sweeper.run(rf_source, sweep_cfg, on_progress=_on_prog)
496
+ except Exception as exc:
497
+ typer.echo(f"Sweep failed: {exc}", err=True)
498
+ raise typer.Exit(1)
499
+ finally:
500
+ if store is not None:
501
+ store.end_session()
502
+ if exporter is not None:
503
+ exporter.close()
504
+
505
+ console.print(
506
+ f"[{AMS_TEXT}]Sweep complete:[/{AMS_TEXT}] "
507
+ f"[{AMS_THOR}]{result.start_freq_mhz:.2f}–{result.end_freq_mhz:.2f} MHz[/{AMS_THOR}] "
508
+ f"noise=[{AMS_MUTED}]{result.noise_floor_db:.1f} dBFS[/{AMS_MUTED}] "
509
+ f"peaks=[{AMS_OK}]{len(result.peaks)}[/{AMS_OK}] "
510
+ f"time=[{AMS_MUTED}]{result.duration_s:.2f}s[/{AMS_MUTED}]"
511
+ )
512
+ if result.peaks:
513
+ table = Table(
514
+ box=box.ROUNDED,
515
+ border_style=AMS_LINE,
516
+ header_style=f"bold {AMS_THOR}",
517
+ )
518
+ table.add_column("Freq (MHz)", style=AMS_THOR, justify="right")
519
+ table.add_column("Power (dBFS)", style=AMS_YELLOW, justify="right")
520
+ table.add_column("SNR (dB)", style=AMS_OK, justify="right")
521
+ table.add_column("BW (kHz)", style=AMS_MUTED, justify="right")
522
+ for pk in result.peaks[:20]:
523
+ table.add_row(
524
+ f"{pk.frequency_mhz:.4f}",
525
+ f"{pk.power_db:.1f}",
526
+ f"+{pk.snr_db:.1f}",
527
+ f"{pk.bandwidth_hz / 1e3:.1f}",
528
+ )
529
+ console.print(table)
530
+
531
+
532
+ @app.command(name="stats")
533
+ def stats(
534
+ db_path: Path = typer.Argument(Path("rtl_sdr_analyzer.db"), help="Path to SQLite database"),
535
+ top_freqs: bool = typer.Option(True, "--top-freqs", help="Show top frequencies"),
536
+ hourly: bool = typer.Option(True, "--hourly", help="Show hourly activity"),
537
+ recent: int = typer.Option(10, "--recent", help="Number of recent events to show"),
538
+ export_csv: Path | None = typer.Option(None, "--export-csv", help="Export events to CSV"),
539
+ since_hours: int | None = typer.Option(None, "--since-hours", help="Filter events by hours"),
540
+ ) -> None:
541
+ """Display AMSTech statistics dashboard for detection events."""
542
+ if not db_path.exists():
543
+ typer.echo(f"Database not found: {db_path}", err=True)
544
+ raise typer.Exit(1)
545
+
546
+ dashboard = StatsDashboard(db_path)
547
+ dashboard.show_summary()
548
+ if top_freqs:
549
+ dashboard.show_top_frequencies()
550
+ if hourly:
551
+ dashboard.show_hourly_activity()
552
+ if recent > 0:
553
+ dashboard.show_recent_events(limit=recent)
554
+ if export_csv:
555
+ dashboard.export_csv(export_csv, since_hours=since_hours)
556
+
557
+
558
+ @app.command(name="config-validate")
559
+ def config_validate(
560
+ config_path: Path = typer.Argument(..., help="Path to YAML configuration file"),
561
+ ) -> None:
562
+ """Validate a configuration file against the Pydantic schema."""
563
+ try:
564
+ settings = load_settings(config_path=config_path)
565
+ typer.echo("Configuration is valid.")
566
+ typer.echo(settings.model_dump_json(indent=2))
567
+ except Exception as exc:
568
+ typer.echo(f"Configuration error: {exc}", err=True)
569
+ raise typer.Exit(1)
570
+
571
+
572
+ @app.command(name="config-show")
573
+ def config_show(
574
+ config: Path | None = _config_option,
575
+ format: str = typer.Option("yaml", "--format", help="Output format: yaml or json"),
576
+ ) -> None:
577
+ """Show the resolved configuration (defaults + env + file + CLI)."""
578
+ settings = load_settings(config_path=config)
579
+ if format.lower() == "json":
580
+ typer.echo(settings.model_dump_json(indent=2))
581
+ else:
582
+ import yaml
583
+
584
+ typer.echo(yaml.safe_dump(settings.model_dump(), sort_keys=False))
585
+
586
+
587
+ if __name__ == "__main__":
588
+ app()
@@ -0,0 +1,42 @@
1
+ """Map flat CLI argument names to nested configuration paths."""
2
+
3
+ from typing import Any
4
+
5
+ CLI_TO_CONFIG_PATH: dict[str, str] = {
6
+ "source": "source.mode",
7
+ "device": "source.device_index",
8
+ "lib_path": "source.library_path",
9
+ "replay_path": "source.replay_path",
10
+ "host": "rtl_tcp.host",
11
+ "tcp_host": "rtl_tcp.host",
12
+ "port": "rtl_tcp.port",
13
+ "tcp_port": "rtl_tcp.port",
14
+ "freq": "receiver.frequency",
15
+ "sample_rate": "receiver.sample_rate",
16
+ "fft_size": "receiver.fft_size",
17
+ "gain": "receiver.gain",
18
+ "ppm": "receiver.ppm",
19
+ "direct_sampling": "receiver.direct_sampling",
20
+ "power_threshold": "detector.power_threshold",
21
+ "snr_threshold": "detector.snr_threshold",
22
+ "bandwidth_threshold": "detector.bandwidth_threshold",
23
+ "z_score_threshold": "detector.z_score_threshold",
24
+ "detection_window": "detector.detection_window",
25
+ "min_duration": "detector.min_duration",
26
+ "test_mode": "detector.test_mode",
27
+ "waterfall_length": "display.waterfall_length",
28
+ "target_fps": "display.target_fps",
29
+ "web_host": "web.host",
30
+ "web_port": "web.port",
31
+ "db_path": "storage.db_path",
32
+ "recordings_dir": "storage.recordings_dir",
33
+ }
34
+
35
+
36
+ def build_cli_overrides(**kwargs: Any) -> dict[str, Any]:
37
+ """Build a dot-notation override dictionary from flat CLI kwargs."""
38
+ overrides: dict[str, Any] = {}
39
+ for key, value in kwargs.items():
40
+ if value is not None and key in CLI_TO_CONFIG_PATH:
41
+ overrides[CLI_TO_CONFIG_PATH[key]] = value
42
+ return overrides
File without changes