bandsaunter/bandsaunter/tui.py
The Dust Council 2b653c2c3e Read the APRS channel: who is out there, and what they said
A third section, alongside the aircraft and the weather sensors, and for the
same reason as both: a scan stops on a signal, records it and moves on, while
APRS is a two-second transmission every few minutes from a hundred stations
sharing one frequency.  A sweep catches whichever happened to key up as it
passed.  `bandsaunter aprs` parks on the channel and catches all of them;
`bandsaunter packets` reads a log back.

Four layers, three of them new.

The link layer was already here, opportunistically, in the generic decoder --
a correlator, NRZI, HDLC and a checksum, run on whatever a scan happened to
record.  It is now a receiver.  What had to change is the state that survives
a block boundary: the tail of the audio so the correlators see no edge, the
phase of the sampling loop so a bit is not lost where one block meets the
next, the tone the line was last at, and the bits themselves.  A packet is
most of a second and a block is about one, so frames straddling the boundary
are not an edge case, they are most of them.

Above that, the APRS information field, which is not one format but about
twenty, chosen by the first character and accreted over thirty years.
Positions uncompressed and compressed; Mic-E, which every Kenwood and Yaesu
mobile sends and which hides the latitude inside the destination callsign
because in 1995 those six bytes were carrying the word "APRS" and nothing
else; weather with a position and without; messages, acknowledgements,
rejections and bulletins; objects and items; status; telemetry; third-party
traffic, credited to whoever originally sent it rather than to the gateway.
Course and speed, altitude, power and antenna height, range and the precision
extension, all of which ride in the comment.  Every one has a writer beside
its reader, so a packet goes in and the same packet comes out.

Above that the section: a registry of who is out there and what each last
said of each kind, distances and bearings from --at, a log keeping the whole
frame under whatever was made of it, a spreadsheet, a map, and a channel full
of stations that are not there for --simulate.

One rule is worth naming because it is the difference between a decoder and a
liar.  A packet whose format does not match what its first character promised
comes back as unparsed with its text intact.  Thirteen characters of a
*malformed* uncompressed position are perfectly good base-91, so trying one
format and falling back to the other does not fail on a bad packet -- it
succeeds, as a confident and completely different place, usually a thousand
miles away.  The specification makes the two unambiguous, a leading digit
always meaning uncompressed, and the rule is read rather than guessed at.

Two faults found by building it, both by measurement rather than by reading
the code again.  The framer handed back frames it had already reported,
because it trimmed its buffer to before them rather than after -- every packet
counted twice, for ever, which only shows up once the same signal is read
across more than one block.  And the invented channel truncated a
transmission at the end of the block it began in rather than carrying the
remainder over, which was invisible for as long as the simulated clock
advanced in exact seconds and put every transmission at a block boundary; the
moment it was paced against a real clock, nothing decoded at all.

204 new tests against seven deliberately broken builds, one of which survived
until a test was written for the case it actually breaks.  Full suite 2597
passed.  Built as 2026-09-20_02.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
2026-09-20 19:36:30 -07:00

1585 lines
68 KiB
Python

"""The in-application interface: configure everything without command-line flags.
Every setting the command line accepts is reachable here, because both are
generated from the same table in :mod:`bandsaunter.settings`. Each one carries
its own help, so nothing has to be looked up elsewhere.
"""
from __future__ import annotations
from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm, Prompt
from rich.table import Table
from rich.text import Text
from . import bandplan, settings as st
from .bandplan import CATEGORIES, PRESETS, BandPreset, fmt_hz, in_category, search
from .config import (DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_PATH,
DEFAULT_OUTPUT_DIR, ScanConfig,
delete_profile, list_profiles, load_config, save_config,
save_default)
from .ranges import RangeError, ScanRange, parse_frequency
__all__ = ["run_tui", "show_ranges", "settings_menu", "help_screen",
"aircraft_menu", "weather_menu", "aprs_menu", "first_run_setup",
"TUIAbort"]
_BACK = ("", "b", "back", "q", "quit", "x")
def _rule(console: Console, text: str) -> None:
console.print()
console.rule(f"[bold]{text}[/bold]", style="blue")
class TUIAbort(Exception):
"""Input ended or the user interrupted; unwind out of the menus."""
def _ask(console: Console, prompt: str, default: str = "") -> str:
try:
return Prompt.ask(prompt, default=default, show_default=bool(default))
except (EOFError, KeyboardInterrupt):
# Returning an empty string here would send the menu round again and,
# with no input left to read, round forever.
raise TUIAbort() from None
def _confirm(prompt: str, default: bool = False) -> bool:
"""Yes/no that treats a closed input as "no" rather than crashing."""
try:
return Confirm.ask(prompt, default=default)
except (EOFError, KeyboardInterrupt):
return False
# ---------------------------------------------------------------------------
# Ranges
# ---------------------------------------------------------------------------
def show_ranges(console: Console, cfg: ScanConfig) -> None:
if not cfg.ranges:
console.print("[yellow]No frequency ranges selected yet.[/yellow] "
"[grey62]Add some with 1 or 2.[/grey62]")
return
t = Table(box=None, header_style="bold", pad_edge=False)
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("label")
t.add_column("from", justify="right")
t.add_column("to", justify="right")
t.add_column("span", justify="right", style="grey62")
t.add_column("mode", justify="center")
t.add_column("on", justify="center")
total = 0.0
for i, r in enumerate(cfg.ranges, 1):
if r.enabled:
total += r.span
t.add_row(str(i), r.label, fmt_hz(r.start), fmt_hz(r.stop),
fmt_hz(r.span), r.mode,
"[green]yes[/green]" if r.enabled else "[red]no[/red]")
console.print(t)
console.print(f"[grey62]{len(cfg.ranges)} range(s), {fmt_hz(total)} of "
f"spectrum enabled[/grey62]")
def add_manual_ranges(console: Console, cfg: ScanConfig) -> None:
_rule(console, "add frequency ranges")
console.print(
"Enter a start and end frequency for each range. Units may be "
"written [cyan]144M[/cyan], [cyan]144 MHz[/cyan], "
"[cyan]144000k[/cyan] or plain Hz; a bare number under 10000 is read "
"as MHz.\nLeave the start blank when you are done. There is no limit "
"on how many ranges you add.\n")
added = 0
while True:
start_s = _ask(console, f" [bold]start[/bold] of range "
f"{len(cfg.ranges) + 1}")
if not start_s.strip():
break
try:
start = parse_frequency(start_s)
except RangeError as exc:
console.print(f" [red]{exc}[/red]")
continue
end_s = _ask(console, " [bold]end[/bold] of range")
try:
stop = parse_frequency(end_s) if end_s.strip() else start
except RangeError as exc:
console.print(f" [red]{exc}[/red]")
continue
r = ScanRange(start, stop)
covering = bandplan.presets_covering(0.5 * (r.start + r.stop))
if covering:
best = min(covering, key=lambda p: p.span)
r.label = f"{fmt_hz(r.start)}-{fmt_hz(r.stop)} ({best.name})"
console.print(f" [grey62]that falls in: {best.name} — default "
f"mode {best.mode}[/grey62]")
mode = _ask(console, " mode [grey62](auto/nfm/wfm/am/usb/lsb/cw/raw)"
"[/grey62]", "auto").lower()
r.mode = mode if mode in ("auto", "nfm", "wfm", "am", "usb", "lsb",
"cw", "raw") else "auto"
cfg.ranges.append(r)
added += 1
console.print(f" [green]added[/green] {r.describe()}\n")
if added:
console.print(f"[green]{added} range(s) added.[/green]")
def choose_presets(console: Console, cfg: ScanConfig) -> None:
while True:
_rule(console, "US band plan")
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("category")
t.add_column("presets", justify="right", style="grey62")
for i, cat in enumerate(CATEGORIES, 1):
t.add_row(str(i), cat, str(len(in_category(cat))))
console.print(t)
console.print("[grey62]Enter a category number, a search term, or "
"blank to go back.[/grey62]")
answer = _ask(console, " category or search").strip()
if not answer:
return
if answer.isdigit() and 1 <= int(answer) <= len(CATEGORIES):
presets = in_category(CATEGORIES[int(answer) - 1])
heading = CATEGORIES[int(answer) - 1]
else:
presets = search(answer)
heading = f"search: {answer!r}"
if not presets:
console.print(f" [yellow]nothing matched {answer!r}[/yellow]")
continue
_pick_from(console, cfg, presets, heading)
def _pick_from(console: Console, cfg: ScanConfig,
presets: list[BandPreset], heading: str) -> None:
_rule(console, heading)
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("name")
t.add_column("range", justify="right")
t.add_column("mode", justify="center")
t.add_column("notes", style="grey62", overflow="fold", max_width=42)
for i, p in enumerate(presets, 1):
extent = (f"{len(p.expand())} ranges" if p.is_group
else f"{fmt_hz(p.start)} - {fmt_hz(p.stop)}")
t.add_row(str(i), p.name, extent, p.mode, p.note)
console.print(t)
console.print("[grey62]Numbers to add ([cyan]1,3,5[/cyan] or "
"[cyan]1-4[/cyan]), [cyan]all[/cyan], or blank to go "
"back.[/grey62]")
answer = _ask(console, " add").strip().lower()
if not answer:
return
chosen = list(presets) if answer == "all" else _expand(answer, presets)
existing = {r.preset_key for r in cfg.ranges if r.preset_key}
added = 0
hf = False
for picked in chosen:
# A preset may stand for a set of others; add what it actually scans.
for p in picked.expand():
if p.key in existing:
continue
cfg.ranges.append(ScanRange.from_preset(p))
existing.add(p.key)
added += 1
hf |= p.needs_direct_sampling
if hf:
console.print(" [yellow]some of these are below 24 MHz — they need "
"direct sampling and an HF antenna.[/yellow]")
console.print(f" [green]added {added} range(s)[/green]")
warn_about_aircraft_bands(console, cfg)
def warn_about_aircraft_bands(console: Console, cfg: ScanConfig) -> None:
"""Say so the moment a band that needs the aircraft mode is chosen.
The band plan lists 1090 MHz because that is where ADS-B is, so picking
it here is the obvious thing to do and the wrong one. It is not refused
-- looking at the spectrum there is a fair thing to want -- but it does
not happen silently, and the menu that does decode it is named.
"""
from . import aircraft as air
warning = air.scanning_aircraft_band(cfg.ranges)
if not warning:
return
console.print(Panel(Text.from_markup(
f"{warning}\n\n"
"Menu [cyan]5[/cyan], [bold]Aircraft (ADS-B)[/bold], listens to it "
"properly and draws where the aircraft went.\n\n"
"[grey62]Scanning it anyway is fine if what you want is the raw "
"spectrum \u2014 turn on 'Save raw IQ' to keep the samples."
"[/grey62]"),
title="[yellow]this band needs the aircraft mode",
border_style="yellow", padding=(0, 1)))
def _expand(answer: str, items: list) -> list:
out = []
for tok in answer.replace(" ", "").split(","):
if not tok:
continue
if "-" in tok:
a, _, b = tok.partition("-")
if a.isdigit() and b.isdigit():
out += [items[i - 1] for i in range(int(a), int(b) + 1)
if 1 <= i <= len(items)]
elif tok.isdigit() and 1 <= int(tok) <= len(items):
out.append(items[int(tok) - 1])
return out
def edit_ranges(console: Console, cfg: ScanConfig) -> None:
while True:
_rule(console, "ranges")
show_ranges(console, cfg)
console.print(
"\n [cyan]a[/cyan] add by hand "
"[cyan]p[/cyan] add from the band plan\n"
" [cyan]r[/cyan] remove "
"[cyan]t[/cyan] toggle on/off\n"
" [cyan]m[/cyan] change mode "
"[cyan]c[/cyan] clear all\n"
" [cyan]b[/cyan] back\n")
choice = _ask(console, " choice", "b").strip().lower()
if choice in _BACK:
return
if choice == "a":
add_manual_ranges(console, cfg)
elif choice == "p":
choose_presets(console, cfg)
elif choice == "c":
if cfg.ranges and _confirm(" remove every range"):
cfg.ranges = []
elif choice in ("r", "t", "m") and cfg.ranges:
which = _ask(console, " which numbers").strip()
picked = _expand(which, list(range(1, len(cfg.ranges) + 1)))
if not picked:
console.print(" [yellow]nothing selected[/yellow]")
continue
if choice == "r":
cfg.ranges = [r for i, r in enumerate(cfg.ranges, 1)
if i not in picked]
elif choice == "t":
for i in picked:
cfg.ranges[i - 1].enabled = not cfg.ranges[i - 1].enabled
else:
mode = _ask(console, " mode", "auto").strip().lower()
for i in picked:
cfg.ranges[i - 1].mode = mode or "auto"
# ---------------------------------------------------------------------------
# Settings
# ---------------------------------------------------------------------------
def _setting_row(setting: st.Setting, cfg: ScanConfig, default: ScanConfig):
value = getattr(cfg, setting.key)
shown = st.format_value(setting, value)
changed = value != getattr(default, setting.key)
return Text(shown, style="bold cyan" if changed else "white"), changed
def _settings_table(console: Console, group: str, cfg: ScanConfig) -> list[st.Setting]:
items = st.in_group(group)
default = ScanConfig()
t = Table(box=None, header_style="bold", pad_edge=False)
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("setting", width=22)
t.add_column("value", width=18)
t.add_column("what it does", style="grey62", overflow="fold")
for i, s in enumerate(items, 1):
value, changed = _setting_row(s, cfg, default)
t.add_row(str(i), s.label + (" *" if changed else ""), value, s.help)
console.print(t)
console.print("[grey62]* differs from the built-in default[/grey62]")
return items
def setting_help(console: Console, setting: st.Setting,
cfg: ScanConfig, default=None) -> None:
default = ScanConfig() if default is None else default
body = [f"[bold]{setting.label}[/bold] [grey62]({setting.key})[/grey62]",
"", setting.help.capitalize() + "."]
if setting.detail:
body += ["", setting.detail]
if setting.guidance and setting.guidance != setting.detail:
body += ["", f"[grey62]{setting.guidance}[/grey62]"]
body.append("")
body.append(f"[grey62]now:[/grey62] "
f"{st.format_value(setting, getattr(cfg, setting.key))}"
f" [grey62]default:[/grey62] "
f"{st.format_value(setting, getattr(default, setting.key))}")
rng = setting.describe_range()
if rng:
body.append(f"[grey62]accepts:[/grey62] {rng}")
if setting.flags:
flags = " ".join(setting.flags)
if setting.off_flags:
flags += " / " + " ".join(setting.off_flags)
body.append(f"[grey62]command line:[/grey62] {flags}")
console.print(Panel(Text.from_markup("\n".join(body)),
border_style="blue", padding=(0, 1)))
def edit_setting(console: Console, setting: st.Setting, cfg: ScanConfig,
default=None, show_help=None) -> bool:
"""Prompt for one value. Returns True if it changed.
``cfg`` is whatever holds the value -- the scan config, or the aircraft
options, which are described by the same kind of table and so can be
edited by the same code. ``default`` is the object the built-in defaults
come from, and ``show_help`` the panel to print above the prompt.
"""
current = getattr(cfg, setting.key)
(show_help or setting_help)(console, setting, cfg)
hint = "yes/no" if setting.kind == "bool" else (
"/".join(setting.choices) if setting.choices else
(setting.example or setting.metavar or "value"))
while True:
raw = _ask(console, f" [bold]{setting.label}[/bold] [grey62]({hint})"
f"[/grey62]", st.format_value(setting, current)
if setting.kind not in ("lockout_list", "accept_list")
else "")
if raw.strip() == "" or raw == st.format_value(setting, current):
return False
if raw.strip().lower() in ("d", "default"):
value = getattr(default if default is not None else ScanConfig(),
setting.key)
else:
try:
value = st.parse_value(setting, raw)
except st.SettingError as exc:
console.print(f" [red]{exc}[/red]")
continue
setattr(cfg, setting.key, value)
errs = [e for e in cfg.validate() if "frequency ranges" not in e]
if errs:
console.print(f" [red]{errs[0]}[/red]")
setattr(cfg, setting.key, current)
continue
console.print(f" [green]{setting.label} = "
f"{st.format_value(setting, value)}[/green]")
return True
def settings_menu(console: Console, cfg: ScanConfig) -> None:
while True:
_rule(console, "settings")
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("group")
t.add_column("settings", justify="right", style="grey62")
for i, g in enumerate(st.GROUPS, 1):
t.add_row(str(i), g, str(len(st.in_group(g))))
console.print(t)
console.print("[grey62]Enter a group number, a search term "
"(e.g. [cyan]hang[/cyan]), or blank to go back."
"[/grey62]")
answer = _ask(console, " group or search").strip()
if not answer:
return
if answer.isdigit() and 1 <= int(answer) <= len(st.GROUPS):
_group_menu(console, cfg, st.GROUPS[int(answer) - 1])
else:
hits = st.search(answer)
if not hits:
console.print(f" [yellow]no setting matches "
f"{answer!r}[/yellow]")
continue
if len(hits) == 1:
edit_setting(console, hits[0], cfg)
else:
_list_menu(console, cfg, hits, f"matching {answer!r}")
def _list_menu(console: Console, cfg: ScanConfig, items: list[st.Setting],
heading: str) -> None:
while True:
_rule(console, heading)
default = ScanConfig()
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("setting", width=22)
t.add_column("value", width=18)
t.add_column("group", style="grey62")
for i, s in enumerate(items, 1):
value, _ = _setting_row(s, cfg, default)
t.add_row(str(i), s.label, value, s.group)
console.print(t)
answer = _ask(console, " number to edit, or blank to go back").strip()
if not answer or not answer.isdigit():
return
idx = int(answer)
if 1 <= idx <= len(items):
edit_setting(console, items[idx - 1], cfg)
def _group_menu(console: Console, cfg: ScanConfig, group: str) -> None:
while True:
_rule(console, group.lower())
items = _settings_table(console, group, cfg)
console.print("[grey62]Number to change it, [cyan]?N[/cyan] for help "
"on one, [cyan]d[/cyan] to reset the group, blank to go "
"back.[/grey62]")
answer = _ask(console, " choice").strip().lower()
if answer in _BACK:
return
if answer == "d":
if _confirm(f" reset every setting in {group}"):
default = ScanConfig()
for s in items:
setattr(cfg, s.key, getattr(default, s.key))
console.print(" [green]reset[/green]")
continue
want_help = answer.startswith("?")
token = answer.lstrip("?").strip()
if not token.isdigit():
console.print(" [yellow]enter a number from the list[/yellow]")
continue
idx = int(token)
if not (1 <= idx <= len(items)):
console.print(" [yellow]no such number[/yellow]")
continue
if want_help:
setting_help(console, items[idx - 1], cfg)
else:
edit_setting(console, items[idx - 1], cfg)
# ---------------------------------------------------------------------------
# Profiles and saved settings
# ---------------------------------------------------------------------------
def profiles_menu(console: Console, cfg: ScanConfig) -> ScanConfig:
while True:
_rule(console, "saved settings")
console.print(f"[grey62]Settings live in {DEFAULT_CONFIG_DIR}[/grey62]")
exists = DEFAULT_CONFIG_PATH.exists()
console.print(" default settings file: "
+ (f"[green]{DEFAULT_CONFIG_PATH}[/green]" if exists
else "[yellow]not saved yet[/yellow]"))
profiles = list_profiles()
if profiles:
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("profile")
t.add_column("ranges", justify="right")
t.add_column("record", justify="right")
t.add_column("hang", justify="right")
for i, p in enumerate(profiles, 1):
try:
other = load_config(str(p))
t.add_row(str(i), p.stem, str(len(other.ranges)),
f"{other.record_seconds:g}s",
f"{other.hang_seconds:g}s")
except Exception:
t.add_row(str(i), p.stem, "[red]unreadable[/red]", "", "")
console.print(t)
else:
console.print(" [grey62]no named profiles yet[/grey62]")
console.print(
"\n [cyan]s[/cyan] save as the default settings\n"
" [cyan]n[/cyan] save as a named profile\n"
" [cyan]l[/cyan] load a profile\n"
" [cyan]d[/cyan] delete a profile\n"
" [cyan]b[/cyan] back\n")
choice = _ask(console, " choice", "b").strip().lower()
if choice in _BACK:
return cfg
try:
if choice == "s":
path = save_default(cfg)
console.print(f" [green]saved — every run will start from "
f"{path}[/green]")
elif choice == "n":
name = _ask(console, " profile name", "myscan").strip()
if name:
console.print(f" [green]saved to "
f"{save_config(cfg, name)}[/green]")
elif choice == "l" and profiles:
name = _ask(console, " profile name or number").strip()
if name.isdigit() and 1 <= int(name) <= len(profiles):
name = profiles[int(name) - 1].stem
cfg = load_config(name)
console.print(f" [green]loaded {name}[/green]")
elif choice == "d" and profiles:
name = _ask(console, " profile name or number").strip()
if name.isdigit() and 1 <= int(name) <= len(profiles):
name = profiles[int(name) - 1].stem
if name and _confirm(f" delete {name}"):
console.print(" [green]deleted[/green]"
if delete_profile(name)
else " [yellow]no such profile[/yellow]")
except (OSError, FileNotFoundError, ValueError) as exc:
console.print(f" [red]{exc}[/red]")
# ---------------------------------------------------------------------------
# Help
# ---------------------------------------------------------------------------
_TOPICS: dict[str, tuple[str, str]] = {
"1": ("Getting started", """
Pick what to scan, then start. Ranges come from two places: type start and
end frequencies by hand, or choose from the built-in US band plan, which
carries each band's usual channel spacing and demodulator so you do not have
to set them.
Everything on this menu can also be given on the command line, and every
command-line option can be set here. Settings you save become the starting
point for every later run."""),
"2": ("How the scan works", """
The scanner sweeps each range in steps, listening at each tuner position for
the dwell time. Anything standing far enough above the noise counts as a
detection.
It then drops onto that frequency, looks at the signal briefly to choose the
right demodulator, and records until either the record limit is reached or the
channel goes quiet for the hang time. Gaps shorter than the hang time are
recorded straight through, so a two-way exchange stays in one file."""),
"3": ("Why nothing is being recorded", """
Most often the squelch threshold is too high, or the content check is
rejecting what it hears.
Try 'Squelch threshold' lower (8 dB is sensitive, 15 dB is conservative), and
check the scan summary: it reports how many detections were discarded and
why. To see everything the squelch opens on, set 'Check for content' to no —
but expect static and interference to be recorded too."""),
"4": ("Why static is being recorded", """
Turn 'Check for content' back on. With it on, a capture is kept only if it
carries speech, decodable Morse, or an identified digital keying scheme;
static, hum, bare carriers and interference are deleted.
If real signals are being rejected, lower 'Minimum speech score'. Speech
detection needs roughly a second of audio, so very short overs may be
missed."""),
"5": ("Recording conversations", """
Set 'Record for' to 0 so a long exchange is not cut off, and 'Wait for quiet'
longer than the pause between overs — five or six seconds suits most two-way
traffic. 'Absolute limit' still stops a capture running away.
Silence, static and interference all count as quiet, so a burst of noise
during a pause will not park the receiver on a finished conversation."""),
"6": ("Files and where they go", """
Recordings are written to the output directory, all in one flat folder, named
yyyy-mm-dd_hh.mm.ss_frequency_modulation.wav. Beside each one is a .json with
the identification and measurements, and with 'Save raw IQ' on, the raw
samples plus a SigMF sidecar.
scan_log.csv lists every hit and opens in a spreadsheet."""),
"7": ("HF and direct sampling", """
Below about 24 MHz the tuner cannot reach, so the signal is fed straight into
the digitiser. 'Direct sampling' set to auto switches this on and off as
needed; most dongles use the Q branch.
There is no filtering or gain in front of the digitiser in this mode, so an HF
antenna and a quiet location matter more than usual."""),
"8": ("Trunked systems", """
Police, fire and large business radio mostly runs on trunked systems, where a
pool of channels is shared and one frequency is given over entirely to a data
stream saying which channel each conversation has been put on. That is the
control channel: loud, perfectly steady, never silent, and with nothing on it
to hear.
It is recognised by its symbol rate and its refusal to pause, named on screen,
and skipped within a second or two. Turn 'Skip trunk control channels' off
only if you are collecting them for a decoder. If digital voice calls are
being skipped by mistake, raise 'Control channel patience'."""),
"9": ("Reading data signals", """
Much of what a scanner finds is not speech: doorbells, tyre-pressure sensors,
weather stations, remote controls, paging, packet radio. All of it is read.
Whatever the modulation, a data signal comes down to the same shape once it has
been sliced — a train of runs whose lengths carry the information — and which
line code it is (PWM, PPM, Manchester, NRZ) is worked out from the runs alone
rather than configured. Four-level FSK, as P25 and DMR use it, is recognised
as such and read as symbols; where a frame sync word appears the system is
named.
POCSAG paging and APRS packet carry their own checksums, so those are read in
full: the address and message text of a page, the callsign and position of an
APRS beacon. A decoded callsign goes onto the map with the rest.
What keeps it honest is repetition. Noise sliced at a threshold produces runs,
and runs produce bits, so a reading with nothing behind it is reported as
nothing at all. These transmitters send the same packet three to ten times
over, and bits that come back identical every time did not come from noise."""),
"10": ("Callsigns and the map", """
Anyone who identifies themselves in a transcript is picked out and looked up in
the FCC's published licence register: the name, the town, the class of licence.
The callsign is the only thing sent, and each one is asked about once and then
remembered, so a net recorded night after night is looked up once.
Because a licence says where its holder is, the same information is written as
a map — callsigns.kml in the output directory — with one pin per station,
carrying the licensee, the town, and every frequency and time you heard them.
It opens in Google Earth, QGIS, Marble and OsmAnd, and later scans add to it
rather than starting it over, so it fills in as a picture of what your aerial
can reach.
Callsigns arrive from three directions and all three end up on the same map:
spoken and transcribed, sent in Morse, or carried in the header of an APRS
packet. Neither of the last two involves a speech recogniser, so a receiver
with none installed still builds a map -- most of the stations on the air
never say a word, and identify themselves in a short burst of CW instead.
Turn 'Look callsigns up' off to keep the scan entirely offline; callsigns are
still found, and named by country from their prefix. Clear 'Map file' to stop
writing the map. US licence records are public, and include addresses."""),
"12": ("Pictures, aircraft, meters", """
Three of the things a receiver can hear are images rather than sounds, and all
three arrive as the audio a scan already records: slow-scan television, the
NOAA weather satellites on 137 MHz, and the shortwave weather fax stations.
Each announces itself -- a VIS header, a pair of line syncs, a phasing signal
-- so none of them is guessed at, and what is decoded is written as a PNG
beside the recording. saunterbrowse marks those in the list and gives the
path. Turn 'Decode pictures' off to skip the work.
A picture takes minutes rather than seconds, so 'Max record time' has to be
long enough or what arrives is the top of one. A partial picture is kept and
labelled partial.
Utility meters on 900 MHz are named rather than reported as hexadecimal, and
are not believed without their own checksum.
Two things are separate commands, because neither fits through a scan.
`bandsaunter adsb` parks the receiver on 1090 MHz: ADS-B is a megabit a
second and will not go through a channel twelve and a half kilohertz wide.
`bandsaunter weather` parks it on 433.92 MHz for the weather sensors, whose
messages are bursts of a carrier switched on and off, which a scan records as
clicks."""),
"13": ("Weather sensors on 433 MHz", """
The plastic box on a fence post that came with a consumer weather station
broadcasts what it can see every sixteen seconds, in the clear, on 433.92
MHz. `bandsaunter weather` reads it, and reads five families of them:
Tower 592TXR temperature, humidity
5-in-1 06014RM wind speed, wind direction, rainfall, temperature, humidity
Lightning 6045M temperature, humidity, strike count, how far off the storm is
609TXC temperature, humidity
606TX temperature
Battery state comes from all of them. Nothing is reported that has not
satisfied its own checksum and, on the older two models, arrived twice.
The identity in the message is a number that came out of a hat in a factory,
so press n while listening to name whichever sensor is on the screen -- the
shed, the greenhouse -- and it keeps the name from then on. Names live in
sensors.yaml beside the settings and can be edited by hand.
`bandsaunter readings --csv` turns a log into a spreadsheet: a column per
quantity, a row per reading, the name in the second column."""),
"14": ("APRS on 144 MHz", """
One channel, one frequency, everybody: 144.390 MHz across North America and a
different number in every other region. `bandsaunter aprs` parks on it and
writes down everything that passes -- positions, weather, messages, objects,
telemetry -- from every amateur station in earshot and every digipeater
repeating them onward, which is most of what you will hear.
The frequency is agreed between amateurs rather than allocated, so check
--region first: on the wrong channel there is silence, not a bad signal.
north-america is 144.390, europe 144.800, australia 145.175.
Nothing here needs naming. A station broadcasts a callsign issued by a
government, which is already the name.
What it reads: positions both uncompressed and compressed; Mic-E, which every
Kenwood and Yaesu mobile sends and which hides half the position inside the
destination callsign; weather; messages, acknowledgements and bulletins;
objects and items; status; telemetry; and traffic relayed in from another
network. A packet in a format it cannot read keeps its text and says so,
rather than being reported as a position it never claimed.
Three tables when it stops: who was heard and how well, what they said, and
the messages in order. --at LAT,LON adds distance and bearing.
--direct-only leaves out anything that came through a digipeater, which is the
honest measure of what your aerial reaches. `bandsaunter packets --csv --kml`
turns a log into a spreadsheet and something Google Earth opens."""),
"11": ("Keys during a scan", """
q stop the scan
p pause and resume
s skip the signal being recorded and carry on sweeping
l lock out this frequency for the rest of the run
+/- raise or lower the squelch threshold on the fly
saunterbrowse writes to the same lock-out list afterwards: pressing m over a
recording locks out the frequency it was heard on, which is usually when you
find out a frequency is not worth listening to. It can also file recordings
into saved/, investigate/ or noise/, and delete the ones worth nothing."""),
}
# ---------------------------------------------------------------------------
# Aircraft
# ---------------------------------------------------------------------------
_AIRCRAFT_INTRO = (
"Every airliner overhead broadcasts its address, callsign, altitude, "
"position and speed twice a second on 1090 MHz. This is not a scan and "
"cannot be one \u2014 the signalling is a megabit a second, and the scan "
"path is 12.5 kHz wide \u2014 so it has its own listening mode here.\n\n"
"Everything heard is written to a log as it arrives; the map is drawn "
"from that log afterwards, and can be drawn again with different options "
"as often as you like.\n\n"
"[bold]Passive capture[/bold] listens and writes, showing a line per "
"aircraft in this terminal. [bold]Realtime display[/bold] does the same "
"and opens a window with a real map in it, each aircraft moving on it "
"with a box beside it saying everything known about the flight. Both "
"leave the same files behind."
)
def _section(section=None):
"""The module that owns a set of options: aircraft unless told otherwise.
Every helper below works off ``OPTIONS``, ``OPTION_GROUPS``, ``in_group``,
``defaults`` and ``format_option``, which both sections provide and which
say nothing about aircraft or weather. That is what lets one set of
menus drive both, and what will let it drive a third.
"""
if section is not None:
return section
from . import aircraft as air
return air
def _options_table(console: Console, options, group: str,
section=None) -> list[st.Setting]:
air = _section(section)
items = air.in_group(group)
default = air.defaults()
t = Table(box=None, header_style="bold", pad_edge=False,
title=f"[bold]{group.lower()}[/bold]", title_justify="left")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("option", width=20)
t.add_column("value", width=16)
t.add_column("what it does", style="grey62", overflow="fold")
start = air.OPTIONS.index(items[0]) + 1
for i, o in enumerate(items, start):
value = air.format_option(o, getattr(options, o.key))
changed = getattr(options, o.key) != getattr(default, o.key)
t.add_row(str(i), o.label + (" *" if changed else ""),
Text(value, style="bold cyan" if changed else "white"),
o.help)
console.print(t)
return items
def aircraft_menu(console: Console, cfg: ScanConfig) -> None:
"""Listen to aircraft, and draw where they went, without a command line.
The options are the same ones the command line takes, described in the
same table, so the help here is the help there.
"""
from . import aircraft as air
options = air.load_options()
while True:
_rule(console, "aircraft (ADS-B)")
console.print(Panel(Text.from_markup(_AIRCRAFT_INTRO),
border_style="blue", padding=(0, 1)))
_option_groups(console, options)
logs = air.logs_in(cfg.output_dir)
kept = "no logs yet" if not logs else \
f"{len(logs)} log{'s' if len(logs) != 1 else ''}"
window = "opens a window" if air.windowed() else \
"needs Qt \u2014 see ?"
console.print(
f"\n [cyan]p[/cyan] [bold green]Passive capture[/bold green]"
f" [grey62]{air.describe(options)}[/grey62]\n"
f" [cyan]r[/cyan] [bold green]Realtime display[/bold green]"
f" [grey62]{window}, the map and the aircraft on it"
f"[/grey62]\n"
f" [cyan]m[/cyan] Draw a map from a log [grey62]{kept} in "
f"{cfg.output_dir}[/grey62]\n"
f" [cyan]N[/cyan] open group N "
f"[grey62]or type part of an option's name to find it[/grey62]\n"
f" [cyan]s[/cyan] Save these as default "
f"[grey62]kept in {air.options_path()}[/grey62]\n"
f" [cyan]d[/cyan] Reset them\n"
f" [cyan]b[/cyan] Back\n")
answer = _ask(console, " choice", "p").strip().lower()
if answer in _BACK:
return
# "l" was what this was called before there were two of them.
if answer in ("p", "l", "passive", "listen"):
_listen(console, cfg, options)
elif answer in ("r", "realtime", "window"):
_watch(console, cfg, options)
elif answer in ("m", "map", "draw"):
_draw_from_menu(console, cfg, options, logs)
elif answer == "s":
try:
where = air.save_options(options)
console.print(f" [green]saved to {where}[/green]")
except OSError as exc:
console.print(f" [red]could not save: {exc}[/red]")
elif answer == "d":
if _confirm(" reset every aircraft option"):
options = air.AircraftOptions()
console.print(" [green]reset[/green]")
elif answer.isdigit() and 1 <= int(answer) <= len(air.OPTION_GROUPS):
_option_group_menu(console, options,
air.OPTION_GROUPS[int(answer) - 1])
elif answer.lstrip("?").strip().isdigit():
_edit_option(console, options, answer)
elif answer:
found = _find_options(answer)
if not found:
console.print(f" [yellow]nothing matches {answer!r} \u2014 "
f"enter a group number, or p, r, m, s, d or b"
f"[/yellow]")
elif len(found) == 1:
_edit_option(console, options,
str(air.OPTIONS.index(found[0]) + 1))
else:
_option_list(console, options, found, f"matching {answer!r}")
_pick_option(console, options)
def _option_groups(console: Console, options, section=None) -> None:
"""The groups, and how many of each has been changed from the default.
A list of six lines rather than a table of thirty-three: the options
are all still there, and this is the way in to them.
"""
air = _section(section)
default = air.defaults()
t = Table(box=None, header_style="bold", pad_edge=False,
title="[bold]options[/bold]", title_justify="left")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("group", width=20)
t.add_column("", width=16, style="grey62")
t.add_column("what is in it", style="grey62", overflow="fold")
for i, group in enumerate(air.OPTION_GROUPS, 1):
items = air.in_group(group)
changed = sum(1 for o in items
if getattr(options, o.key) != getattr(default, o.key))
count = f"{len(items)} option{'s' if len(items) != 1 else ''}"
if changed:
count += f", {changed} changed"
t.add_row(str(i), group.lower(),
Text(count, style="bold cyan" if changed else "grey62"),
", ".join(o.label.lower() for o in items))
console.print(t)
def _find_options(text: str, section=None) -> list:
"""Every option this could mean, nearest match first.
An exact name wins outright. Typing "seconds" should reach the setting
called seconds, not that one and every other whose description happens
to mention the word -- so a name that matches exactly is the answer, and
the wider search is only what happens when nothing does.
"""
air = _section(section)
wanted = text.strip().lower()
if not wanted:
return []
exact = [o for o in air.OPTIONS
if wanted in (o.key.lower(), o.label.lower())]
if exact:
return exact
return [o for o in air.OPTIONS
if wanted in o.key.lower() or wanted in o.label.lower()
or wanted in o.help.lower()]
def _option_list(console: Console, options, items, title: str,
section=None) -> None:
"""One table of whichever options were asked for."""
air = _section(section)
default = air.defaults()
t = Table(box=None, header_style="bold", pad_edge=False,
title=f"[bold]{title}[/bold]", title_justify="left")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("option", width=20)
t.add_column("value", width=16)
t.add_column("what it does", style="grey62", overflow="fold")
for o in items:
value = air.format_option(o, getattr(options, o.key))
changed = getattr(options, o.key) != getattr(default, o.key)
t.add_row(str(air.OPTIONS.index(o) + 1), o.label + (" *" if changed else ""),
Text(value, style="bold cyan" if changed else "white"),
o.help)
console.print(t)
def _pick_option(console: Console, options, section=None) -> None:
"""Ask which of the options just listed to change, and change it."""
console.print("[grey62]Enter an option number to change it, "
"[cyan]?N[/cyan] for what it does, or blank to go back."
"[/grey62]")
answer = _ask(console, " option").strip().lower()
if answer and answer.lstrip("?").strip().isdigit():
_edit_option(console, options, answer, section)
def _option_group_menu(console: Console, options, group: str,
section=None) -> None:
"""One group of options, on a screen of its own."""
air = _section(section)
while True:
_rule(console, group.lower())
items = air.in_group(group)
_option_list(console, options, items, group.lower(), air)
console.print("\n[grey62]Enter an option number to change it, "
"[cyan]?N[/cyan] for what it does, or [cyan]b[/cyan] "
"to go back.[/grey62]")
answer = _ask(console, " option", "b").strip().lower()
if not answer or answer in _BACK:
return
if answer.lstrip("?").strip().isdigit():
_edit_option(console, options, answer, air)
else:
console.print(" [yellow]enter a number from the list, "
"or b[/yellow]")
def _edit_option(console: Console, options, answer: str,
section=None) -> None:
"""Change one option, or explain it when asked with a question mark."""
air = _section(section)
want_help = answer.startswith("?")
index = int(answer.lstrip("?").strip())
if not 1 <= index <= len(air.OPTIONS):
console.print(" [yellow]no such number[/yellow]")
return
option = air.OPTIONS[index - 1]
if want_help:
option_help(console, option, options, air)
else:
edit_setting(console, option, options, default=air.defaults(),
show_help=lambda c, o, v: option_help(c, o, v, air))
def option_help(console: Console, option: st.Setting, options,
section=None) -> None:
"""The same help panel the settings menu shows, for a section option."""
air = _section(section)
body = [f"[bold]{option.label}[/bold] [grey62]({option.key})[/grey62]",
"", option.help.capitalize() + "."]
if option.detail:
body += ["", option.detail]
if option.guidance and option.guidance != option.detail:
body += ["", f"[grey62]{option.guidance}[/grey62]"]
default = air.defaults()
body += ["", f"[grey62]now:[/grey62] "
f"{air.format_option(option, getattr(options, option.key))}"
f" [grey62]default:[/grey62] "
f"{air.format_option(option, getattr(default, option.key))}"]
rng = option.describe_range()
if rng:
body.append(f"[grey62]accepts:[/grey62] {rng}")
if option.flags:
flags = " ".join(option.flags)
if option.off_flags:
flags += " / " + " ".join(option.off_flags)
body.append(f"[grey62]command line:[/grey62] {flags}")
console.print(Panel(Text.from_markup("\n".join(body)),
border_style="blue", padding=(0, 1)))
# ---------------------------------------------------------------------------
# APRS
# ---------------------------------------------------------------------------
_APRS_INTRO = (
"One channel, one frequency, everybody: 144.390 MHz across North "
"America and a different number in every other region, carrying "
"position reports, weather, messages, objects and telemetry from every "
"amateur station within earshot \u2014 and from every hilltop "
"digipeater repeating them onward, which is most of what you will "
"hear.\n\n"
"Unlike the other two modes this is a conversation rather than a "
"broadcast. Stations address each other, acknowledge each other and "
"relay for each other, so what is worth showing is not only who is out "
"there but what was said.\n\n"
"Nothing here has to be named. A weather sensor broadcasts a number out "
"of a hat; an APRS station broadcasts a callsign issued by a "
"government, which is already the name."
)
def aprs_menu(console: Console, cfg: ScanConfig) -> None:
"""Listen to the APRS channel, without a command line."""
from . import aprs as ap
options = ap.load_options()
while True:
_rule(console, "APRS (144 MHz packet)")
console.print(Panel(Text.from_markup(_APRS_INTRO),
border_style="blue", padding=(0, 1)))
_option_groups(console, options, ap)
logs = ap.logs_in(cfg.output_dir)
kept = "no logs yet" if not logs else \
f"{len(logs)} log{'s' if len(logs) != 1 else ''}"
console.print(
f"\n [cyan]l[/cyan] [bold green]Listen[/bold green]"
f" [grey62]{ap.describe(options)}[/grey62]\n"
f" [cyan]r[/cyan] Read a log back [grey62]{kept} in "
f"{cfg.output_dir}[/grey62]\n"
f" [cyan]N[/cyan] open group N "
f"[grey62]or type part of an option's name to find it[/grey62]\n"
f" [cyan]s[/cyan] Save these as default "
f"[grey62]kept in {ap.options_path()}[/grey62]\n"
f" [cyan]d[/cyan] Reset them\n"
f" [cyan]b[/cyan] Back\n")
answer = _ask(console, " choice", "l").strip().lower()
if answer in _BACK:
return
if answer in ("l", "listen", "p"):
_aprs_listen(console, cfg, options)
elif answer in ("r", "read", "packets", "m"):
_aprs_read(console, cfg, options, logs)
elif answer == "s":
try:
where = ap.save_options(options)
console.print(f" [green]saved to {where}[/green]")
except OSError as exc:
console.print(f" [red]could not save: {exc}[/red]")
elif answer == "d":
if _confirm(" reset every APRS option"):
options = ap.AprsOptions()
console.print(" [green]reset[/green]")
elif answer.isdigit() and 1 <= int(answer) <= len(ap.OPTION_GROUPS):
_option_group_menu(console, options,
ap.OPTION_GROUPS[int(answer) - 1], ap)
elif answer.lstrip("?").strip().isdigit():
_edit_option(console, options, answer, ap)
elif answer:
found = _find_options(answer, ap)
if not found:
console.print(f" [yellow]nothing matches {answer!r} \u2014 "
f"enter a group number, or l, r, s, d or b"
f"[/yellow]")
elif len(found) == 1:
_edit_option(console, options,
str(ap.OPTIONS.index(found[0]) + 1), ap)
else:
_option_list(console, options, found, f"matching {answer!r}",
ap)
_pick_option(console, options, ap)
def _aprs_listen(console: Console, cfg: ScanConfig, options) -> None:
from . import aprs as ap
errs = options.validate()
if errs:
for e in errs:
console.print(f" [red]{e}[/red]")
return
console.print("[grey62]control-C stops listening and comes back here. "
"Stations beacon every few minutes, so give it a while."
"[/grey62]")
try:
ap.listen(console, options, cfg.output_dir)
except Exception as exc: # a menu must survive it
console.print(f" [red]{exc}[/red]")
def _aprs_read(console: Console, cfg: ScanConfig, options, logs) -> None:
"""Pick a log and read it back, newest first."""
from . import aprs as ap
from .aprslog import read_logs, write_csv, write_kml
if not logs:
console.print(f" [yellow]no logs in {cfg.output_dir} yet \u2014 "
"listen first, or turn the invented channel on"
"[/yellow]")
return
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("log")
t.add_column("when", style="grey62")
t.add_column("size", style="grey62", justify="right")
for i, path in enumerate(logs[:12], 1):
stat = path.stat()
t.add_row(str(i), path.name, _when(stat.st_mtime),
f"{stat.st_size / 1e6:.2f} MB")
console.print(t)
answer = _ask(console, " which log", "1").strip()
if answer in _BACK or not answer.isdigit():
return
index = int(answer)
if not 1 <= index <= min(12, len(logs)):
console.print(" [yellow]no such number[/yellow]")
return
path = logs[index - 1]
heard = read_logs([path])
if not heard:
console.print(f" [yellow]{path.name} holds no packets[/yellow]")
return
ap.report(console, ap.Net.of(heard), options)
if _confirm(" write a map and a spreadsheet too"):
for writer, suffix in ((write_csv, ".csv"), (write_kml, ".kml")):
try:
where = writer(path.with_suffix(suffix), heard,
options.imperial)
except OSError as exc:
console.print(f" [red]could not write it: {exc}[/red]")
continue
if where is not None:
console.print(f" [green]wrote {where}[/green]")
# ---------------------------------------------------------------------------
# Weather sensors
# ---------------------------------------------------------------------------
_WEATHER_INTRO = (
"Every consumer weather station has a plastic box on a fence post which "
"says what it can see, in the clear, on 433.92 MHz, every sixteen "
"seconds \u2014 to the display in the kitchen and to anyone else "
"listening. This reads the box.\n\n"
"Temperature and humidity from all of them; wind speed, wind direction "
"and rainfall from a 5-in-1; lightning strikes and how far off the storm "
"is from a 6045M. Battery state from every one.\n\n"
"What a sensor cannot tell you is which sensor it is: the identity in "
"the message came out of a hat in a factory. So [bold]press n while "
"listening[/bold] to give whichever is on the screen a name \u2014 the "
"shed, the greenhouse, the back fence \u2014 and it keeps it from then "
"on, in the display, in the log and in the spreadsheet."
)
def weather_menu(console: Console, cfg: ScanConfig) -> None:
"""Listen to the weather sensors, and name them, without a command line."""
from . import weather as wx
from .sensors import SensorBook
options = wx.load_options()
while True:
_rule(console, "weather sensors (433 MHz)")
console.print(Panel(Text.from_markup(_WEATHER_INTRO),
border_style="blue", padding=(0, 1)))
_option_groups(console, options, wx)
logs = wx.logs_in(cfg.output_dir)
book = SensorBook()
kept = "no logs yet" if not logs else \
f"{len(logs)} log{'s' if len(logs) != 1 else ''}"
named = sum(1 for s in book.ordered() if s.named)
known = (f"{len(book)} heard, {named} named" if len(book)
else "none heard yet")
console.print(
f"\n [cyan]l[/cyan] [bold green]Listen[/bold green]"
f" [grey62]{wx.describe(options)}[/grey62]\n"
f" [cyan]n[/cyan] Name the sensors [grey62]{known}"
f"[/grey62]\n"
f" [cyan]r[/cyan] Read a log back [grey62]{kept} in "
f"{cfg.output_dir}[/grey62]\n"
f" [cyan]N[/cyan] open group N "
f"[grey62]or type part of an option's name to find it[/grey62]\n"
f" [cyan]s[/cyan] Save these as default "
f"[grey62]kept in {wx.options_path()}[/grey62]\n"
f" [cyan]d[/cyan] Reset them\n"
f" [cyan]b[/cyan] Back\n")
answer = _ask(console, " choice", "l").strip().lower()
if answer in _BACK:
return
if answer in ("l", "listen", "p"):
_weather_listen(console, cfg, options)
elif answer in ("n", "name", "names"):
_sensor_names(console, book)
elif answer in ("r", "read", "readings", "m"):
_weather_readings(console, cfg, options, logs)
elif answer == "s":
try:
where = wx.save_options(options)
console.print(f" [green]saved to {where}[/green]")
except OSError as exc:
console.print(f" [red]could not save: {exc}[/red]")
elif answer == "d":
if _confirm(" reset every weather option"):
options = wx.WeatherOptions()
console.print(" [green]reset[/green]")
elif answer.isdigit() and 1 <= int(answer) <= len(wx.OPTION_GROUPS):
_option_group_menu(console, options,
wx.OPTION_GROUPS[int(answer) - 1], wx)
elif answer.lstrip("?").strip().isdigit():
_edit_option(console, options, answer, wx)
elif answer:
found = _find_options(answer, wx)
if not found:
console.print(f" [yellow]nothing matches {answer!r} \u2014 "
f"enter a group number, or l, n, r, s, d or b"
f"[/yellow]")
elif len(found) == 1:
_edit_option(console, options,
str(wx.OPTIONS.index(found[0]) + 1), wx)
else:
_option_list(console, options, found, f"matching {answer!r}",
wx)
_pick_option(console, options, wx)
def _weather_listen(console: Console, cfg: ScanConfig, options) -> None:
"""Run a listening session from the menu and come back afterwards."""
from . import weather as wx
errs = options.validate()
if errs:
for e in errs:
console.print(f" [red]{e}[/red]")
return
console.print("[grey62]control-C stops listening and comes back here. "
"Press [cyan]n[/cyan] while it runs to name a sensor."
"[/grey62]")
try:
wx.listen(console, options, cfg.output_dir)
except Exception as exc: # a menu must survive it
console.print(f" [red]{exc}[/red]")
def _sensor_names(console: Console, book) -> None:
"""The list of everything ever heard, and what it is called.
Everything ever heard rather than everything heard lately, because a
sensor with a flat battery is exactly the one somebody wants to look up.
"""
while True:
_rule(console, "sensor names")
sensors = book.ordered()
if not sensors:
console.print(" [yellow]nothing heard yet. Listen first, or "
"turn the invented garden on.[/yellow]")
return
t = Table(box=None, header_style="bold", pad_edge=False)
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("name", width=18)
t.add_column("id", style="grey62", width=6)
t.add_column("model", style="grey62", width=18)
t.add_column("msgs", style="grey62", justify="right", width=7)
t.add_column("last heard", style="grey62")
t.add_column("note", style="grey62", overflow="fold")
for i, sensor in enumerate(sensors, 1):
t.add_row(str(i),
Text(sensor.name, style="bold") if sensor.named
else Text("unnamed", style="yellow"),
sensor.sensor, sensor.model, f"{sensor.messages:,}",
_when(sensor.last_heard) if sensor.last_heard else "",
sensor.note)
console.print(t)
console.print(f"\n[grey62]Enter a number to name it, "
f"[cyan]-N[/cyan] to forget it, or [cyan]b[/cyan] to go "
f"back. Kept in {book.path}.[/grey62]")
answer = _ask(console, " sensor", "b").strip().lower()
if not answer or answer in _BACK:
return
forget = answer.startswith("-")
index = answer.lstrip("-").strip()
if not index.isdigit() or not 1 <= int(index) <= len(sensors):
console.print(" [yellow]enter a number from the list[/yellow]")
continue
sensor = sensors[int(index) - 1]
if forget:
if _confirm(f" forget {sensor.label()}"):
book.forget(sensor.key)
console.print(" [green]forgotten[/green]")
continue
name = _ask(console, f" a name for {sensor.sensor}",
sensor.name).strip()
note = _ask(console, " a note (optional)", sensor.note).strip()
try:
book.tag(sensor.key, name, note)
console.print(f" [green]saved[/green]")
except OSError as exc:
console.print(f" [red]could not save: {exc}[/red]")
def _weather_readings(console: Console, cfg: ScanConfig, options,
logs) -> None:
"""Pick a log and read it back, newest first."""
from . import weather as wx
from .sensors import SensorBook
from .weatherlog import read_logs, write_csv
if not logs:
console.print(f" [yellow]no logs in {cfg.output_dir} yet \u2014 "
"listen first, or turn the invented garden on[/yellow]")
return
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("log")
t.add_column("when", style="grey62")
t.add_column("size", style="grey62", justify="right")
for i, path in enumerate(logs[:12], 1):
stat = path.stat()
t.add_row(str(i), path.name, _when(stat.st_mtime),
f"{stat.st_size / 1e6:.2f} MB")
console.print(t)
answer = _ask(console, " which log", "1").strip()
if answer in _BACK or not answer.isdigit():
return
index = int(answer)
if not 1 <= index <= min(12, len(logs)):
console.print(" [yellow]no such number[/yellow]")
return
path = logs[index - 1]
readings = read_logs([path])
if not readings:
console.print(f" [yellow]{path.name} holds no readings[/yellow]")
return
book = SensorBook()
wx.report(console, wx.Garden.of(readings), book, options.imperial)
if _confirm(" write it as a spreadsheet too"):
try:
where = write_csv(path.with_suffix(".csv"), readings, book,
options.imperial)
console.print(f" [green]wrote {where}[/green]")
except OSError as exc:
console.print(f" [red]could not write it: {exc}[/red]")
def _listen(console: Console, cfg: ScanConfig, options) -> None:
"""Run a listening session from the menu and come back afterwards."""
from . import aircraft as air
errs = options.validate()
if errs:
for e in errs:
console.print(f" [red]{e}[/red]")
return
if not options.simulate:
console.print("[grey62]control-C stops listening and comes back "
"here.[/grey62]")
try:
heard = air.listen(console, options, cfg.output_dir)
except Exception as exc: # a menu must survive it
console.print(f" [red]{exc}[/red]")
return
if heard.log_path and not options.draw_after:
console.print(" [grey62]draw it with [cyan]m[/cyan], or set "
"\"Draw when finished\"[/grey62]")
def _watch(console: Console, cfg: ScanConfig, options) -> None:
"""Open the window, and come back to the menu when it is closed."""
from . import aircraft as air
errs = options.validate()
if errs:
for e in errs:
console.print(f" [red]{e}[/red]")
return
console.print("[grey62]closing the window stops the capture and writes "
"the log, the report and the map, exactly as the passive "
"capture does.[/grey62]")
try:
air.watch(console, options, cfg.output_dir)
except Exception as exc: # a menu must survive it
console.print(f" [red]{exc}[/red]")
def _draw_from_menu(console: Console, cfg: ScanConfig, options, logs) -> None:
"""Pick a log and draw it, newest first because that is usually the one."""
from . import aircraft as air
if not logs:
console.print(f" [yellow]no logs in {cfg.output_dir} yet \u2014 "
"listen first, or turn the simulated sky on[/yellow]")
return
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("log")
t.add_column("when", style="grey62")
t.add_column("size", style="grey62", justify="right")
for i, path in enumerate(logs[:12], 1):
stat = path.stat()
t.add_row(str(i), path.name,
_when(stat.st_mtime), f"{stat.st_size/1e6:.1f} MB")
console.print(t)
answer = _ask(console, " which log", "1").strip()
if answer in _BACK:
return
if not answer.isdigit() or not 1 <= int(answer) <= len(logs[:12]):
console.print(" [yellow]no such log[/yellow]")
return
chosen = logs[int(answer) - 1]
try:
air.draw_log(console, options, [chosen])
except Exception as exc:
console.print(f" [red]{exc}[/red]")
def _when(stamp: float) -> str:
from datetime import datetime
return datetime.fromtimestamp(stamp).strftime("%y-%m-%d %H:%M")
def help_screen(console: Console) -> None:
while True:
_rule(console, "help")
t = Table(box=None, header_style="bold")
t.add_column("#", style="grey62", width=3, justify="right")
t.add_column("topic")
for k, (title, _) in _TOPICS.items():
t.add_row(k, title)
console.print(t)
console.print("[grey62]Enter a topic number, a setting name to look "
"up, or blank to go back.[/grey62]")
answer = _ask(console, " topic").strip()
if not answer:
return
if answer in _TOPICS:
title, body = _TOPICS[answer]
console.print(Panel(Text(body.strip()), title=title,
border_style="blue", padding=(0, 1)))
else:
hits = st.search(answer)
if not hits:
console.print(f" [yellow]nothing matches {answer!r}[/yellow]")
for s in hits[:4]:
setting_help(console, s, ScanConfig())
# ---------------------------------------------------------------------------
# First run
# ---------------------------------------------------------------------------
def first_run_setup(console: Console, cfg: ScanConfig) -> bool:
"""Ask where recordings should go, the first time the program is run.
Returns True if settings were saved. Only the one question: everything
else has a working default and can be changed from the settings menu.
"""
console.print(Panel(Text.from_markup(
"[bold]Welcome to bandsaunter[/bold]\n\n"
"Recordings, transcripts and the scan log are all written to one "
"directory. Where would you like them?\n\n"
"[grey62]This is saved, so you are only asked once. Everything else "
"can be changed later from Settings, or with "
"[cyan]bandsaunter config[/cyan].[/grey62]"),
border_style="blue", padding=(0, 1)))
while True:
answer = _ask(console, " recordings directory",
cfg.output_dir or DEFAULT_OUTPUT_DIR).strip()
if not answer:
answer = DEFAULT_OUTPUT_DIR
path = Path(answer).expanduser()
try:
path.mkdir(parents=True, exist_ok=True)
probe = path / ".bandsaunter-write-test"
probe.touch()
probe.unlink()
except OSError as exc:
console.print(f" [red]cannot use that directory: {exc}[/red]")
continue
cfg.output_dir = answer
break
try:
saved = save_default(cfg)
console.print(f" [green]recordings will go to {path}[/green]")
console.print(f" [grey62]settings saved to {saved}[/grey62]\n")
return True
except OSError as exc:
console.print(f" [yellow]could not save settings: {exc}[/yellow]")
return False
# ---------------------------------------------------------------------------
# Main menu
# ---------------------------------------------------------------------------
def _summary(cfg: ScanConfig) -> str:
record = ("no limit" if not cfg.record_seconds
else f"{cfg.record_seconds:g}s")
gate = ", ".join(cfg.accept) if cfg.require_signal else "everything"
return (f"record {record}, hang {cfg.hang_seconds:g}s, "
f"squelch +{cfg.threshold_db:g} dB, keep {gate}")
def run_tui(console: Console, cfg: ScanConfig | None = None,
source: Path | None = None) -> ScanConfig | None:
"""The interactive front end. Returns a config to scan with, or None."""
cfg = cfg or ScanConfig()
console.print(Panel(Text.from_markup(
"[bold]bandsaunter[/bold] — RTL-SDR signal scanner\n"
"[grey62]Scan any set of frequencies, record what turns up, and "
"identify it. Everything is configurable here; press "
"[cyan]h[/cyan] for help at any point.[/grey62]"),
border_style="blue"))
if source:
console.print(f"[grey62]settings loaded from {source}[/grey62]")
try:
return _main_loop(console, cfg)
except TUIAbort:
console.print()
return None
def _main_loop(console: Console, cfg: ScanConfig) -> ScanConfig | None:
while True:
_rule(console, "main menu")
show_ranges(console, cfg)
console.print(
f"\n [cyan]1[/cyan] Frequency ranges "
f"[grey62]{len(cfg.ranges)} configured[/grey62]\n"
f" [cyan]2[/cyan] Band plan "
f"[grey62]{len(PRESETS)} US presets[/grey62]\n"
f" [cyan]3[/cyan] Settings "
f"[grey62]{_summary(cfg)}[/grey62]\n"
f" [cyan]4[/cyan] Saved settings and profiles\n"
f" [cyan]5[/cyan] Aircraft (ADS-B) "
f"[grey62]listen on 1090 MHz, draw where they went[/grey62]\n"
f" [cyan]6[/cyan] Weather sensors "
f"[grey62]listen on 433 MHz, name what is out there[/grey62]\n"
f" [cyan]7[/cyan] APRS (144 MHz packet) "
f"[grey62]positions, weather and messages from amateurs"
f"[/grey62]\n"
f" [cyan]h[/cyan] Help\n"
f" [cyan]s[/cyan] [bold green]Start scanning[/bold green]\n"
f" [cyan]q[/cyan] Quit\n")
choice = _ask(console, " choice", "s").strip().lower()
if choice == "1":
edit_ranges(console, cfg)
elif choice == "2":
choose_presets(console, cfg)
elif choice == "3":
settings_menu(console, cfg)
elif choice == "4":
cfg = profiles_menu(console, cfg)
elif choice == "5":
aircraft_menu(console, cfg)
elif choice == "6":
weather_menu(console, cfg)
elif choice == "7":
aprs_menu(console, cfg)
elif choice in ("h", "?", "help"):
help_screen(console)
elif choice in ("s", "start", "go"):
errs = cfg.validate()
if errs:
for e in errs:
console.print(f" [red]{e}[/red]")
continue
return cfg
elif choice in ("q", "quit", "exit"):
return None