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
This commit is contained in:
The Dust Council 2026-09-20 19:36:30 -07:00
parent 0f7e47e55e
commit 2b653c2c3e
16 changed files with 5543 additions and 17 deletions

View file

@ -10,9 +10,10 @@ If you are on Debian, Ubuntu or Mint, [build the package](#a-debian-ubuntu-mint-
**You can try the whole program before buying or plugging in a receiver.**
`--simulate` runs the scanner against a synthetic band, `bandsaunter adsb
--simulate` flies imaginary aircraft past an imaginary receiver, and
`bandsaunter weather --simulate` puts six weather sensors on a fence that does
not exist. None of the three needs
--simulate` flies imaginary aircraft past an imaginary receiver, `bandsaunter
weather --simulate` puts six weather sensors on a fence that does not exist,
and `bandsaunter aprs --simulate` fills a channel with amateur stations that
are not there. None of the four needs
hardware or a network.
---
@ -120,6 +121,8 @@ bandsaunter adsb --simulate --seconds 30
bandsaunter flights # draws what the last command heard
bandsaunter weather --simulate --seconds 60
bandsaunter readings --csv # turns what it heard into a spreadsheet
bandsaunter aprs --simulate --seconds 120
bandsaunter packets --kml # turns what it heard into a map
```
With a receiver plugged in:
@ -229,6 +232,13 @@ read the output. `--save-iq FILE` keeps the raw samples (2 MB a second, so
bound it with `--seconds 60`) and `--from-iq FILE` reads one back, so a
recording made where the aerial is can be worked on anywhere.
**APRS needs nothing extra either** — no network, no key, no package beyond
the table above. The only thing that decides whether you hear it is the aerial
and whether a digipeater is in range: a quarter-wave whip for 144 MHz is 49 cm,
which is longer than the one most dongles ship with. Check `--region` before
anything else, because on the wrong channel there is silence rather than a bad
signal. `bandsaunter aprs --simulate` runs the whole thing without an aerial.
**Aircraft and callsign lookups need no installation**, only a network. They
ask public registers about a callsign or a 24-bit address and cache the
answers for a month; `--no-lookup` turns them off, and what the address and

225
README.md
View file

@ -7,10 +7,11 @@ built-in US band plan — and it sweeps them, stops on anything above the noise
floor, records it, and works out what kind of signal it was. CW/Morse is
decoded to text.
Two things get sections of their own, because neither fits through a scan:
[the aircraft overhead](#aircraft) on 1090 MHz, drawn on a moving map, and
Three things get sections of their own, because none of them fits through a
scan: [the aircraft overhead](#aircraft) on 1090 MHz, drawn on a moving map;
[the weather sensors](#weather-sensors-on-433-mhz) on 433 MHz, which you can
give names to as they arrive.
give names to as they arrive; and [APRS](#aprs-on-144-mhz) on 144 MHz, where
amateur stations report where they are and talk to each other.
Two programs: `bandsaunter` scans, and
[`saunterbrowse`](#browsing-what-you-recorded) reads back what it collected —
@ -247,6 +248,7 @@ bandsaunter scan -r 144M-148M -r 420M-450M # your own ranges
bandsaunter scan -b 2m --simulate # try it without hardware
bandsaunter adsb --window # aircraft overhead, on a map
bandsaunter weather # the weather sensors on 433 MHz
bandsaunter aprs # amateur packet on 144.39 MHz
```
## Two ways to drive it
@ -262,15 +264,19 @@ table of settings, so neither can offer something the other cannot.
4 Saved settings and profiles
5 Aircraft (ADS-B) listen on 1090 MHz, draw where they went
6 Weather sensors listen on 433 MHz, name what is out there
7 APRS (144 MHz packet) positions, weather and messages from amateurs
h Help
s Start scanning
q Quit
```
Items 5 and 6 are sections of their own, with their own options and their own
menus, because neither fits through a scan: ADS-B is a megabit a second and a
scan channel is 12.5 kHz wide, and a weather sensor message is a burst of a
carrier switched on and off that a scan would record as clicks.
Items 5, 6 and 7 are sections of their own, with their own options and their
own menus, because none of them fits through a scan: ADS-B is a megabit a
second and a scan channel is 12.5 kHz wide; a weather sensor message is a burst
of a carrier switched on and off that a scan would record as clicks; and APRS
is a two-second transmission every few minutes from a hundred stations sharing
one frequency, of which a sweep would catch whichever happened to key up as it
passed.
Settings are grouped, show their current value against the built-in default,
and carry their own help:
@ -2250,6 +2256,211 @@ decoder problem apart: a capture that yields nothing on replay yields nothing
for anybody, and a capture that yields readings on replay but not on the air
is a setting.
## APRS on 144 MHz
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 —
and from every hilltop digipeater repeating them onward, which is most of what
you will actually hear.
```bash
bandsaunter aprs listen, and show who is out there
bandsaunter aprs --region europe ...on 144.800 instead
bandsaunter aprs --simulate a channel full of stations that are not there
bandsaunter packets --kml turn a log into something Google Earth opens
```
It is a section of its own for the same reason the other two are: a scan stops
on a signal, records it and moves on, and APRS is a two-second transmission
every few minutes from a hundred stations sharing one frequency. A sweep
catches whichever one happened to key up while the sweep was pointed there.
Unlike the others 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. And nothing
here has to be named: a weather sensor broadcasts a number out of a hat, but
an APRS station broadcasts a callsign issued by a government, which is already
the name.
```
╭──────────────────────────────────────────────────────────────────────────────────────────────╮
│ 144.39 MHz 6 stations 12 seen 148 packets 9 messages 41:02 aprs_2026-09-20.jsonl │
╰──────────────────────────────────────────────────────────────────────────────────────────────╯
station what said away signal pkts ago
KU0W-9 car 47.5570N 122.2783W ENE 54 km/h mobile 2 km ENE 38 dB 41 0:08
KB1XYZ weather station 47.5900N 122.2700W temperature 15.0 C 5 km NNE 34 dB 12 0:22
humidity 62% pressure 1013.2 hPa
W1AW-1 digipeater 47.6062N 122.3322W Seattle wide digi 7 km NNW 37 dB 4 1:14
EVENT1 fire 47.5900N 122.3300W 5 km NNW 36 dB 1 3:40
```
### Which channel
The frequency is agreed between amateurs rather than allocated, so it differs
by region and **there is no way to discover it from the air**: on the wrong one
you hear silence, not a bad signal. `--region` covers the common ones —
`north-america` (144.390), `europe` (144.800), `australia` (145.175), `japan`,
`brazil`, `thailand` — and `--frequency` takes a number for anything else.
### What it reads
The information field of an APRS packet is not one format. It is about twenty,
chosen by the first character, accreted over thirty years, and several of them
exist only because a particular radio shipped with them.
| what | how it arrives |
|---|---|
| Position | uncompressed, or compressed into thirteen characters of base-91 |
| Mic-E | every Kenwood and Yaesu mobile, with half the position hidden in the destination callsign |
| Weather | attached to a position, or positionless |
| Messages | to a station, acknowledged, rejected, or broadcast as a bulletin |
| Objects and items | something placed on the map that is not the station placing it |
| Status | what the operator typed |
| Telemetry | five analogue channels and eight bits |
| Third-party traffic | a packet relayed in from another network, credited to whoever originally sent it |
Riding in the comment: course and speed, altitude, transmitter power and
antenna height, pre-computed range, direction-finding reports, and the
precision extension.
**Mic-E deserves a note**, because it is a quarter of everything on the channel
and it is the least readable thing in amateur radio. In 1995 the destination
address of an APRS frame carried nothing but the word "APRS", and somebody
noticed that six bytes is exactly enough for a latitude. So a Mic-E packet puts
the latitude, the north/south bit, the east/west bit, a hundred degrees of
longitude and a three-bit status message into *the callsign it is addressed
to*, and the rest into the information field as characters chosen so the whole
thing survives being typed into a logbook. It is also the reason APRS fits in a
two-second transmission.
### Refusing to guess
A packet whose format does not match what its first character promised comes
back as unparsed, with its text kept, rather than as a position.
That sounds like a nicety and is not. Thirteen characters of a *malformed*
uncompressed position are perfectly good base-91, so a decoder that tries one
format and falls 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 means
uncompressed, which is why the compressed format writes a numeric overlay as a
letter), so the rule is read rather than guessed at.
`--unparsed` is on by default: a packet that defeats every parser here still
arrived, still came from a real station, and showing it is how the next format
gets added.
### Off the air
Four things happen between the aerial and a frame.
**The tones become a soft symbol.** APRS is Bell 202 — 1200 Hz for a mark,
2200 Hz for a space, twelve hundred a second, inside an ordinary FM
transmission. Two correlators, one at each tone, and the difference between
them. A correlator rather than a frequency discriminator because the tones are
less than an octave apart and radio audio is distorted enough that
instantaneous frequency wanders badly.
De-emphasis is turned off, which matters and is easy to miss: voice FM lifts
the high frequencies on transmit and drops them again on receive, and packet
radio takes its audio from the discriminator *before* that happens. Dropping
the highs would take four decibels off the 2200 Hz tone and leave the 1200 Hz
one alone, which is exactly the difference being measured.
**The soft symbol becomes bits**, sampled once a bit at an instant held in the
middle of the bit by a loop nudged at every zero crossing. The loop carries its
phase from one block of audio to the next, which is what makes this a receiver
rather than a decoder of recordings — 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.
**The bits become a frame.** NRZI first, where a zero is a change of tone and a
one is no change — which makes the whole thing immune to being wired up
backwards, since inverting the stream decodes to identical data. Then HDLC:
frames delimited by 01111110, with a zero stuffed after every five ones so the
flag cannot occur inside one.
**The frame is believed or it is not.** Sixteen bits of CRC, and nothing
without a correct one is reported. That is what makes it safe to leave running
for hours with the squelch open: a frame either checks out or it never existed.
A frame whose callsigns are unprintable is refused as well — on a band this
busy, sixteen bits is strong but not infinite.
It decodes down to about 8 dB of signal-to-noise and finds nothing at all in
pure noise.
### Afterwards
Three tables, because they answer different questions. **Stations heard** is
about the band and the aerial: where each was, how far off, how many packets,
how many of those arrived *directly* rather than through a digipeater, and how
strongly. **What they said** is the weather, the speeds and the status lines.
**What passed between them** is the messages, in order — the only part of APRS
that is a conversation.
`--at LAT,LON` turns on the distance and bearing columns. `--direct-only`
leaves out anything that reached you through a digipeater, which is a much
shorter list and is the honest measure of what your aerial can actually reach.
`--csv` writes a row per packet with position, speed and weather in their own
columns. `--kml` writes a pin where each station was last heard and a line for
anything that moved. Both can be made later from a log with `bandsaunter
packets --csv --kml`, and `--station CALL` narrows either to one callsign.
The log keeps the whole AX.25 frame in hexadecimal under whatever was made of
it. That is not a hypothetical precaution: the list of APRS formats is still
growing, so a packet this version cannot read is on the disk in full for a
version that can.
### Every APRS option
| option | flag | default | what it does |
|---|---|---|---|
| Receiver | `--device` | 0 | which receiver, when more than one is plugged in |
| Gain | `--gain` | auto | tuner gain in dB, or automatic |
| Sample rate | `--rate` | 240 kS/s | 96 kS/s is the least that holds the channel |
| Region | `--region` | north-america | which APRS channel to listen on |
| Listen on | `--frequency`, `--freq` | 144.390 MHz | the exact frequency, if the region's is not what you want |
| Invent a channel | `--simulate` / `--no-simulate` | no | stations that are not there |
| Listen for | `--seconds` | until stopped | how long before stopping |
| Write a log | `--log` / `--no-log` | yes | one line of JSON per packet |
| Print every packet | `--packets` / `--no-packets` | no | a stream of lines instead of a table |
| Keep on screen for | `--hold` | 3600 s | how long a station stays after its last packet |
| Receiver at | `--at` | blank | where the aerial is, for distances |
| Show readings in | `--units` | metric | metric or imperial, for the display and the export |
| Show what cannot be read | `--unparsed` / `--no-unparsed` | yes | list packets in unknown formats |
| Include relayed packets | `--digipeated` / `--direct-only` | yes | count what reached you through a digipeater |
| Report at the end | `--report` / `--no-report` | yes | print what was heard |
| Also write a spreadsheet | `--csv` / `--no-csv` | no | CSV beside the log |
| Also write a map | `--kml` / `--no-kml` | no | KML beside the log |
Saved in `aprs.yaml` beside the other settings, from the menu's **s** or by
hand.
### Without an aerial
`--simulate` puts a dozen stations on a channel that does not exist — cars
moving, a weather station, a digipeater, objects, messages passing between
them — keyed as real Bell 202 audio on a real FM carrier, through the real
demodulator and the real parsers. Nothing touches the receiver.
### If nothing is heard
**Check the region first.** It is the one fault that looks like a dead aerial
and is not: on the wrong channel there is silence rather than a bad signal.
Then give it time. A fixed station beacons every twenty or thirty minutes and a
mobile every minute or two, so five minutes of an ordinary suburb might be
three packets and an hour is a fair picture. If you are somewhere without a
digipeater in range you may genuinely hear nothing — APRS coverage is built
from volunteers' hilltops, and it has holes.
A quarter-wave whip for 144 MHz is 49 cm, which is longer than the aerial most
dongles ship with; the stock telescopic one extended properly does well.
`--packets` shows each frame as it arrives, which is the thing to watch while
moving an aerial about.
## Meters on 900 MHz
A scan of 902–928 MHz that turns up a burst gets it named rather than reported

View file

@ -9,7 +9,7 @@ and transcribing speech.
# 2026-08-21_02 is the second build made on the 21st. The revision is padded
# to two digits so versions sort as text.
VERSION_DATE = "2026-09-20"
VERSION_REVISION = 1
VERSION_REVISION = 2
__version__ = f"{VERSION_DATE}_{VERSION_REVISION:02d}"

1078
bandsaunter/aprs.py Normal file

File diff suppressed because it is too large Load diff

345
bandsaunter/aprslog.py Normal file
View file

@ -0,0 +1,345 @@
"""Writing down what came over the channel, and reading it back.
One line of JSON per packet, written the moment it arrives. Flushed after
every one, for the reason every log in this program is: a listening session
ends when the operator gets bored and presses control-C, and a log that only
reached the disk on a clean shutdown would be empty exactly when it was most
wanted.
Each line keeps the whole AX.25 frame in hexadecimal alongside whatever was
made of it. APRS has a long tail of formats -- about twenty in the
specification and more that one manufacturer invented once -- so a packet
this version cannot read is still on the disk in full, and a later version
that can read it can go back through old logs and do so. That is not a
hypothetical: the reason the frame is kept is that the list of formats is
still growing.
Out of it come two other things. A spreadsheet, because a track and a
temperature are both columns of numbers people want to plot; and a KML file,
because the natural thing to do with a hundred positions is to look at them
on a globe.
"""
from __future__ import annotations
import csv
import json
import time
from datetime import datetime
from pathlib import Path
from .acurite import Measure
from .packets import Message, Packet, Position, Telemetry
__all__ = ["AprsLog", "read_logs", "write_csv", "write_kml", "logs_in",
"LOG_VERSION"]
LOG_VERSION = 1
class AprsLog:
"""A JSON Lines record of every packet heard, written as it arrives."""
def __init__(self, path, receiver: str = "", frequency: float = 0.0,
sample_rate: float = 0.0, started: float = 0.0):
self.path = Path(path)
self.packets = 0
self.started = started or time.time()
self.path.parent.mkdir(parents=True, exist_ok=True)
self._file = self.path.open("a", encoding="utf8")
self._write({"log": "bandsaunter-aprs", "version": LOG_VERSION,
"started": round(self.started, 3),
"started_local": datetime.fromtimestamp(
self.started).strftime("%Y-%m-%d %H:%M:%S"),
"frequency": frequency, "sample_rate": sample_rate,
"receiver": receiver})
def _write(self, body: dict) -> None:
self._file.write(json.dumps(body, separators=(",", ":"),
ensure_ascii=False) + "\n")
self._file.flush()
def append(self, packet: Packet, frame=None) -> None:
"""Record one packet: what arrived, and what was made of it."""
body: dict = {"t": round(packet.at or time.time(), 3),
"src": packet.source, "dst": packet.destination,
"kind": packet.kind, "info": packet.info}
if packet.path:
body["path"] = list(packet.path)
if frame is not None and frame.raw:
# The frame is the evidence; everything else in the line is an
# opinion about it, and the opinions may improve later.
body["hex"] = frame.raw.hex().upper()
if packet.snr:
body["snr"] = round(packet.snr, 1)
if packet.reported:
body["reported"] = round(packet.reported, 3)
if packet.position is not None:
body["lat"] = round(packet.position.latitude, 6)
body["lon"] = round(packet.position.longitude, 6)
body["sym"] = packet.position.table + packet.position.code
if packet.position.ambiguity:
body["vague"] = packet.position.ambiguity
for name in ("course", "speed", "altitude", "range", "power",
"height", "gain"):
value = getattr(packet, name)
if value is not None:
body[name] = round(float(value), 3)
for name in ("name", "status", "comment", "beam"):
value = getattr(packet, name)
if value:
body[name] = value
if not packet.live:
body["killed"] = True
if packet.weather:
body["wx"] = {n: [m.value, m.unit]
for n, m in packet.weather.items()}
if packet.message is not None:
body["msg"] = {k: v for k, v in vars(packet.message).items() if v}
if packet.telemetry is not None:
body["tlm"] = {"seq": packet.telemetry.sequence,
"a": list(packet.telemetry.analogue),
"d": packet.telemetry.digital}
self.packets += 1
self._write(body)
def close(self) -> None:
try:
self._file.close()
except OSError:
pass
def __enter__(self) -> "AprsLog":
return self
def __exit__(self, *exc) -> None:
self.close()
# ---------------------------------------------------------------------------
# Reading it back
# ---------------------------------------------------------------------------
def logs_in(directory) -> list[Path]:
try:
found = list(Path(directory).expanduser().glob("aprs_*.jsonl"))
except OSError:
return []
return sorted(found, key=lambda p: p.stat().st_mtime, reverse=True)
def read_logs(paths) -> list[Packet]:
"""Every packet in one or more logs, in the order they were heard.
A line that will not parse is skipped rather than fatal. A log is
appended to while the disk fills and the power goes off, so the last line
of one is quite often half a line.
"""
out: list[Packet] = []
for path in ([paths] if isinstance(paths, (str, Path)) else paths):
try:
text = Path(path).expanduser().read_text(encoding="utf8")
except OSError:
continue
for line in text.splitlines():
packet = _packet_from(line)
if packet is not None:
out.append(packet)
out.sort(key=lambda p: p.at)
return out
def _packet_from(line: str) -> Packet | None:
line = line.strip()
if not line:
return None
try:
body = json.loads(line)
except ValueError:
return None
if not isinstance(body, dict) or "src" not in body:
return None # the header line, or something else entirely
packet = Packet(kind=str(body.get("kind", "unparsed")),
source=str(body.get("src", "")),
destination=str(body.get("dst", "")),
path=tuple(body.get("path") or ()),
at=float(body.get("t", 0.0) or 0.0),
reported=float(body.get("reported", 0.0) or 0.0),
snr=float(body.get("snr", 0.0) or 0.0),
info=str(body.get("info", "")))
if "lat" in body and "lon" in body:
symbol = str(body.get("sym", "/-"))
packet.position = Position(latitude=float(body["lat"]),
longitude=float(body["lon"]),
ambiguity=int(body.get("vague", 0) or 0),
table=symbol[:1] or "/",
code=symbol[1:2] or "-")
for name in ("course", "speed", "altitude", "range", "power", "height",
"gain"):
if name in body:
setattr(packet, name, float(body[name]))
for name in ("name", "status", "comment", "beam"):
if name in body:
setattr(packet, name, str(body[name]))
packet.live = not body.get("killed", False)
for name, value in (body.get("wx") or {}).items():
if isinstance(value, list) and value:
packet.weather[name] = Measure(
name, float(value[0]), str(value[1]) if len(value) > 1 else "")
if body.get("msg"):
packet.message = Message(**{k: str(v)
for k, v in body["msg"].items()
if k in vars(Message())})
if body.get("tlm"):
told = body["tlm"]
packet.telemetry = Telemetry(sequence=str(told.get("seq", "")),
analogue=tuple(told.get("a") or ()),
digital=str(told.get("d", "")))
return packet
# ---------------------------------------------------------------------------
# Out to a spreadsheet
# ---------------------------------------------------------------------------
_IMPERIAL = {"C": "F", "km/h": "mph", "mm": "in", "km": "mi", "m": "ft"}
def write_csv(path, heard, imperial: bool = False) -> Path:
"""A row per packet, with what it said in columns.
The union of every weather quantity anything reported, so a channel with
one weather station on it has temperature and pressure columns and every
car leaves them empty. That is the shape a spreadsheet wants.
"""
path = Path(path).expanduser()
path.parent.mkdir(parents=True, exist_ok=True)
quantities: list[str] = []
for packet in heard:
for name in packet.weather:
if name not in quantities:
quantities.append(name)
speed_unit = "mph" if imperial else "km/h"
height_unit = "ft" if imperial else "m"
heads = ["time", "unix", "station", "source", "destination", "path",
"kind", "latitude", "longitude", "symbol", "course",
f"speed ({speed_unit})", f"altitude ({height_unit})",
"signal (dB)", "status", "comment"] \
+ [_column(name, heard, imperial) for name in quantities]
with open(path, "w", encoding="utf8", newline="") as fh:
out = csv.writer(fh)
out.writerow(heads)
for packet in heard:
place = packet.position
out.writerow([
datetime.fromtimestamp(packet.at).isoformat(timespec="seconds")
if packet.at else "",
f"{packet.at:.3f}" if packet.at else "",
packet.station, packet.source, packet.destination,
",".join(packet.path), packet.kind,
f"{place.latitude:.6f}" if place else "",
f"{place.longitude:.6f}" if place else "",
(place.table + place.code) if place else "",
f"{packet.course:.0f}" if packet.course is not None else "",
_shown(packet.speed, "km/h", imperial),
_shown(packet.altitude, "m", imperial),
f"{packet.snr:.1f}" if packet.snr else "",
packet.status, packet.comment]
+ [_shown(packet.weather[name].value,
packet.weather[name].unit, imperial)
if name in packet.weather else ""
for name in quantities])
return path
def _column(name: str, heard, imperial: bool) -> str:
unit = ""
for packet in heard:
if name in packet.weather and packet.weather[name].unit:
unit = packet.weather[name].unit
break
if imperial:
unit = _IMPERIAL.get(unit, unit)
return f"{name} ({unit})" if unit else name
def _shown(value, unit: str, imperial: bool) -> str:
"""One number, in whichever system was asked for, as a plain figure.
Plain because a column of "21.5 C" is text and a column of 21.5 is a
temperature, and only one of those can be plotted.
"""
if value is None:
return ""
if imperial:
if unit == "C":
value = value * 9 / 5 + 32
elif unit in ("km/h", "km"):
value = value / 1.609344
elif unit == "mm":
value = value / 25.4
elif unit == "m":
value = value / 0.3048
return str(round(float(value), 3))
# ---------------------------------------------------------------------------
# Out to a globe
# ---------------------------------------------------------------------------
def write_kml(path, heard, imperial: bool = False,
title: str = "bandsaunter — APRS stations") -> Path | None:
"""A pin where each station was last heard, and a line where it moved.
Only the stations that said where they were, because a pin at nowhere is
worse than no pin: it puts a station off the west coast of Africa, which
is where nought degrees by nought degrees is and is the reason that bug
has a name.
"""
from xml.sax.saxutils import escape as xml_escape
tracks: dict[str, list] = {}
latest: dict[str, object] = {}
for packet in heard:
if packet.position is None:
continue
where = (packet.position.longitude, packet.position.latitude,
packet.altitude or 0.0)
line = tracks.setdefault(packet.station, [])
if not line or line[-1][:2] != where[:2]:
line.append(where)
latest[packet.station] = packet
if not latest:
return None
path = Path(path).expanduser()
path.parent.mkdir(parents=True, exist_ok=True)
out = ['<?xml version="1.0" encoding="UTF-8"?>',
'<kml xmlns="http://www.opengis.net/kml/2.2">', " <Document>",
f" <name>{xml_escape(title)}</name>",
' <Style id="track"><LineStyle><color>ff20a0ff</color>'
"<width>2</width></LineStyle></Style>"]
for call, line in sorted(tracks.items()):
packet = latest[call]
told = xml_escape(packet.describe(imperial))
name = xml_escape(call)
if len(line) > 1:
where = " ".join(f"{lon:.6f},{lat:.6f},{alt:.0f}"
for lon, lat, alt in line)
out += [" <Placemark>", f" <name>{name}</name>",
f" <description>{told}</description>",
" <styleUrl>#track</styleUrl>",
" <LineString><tessellate>1</tessellate>",
f" <coordinates>{where}</coordinates>",
" </LineString>", " </Placemark>"]
last = line[-1]
out += [" <Placemark>", f" <name>{name}</name>",
f" <description>{told}</description>",
" <Point><coordinates>"
f"{last[0]:.6f},{last[1]:.6f},{last[2]:.0f}"
"</coordinates></Point>", " </Placemark>"]
out += [" </Document>", "</kml>", ""]
path.write_text("\n".join(out), encoding="utf8")
return path

524
bandsaunter/ax25.py Normal file
View file

@ -0,0 +1,524 @@
"""AX.25 over the air: the frames APRS is carried in, and how to recover them.
Amateur packet radio sends data as HDLC frames over a carrier that is simply
switched between two audio tones inside an ordinary FM transmission -- 1200 Hz
for a mark and 2200 Hz for a space, twelve hundred of them a second, which is
Bell 202 and is what a telephone modem sounded like in 1976. It has stayed
because it works through any FM radio ever made, and because every handheld in
a rucksack is already an AFSK transmitter with a microphone socket.
Four things happen between the aerial and a frame, and each is a place to get
it wrong.
**The tones become a soft symbol.** Two correlators, one at each tone, and
the difference between them. A correlator rather than a frequency
discriminator because the tones are less than an octave apart and radio audio
is distorted enough that instantaneous frequency wanders badly; asking which
of the two tones a bit-length window contains more of is a question that
survives a weak signal.
**The soft symbol becomes bits.** Sampled once a bit, at an instant kept in
the middle of the bit by a phase-locked loop that is nudged at every zero
crossing. The loop is what makes this a receiver rather than a decoder of
recordings: it carries its phase from one block of audio to the next, so a
frame that straddles the boundary is read straight through.
**The bits become a frame.** NRZI first -- the data is in whether the tone
changed, not which tone it is, which makes the whole thing immune to being
wired up backwards. Then HDLC: frames are delimited by the flag 01111110 and
a zero is stuffed after every five ones so the flag cannot occur inside one.
**The frame is believed or it is not.** Sixteen bits of CRC, and nothing
without a correct one is reported. That is what makes it safe to run this
over hours of an open squelch: a frame either checks out or it never existed.
"""
from __future__ import annotations
import math
from dataclasses import dataclass, field
import numpy as np
__all__ = ["Address", "Frame", "Receiver", "fcs", "frame_from", "frame_bytes",
"hdlc_frames", "stuff", "unstuff", "modulate", "nrzi", "un_nrzi",
"MARK_HZ", "SPACE_HZ", "BAUD", "FLAG", "APRS_HZ", "APRS_CHANNELS",
"UI_CONTROL", "NO_LAYER_3", "MAX_FRAME"]
# Bell 202, as every VHF packet station on earth sends it.
MARK_HZ = 1200.0
SPACE_HZ = 2200.0
BAUD = 1200.0
FLAG = "01111110"
# Where APRS lives. One channel per region by agreement rather than by
# regulation, which is why there is a list of them rather than a number.
APRS_HZ = 144_390_000.0
APRS_CHANNELS = (
("north-america", 144_390_000.0, "United States, Canada, Mexico"),
("europe", 144_800_000.0, "IARU Region 1, including the UK"),
("australia", 145_175_000.0, "Australia and New Zealand"),
("japan", 144_640_000.0, "Japan"),
("brazil", 145_570_000.0, "Brazil"),
("thailand", 145_525_000.0, "Thailand"),
)
# An unnumbered information frame with no layer-3 protocol, which is what
# every APRS packet is and very nearly all this will ever see.
UI_CONTROL = 0x03
NO_LAYER_3 = 0xF0
# The longest thing worth believing: eight two-byte-addressed hops, a control
# and protocol byte, and 256 bytes of information.
MAX_FRAME = 8 * 7 + 2 + 2 + 256 + 2
# ---------------------------------------------------------------------------
# What a frame is made of
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class Address:
"""One callsign in a frame's path, with everything packed around it.
An AX.25 address is six characters and four bits, and the other four bits
of the last byte carry the parts that matter here: which station this is
when a callsign is not unique -- the SSID, the number after the dash --
and whether a digipeater has already repeated the frame.
"""
call: str = ""
ssid: int = 0
repeated: bool = False # the H bit: a digipeater has used this hop
reserved: int = 0b11 # the two bits nobody uses
command: bool = False # the C bit, meaningful only on the first two
def __str__(self) -> str:
out = f"{self.call}-{self.ssid}" if self.ssid else self.call
return out + "*" if self.repeated else out
@property
def plain(self) -> str:
"""Without the asterisk, for looking a station up."""
return f"{self.call}-{self.ssid}" if self.ssid else self.call
def address_from(raw: bytes) -> Address:
"""Seven bytes into a callsign. Everything is shifted up by one bit."""
call = "".join(chr(byte >> 1) for byte in raw[:6]).rstrip()
last = raw[6]
return Address(call=call, ssid=(last >> 1) & 0x0F,
repeated=bool(last & 0x80),
reserved=(last >> 5) & 0x03,
command=bool(last & 0x80))
def address_bytes(address: Address, last: bool = False) -> bytes:
"""One callsign back into seven bytes, ready to send."""
call = (address.call.upper() + " ")[:6]
flags = ((address.ssid & 0x0F) << 1) | (0x60 if address.reserved else 0)
if address.repeated:
flags |= 0x80
return bytes((ord(c) << 1) & 0xFE for c in call) + bytes([flags | int(last)])
@dataclass
class Frame:
"""One AX.25 frame whose frame-check sequence was correct."""
destination: Address = field(default_factory=Address)
source: Address = field(default_factory=Address)
path: tuple = ()
control: int = UI_CONTROL
pid: int = NO_LAYER_3
info: bytes = b""
raw: bytes = b""
at: float = 0.0 # when it arrived, as a clock time
snr: float = 0.0 # how far above the noise, in dB
@property
def unnumbered_information(self) -> bool:
"""Whether this is the frame type APRS uses, and nothing else does.
The control byte has its two low bits set on an unnumbered frame, and
the rest of it says which sort. APRS is always UI with no layer 3;
anything else on this channel is somebody running a real AX.25
connection, which is a fair thing to see and not an APRS packet.
"""
return (self.control & 0xEF) == UI_CONTROL and self.pid == NO_LAYER_3
@property
def kind(self) -> str:
"""What sort of AX.25 frame this is, in words."""
if not self.control & 0x01:
return "information"
if (self.control & 0x03) == 0x01:
return {0x00: "receive ready", 0x04: "receive not ready",
0x08: "reject", 0x0C: "selective reject"}.get(
self.control & 0x0C, "supervisory")
return {0x03: "unnumbered information", 0x2F: "set async balanced",
0x43: "disconnect", 0x0F: "disconnect mode",
0x63: "unnumbered ack", 0x87: "frame reject"}.get(
self.control & 0xEF, "unnumbered")
@property
def heard_through(self) -> tuple:
"""The digipeaters that actually repeated this, in order.
The ones with the H bit set, which is how a station says "I passed
this on". The rest of the path is where it has yet to go.
"""
return tuple(hop for hop in self.path if hop.repeated)
def route(self) -> str:
"""The frame's path the way every APRS tool in the world writes it."""
parts = [self.source.plain, self.destination.plain]
parts += [str(hop) for hop in self.path]
return ">".join(parts[:2]) + ("," + ",".join(parts[2:])
if len(parts) > 2 else "")
def text(self) -> str:
"""The information field as characters, for reading and for parsing."""
return self.info.decode("latin-1")
def describe(self) -> str:
body = self.text()
return f"{self.route()}:{body}" if body else self.route()
# ---------------------------------------------------------------------------
# The check that makes any of this safe to run
# ---------------------------------------------------------------------------
def fcs(data: bytes) -> int:
"""The AX.25 frame check: CRC-16/X.25, reflected, inverted at the end."""
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
crc = (crc >> 1) ^ 0x8408 if crc & 1 else crc >> 1
return crc ^ 0xFFFF
def frame_from(raw: bytes) -> Frame | None:
"""One frame out of its bytes, or None if it is not one.
The check is run first and nothing else is looked at until it passes.
Every field below is read on the strength of sixteen bits of CRC saying
the bytes are what was sent.
"""
if len(raw) < 7 * 2 + 2 + 2:
return None
body, check = raw[:-2], raw[-1] << 8 | raw[-2]
if fcs(body) != check:
return None
addresses, at = [], 0
while at + 7 <= len(body) and len(addresses) < 10:
field_ = body[at:at + 7]
addresses.append(address_from(field_))
at += 7
if field_[6] & 0x01: # the end-of-address bit
break
else:
return None
if len(addresses) < 2 or at + 2 > len(body):
return None
if not all(_sane_call(a.call) for a in addresses):
return None
return Frame(destination=addresses[0], source=addresses[1],
path=tuple(addresses[2:]), control=body[at],
pid=body[at + 1], info=body[at + 2:], raw=raw)
def _sane_call(call: str) -> bool:
"""Whether a callsign is one, rather than seven bits of luck.
Sixteen bits of CRC is a strong check and this is a crowded band; a frame
whose addresses are unprintable is one that passed the check by accident,
and there is no reason to put it on a display.
"""
return bool(call) and all(c.isalnum() or c == "-" for c in call) \
and call.isascii() and call.upper() == call
def frame_bytes(source, destination, info: str | bytes = b"",
path=(), control: int = UI_CONTROL,
pid: int = NO_LAYER_3) -> bytes:
"""A complete frame, check included, ready to be keyed out.
Kept beside the decoder so the two cannot drift apart, and so a test can
put a packet in and take the same one out. Callsigns may be given as
strings -- "W1AW-5", "WIDE2-1*" -- or as addresses.
"""
hops = tuple(_as_address(hop) for hop in path)
out = address_bytes(_as_address(destination))
out += address_bytes(_as_address(source), last=not hops)
for i, hop in enumerate(hops):
out += address_bytes(hop, last=(i == len(hops) - 1))
out += bytes([control & 0xFF, pid & 0xFF])
out += info.encode("latin-1") if isinstance(info, str) else bytes(info)
return out + bytes([fcs(out) & 0xFF, (fcs(out) >> 8) & 0xFF])
def _as_address(value) -> Address:
if isinstance(value, Address):
return value
text = str(value).strip().upper()
repeated = text.endswith("*")
text = text.rstrip("*")
call, _, ssid = text.partition("-")
return Address(call=call, ssid=int(ssid) if ssid.isdigit() else 0,
repeated=repeated)
# ---------------------------------------------------------------------------
# HDLC: where one frame ends and the next begins
# ---------------------------------------------------------------------------
def stuff(bits: str) -> str:
"""Insert a zero after every five ones, so no flag can occur inside."""
out, ones = [], 0
for bit in bits:
out.append(bit)
if bit == "1":
ones += 1
if ones == 5:
out.append("0")
ones = 0
else:
ones = 0
return "".join(out)
def unstuff(bits: str) -> str:
"""Take those zeroes back out again."""
out, ones = [], 0
for bit in bits:
if ones == 5:
ones = 0
if bit == "0":
continue # the stuffed bit
out.append(bit)
ones = ones + 1 if bit == "1" else 0
return "".join(out)
def nrzi(bits: str, level: str = "1") -> str:
"""Encode: a zero is sent as a change of tone, a one as no change."""
out = []
for bit in bits:
if bit == "0":
level = "0" if level == "1" else "1"
out.append(level)
return "".join(out)
def un_nrzi(bits: str) -> str:
"""Decode the same, which needs no knowledge of which tone is which.
A one is no change and a zero is a change, so inverting the whole stream
-- swapping mark for space, or wiring a discriminator up backwards --
decodes to exactly the same data. That is the point of the coding and is
why nothing here ever has to guess at polarity.
"""
return "".join("1" if a == b else "0" for a, b in zip(bits, bits[1:]))
def hdlc_frames(bits: str, most: int = 64) -> tuple[list[bytes], int]:
"""Split a bit stream at flags and undo the stuffing.
Returns the frames and how far along the stream was consumed, so a caller
reading a continuous signal knows what it may forget.
"""
frames: list[bytes] = []
at = bits.find(FLAG)
if at < 0:
return frames, max(0, len(bits) - len(FLAG))
used = at
while len(frames) < most:
while bits.startswith(FLAG, at): # flags repeat between frames
at += 8
used = at - 8 # the last flag fully passed
end = bits.find(FLAG, at)
if end < 0:
break # a body still arriving; keep it
body, at = bits[at:end], end
# Everything before this flag has been dealt with. Said here rather
# than at the top of the loop because a caller reading a continuous
# signal trims its buffer by this, and trimming to before a frame
# that has already been reported hands it back again on the next
# block -- every packet counted twice, for ever.
used = end
if len(body) < 8 * 17: # shorter than an empty frame
continue
clean = unstuff(body)
whole = len(clean) - len(clean) % 8
if not 17 <= whole // 8 <= MAX_FRAME:
continue
# Least significant bit first on the air, which is the one thing
# about AX.25 that catches everybody out.
frames.append(bytes(int(clean[i:i + 8][::-1], 2)
for i in range(0, whole, 8)))
return frames, max(used, 0)
# ---------------------------------------------------------------------------
# From audio to frames, without ever stopping
# ---------------------------------------------------------------------------
# How hard the sampling instant is pulled towards the middle of a bit at each
# zero crossing. Low enough that noise cannot drag it about, high enough to
# pull in within a flag or two of the start of a transmission -- which is
# what the flags at the front of every frame are there to allow.
LOOP_GAIN = 0.15
# How much of a bit stream to carry over when no flag has been seen. A frame
# is at most three hundred bytes, so anything older than that has no frame
# in it that has not already been found.
KEEP_BITS = MAX_FRAME * 8 * 2
class Receiver:
"""Audio in, frames out, across as many blocks as you care to feed it.
The state that has to survive a block boundary is the whole point of this
being a class: the tail of the audio, so the correlators see no edge; the
phase of the sampling loop, so a bit is not lost or gained where one
block meets the next; the level the tone was last at, for the NRZI; and
the bits themselves, so a frame that began in one block and ended in
another is read straight through rather than halved.
A packet takes most of a second at twelve hundred baud and blocks are
about that long, so frames straddling a boundary are not an edge case --
they are most of them.
"""
def __init__(self, rate: float, baud: float = BAUD,
mark: float = MARK_HZ, space: float = SPACE_HZ):
self.rate = float(rate)
self.baud = float(baud)
self.window = max(4, int(round(self.rate / self.baud)))
self.frames = 0
self.bytes_seen = 0
turn = 2.0 * math.pi * np.arange(self.window) / self.rate
self._mark = (np.cos(mark * turn), np.sin(mark * turn))
self._space = (np.cos(space * turn), np.sin(space * turn))
self._tail = np.zeros(self.window - 1, dtype=np.float64)
self._phase = 0.0
self._was = 0.0 # the last soft sample, for crossings
self._level = "1" # the tone the line was last at
self._bits = ""
# -- the three stages ------------------------------------------------
def soft(self, audio: np.ndarray) -> np.ndarray:
"""How much more mark than space each moment of audio holds.
Two correlators a bit long, and the difference of their magnitudes.
Positive is a mark. The tail of the previous block is prepended so
that the first bit of this one is measured against real audio rather
than against the zeroes a convolution would otherwise invent.
"""
x = np.concatenate((self._tail, np.asarray(audio, dtype=np.float64)))
if x.size < self.window:
self._tail = x
return np.zeros(0)
self._tail = x[-(self.window - 1):] if self.window > 1 else x[:0]
x = x - x.mean()
out = []
for cosine, sine in (self._mark, self._space):
i = np.convolve(x, cosine[::-1], mode="valid")
q = np.convolve(x, sine[::-1], mode="valid")
out.append(np.hypot(i, q))
return out[0] - out[1]
def slice(self, soft: np.ndarray) -> str:
"""Sample the soft signal once a bit, in the middle of the bit.
The instant is held there by a loop nudged at every zero crossing:
a crossing is a bit boundary, so it should fall half a bit away from
where the last sample was taken, and any difference is an error to
be taken out gently.
"""
step = self.baud / self.rate
phase, was = self._phase, self._was
out = []
for value in soft:
phase += step
if (value > 0.0) != (was > 0.0):
error = phase - 0.5 if phase < 1.0 else phase - 1.5
phase -= error * LOOP_GAIN
if phase >= 1.0:
phase -= 1.0
out.append("1" if value > 0.0 else "0")
was = value
self._phase, self._was = phase, was
return "".join(out)
def feed(self, audio, when: float = 0.0, snr: float = 0.0) -> list[Frame]:
"""One block of audio. Returns whatever frames finished in it."""
soft = self.soft(audio)
if soft.size == 0:
return []
tones = self._level + self.slice(soft)
self._level = tones[-1]
self._bits += un_nrzi(tones)
raw, used = hdlc_frames(self._bits)
self._bits = self._bits[used:][-KEEP_BITS:]
out = []
for data in raw:
self.bytes_seen += len(data)
frame = frame_from(data)
if frame is not None:
frame.at, frame.snr = when, snr
self.frames += 1
out.append(frame)
return out
def reset(self) -> None:
self._tail = np.zeros(self.window - 1, dtype=np.float64)
self._phase, self._was, self._level, self._bits = 0.0, 0.0, "1", ""
# ---------------------------------------------------------------------------
# Keying the same thing out, so the receiver can be held to it
# ---------------------------------------------------------------------------
def bits_of(frame: bytes, flags: int = 8) -> str:
"""One frame as the bits that go on the air: flags, stuffing and all."""
body = "".join(f"{byte:08b}"[::-1] for byte in frame)
return FLAG * flags + stuff(body) + FLAG * flags
def modulate(frames, rate: float = 22_050.0, baud: float = BAUD,
mark: float = MARK_HZ, space: float = SPACE_HZ,
flags: int = 8, amplitude: float = 0.5, noise: float = 0.0,
seed: int = 0, quiet_ms: float = 40.0) -> np.ndarray:
"""What a receiver would hear: the audio, not the radio signal.
The tone is continuous in phase across a bit boundary, because a real
modem's is -- it is one oscillator being retuned, not two being switched
-- and a decoder that only ever saw phase jumps at every bit would be
tested against something nothing transmits.
"""
if isinstance(frames, (bytes, bytearray)):
frames = [frames]
stream = "".join(nrzi(bits_of(bytes(f), flags)) for f in frames)
quiet = int(round(rate * quiet_ms / 1000.0))
per_bit = rate / baud
total = quiet * 2 + int(round(len(stream) * per_bit))
out = np.zeros(total, dtype=np.float64)
phase, at = 0.0, float(quiet)
for bit in stream:
tone = mark if bit == "1" else space
n = int(round(at + per_bit)) - int(round(at))
step = 2.0 * math.pi * tone / rate
out[int(round(at)):int(round(at)) + n] = amplitude * np.sin(
phase + step * np.arange(n))
phase = (phase + step * n) % (2.0 * math.pi)
at += per_bit
if noise:
out = out + np.random.default_rng(seed).normal(0.0, noise, out.size)
return out.astype(np.float32)

View file

@ -25,6 +25,7 @@ from .config import (DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_PATH, ScanConfig,
from .device import RtlSdrError, list_devices, set_driver_messages
from .librtlsdr import load_error
from . import settings as st
from .ax25 import APRS_CHANNELS as _APRS_CHANNELS
from .ranges import (RangeError, ScanRange, build_plan, parse_range_list)
from .scanner import Scanner, ScannerCallbacks
from .tui import TUIAbort, first_run_setup, run_tui, settings_menu
@ -62,6 +63,9 @@ examples:
bandsaunter weather --name 1A2B="back fence" name one while listening
bandsaunter readings --csv turn a weather log into a graph
bandsaunter sensors what is out there, and what it is called
bandsaunter aprs read the APRS channel on 144.39 MHz
bandsaunter aprs --region europe ...or 144.80 MHz, or wherever you are
bandsaunter packets --kml turn an APRS log into a map
bandsaunter scan -b 2m --simulate try it without hardware
""")
# The GNU form: the version, then who holds the copyright and what the
@ -292,6 +296,90 @@ examples:
"phosphor, amber and red")
ad.set_defaults(log_frames=True, lookup=True)
# -- aprs -----------------------------------------------------------------
ap = sub.add_parser("aprs",
help="read the APRS channel: positions, weather, "
"messages, telemetry")
ap.add_argument("--seconds", type=float, default=None,
help="stop after this long (default: until interrupted)")
ap.add_argument("--rate", type=float, default=None,
help="sample rate in Hz; 96 kS/s is the least that holds "
"the channel")
ap.add_argument("--gain", default=None, help="tuner gain in dB, or auto")
ap.add_argument("--device", type=int, default=None, help="which receiver")
ap.add_argument("--region", default=None,
choices=[key for key, _hz, _w in _APRS_CHANNELS],
help="which APRS channel to listen on")
ap.add_argument("--frequency", "--freq", dest="frequency", type=float,
default=None, metavar="HZ",
help="the exact frequency, if the region's channel is "
"not what you want")
ap.add_argument("--simulate", dest="simulate", action="store_true",
default=None,
help="invent a channel full of stations, for a receiver "
"with no aerial")
ap.add_argument("--no-simulate", dest="simulate", action="store_false",
default=None, help="listen to real stations")
ap.add_argument("--log", default=None, metavar="FILE",
help="where to write the packet log "
"(default: aprs_<time>.jsonl in the output directory)")
ap.add_argument("--no-log", dest="log_packets", action="store_false",
default=None, help="listen without writing anything down")
ap.add_argument("--packets", dest="packets_seen", action="store_true",
default=None,
help="print every packet as it arrives, not a table")
ap.add_argument("--no-packets", dest="packets_seen", action="store_false",
default=None, help="show the table that updates in place")
ap.add_argument("--hold", type=float, default=None, metavar="SECONDS",
help="how long a station stays on the display after its "
"last packet")
ap.add_argument("--at", dest="location", default=None, metavar="LAT,LON",
help="where the aerial is, so distances can be worked out")
ap.add_argument("--units", default=None, choices=("metric", "imperial"),
help="what to show readings in (the log is always metric)")
ap.add_argument("--unparsed", dest="unparsed", action="store_true",
default=None,
help="list packets whose format cannot be read")
ap.add_argument("--no-unparsed", dest="unparsed", action="store_false",
default=None, help="only packets that could be read")
ap.add_argument("--digipeated", dest="digipeated", action="store_true",
default=None, help="include packets that reached here "
"through a digipeater")
ap.add_argument("--direct-only", dest="digipeated", action="store_false",
default=None,
help="only what was heard without a relay in between")
ap.add_argument("--report", dest="report", action="store_true",
default=None, help="print what was heard at the end")
ap.add_argument("--no-report", dest="report", action="store_false",
default=None, help="no report when the listening stops")
ap.add_argument("--csv", dest="csv", action="store_true", default=None,
help="also write the packets as CSV beside the log")
ap.add_argument("--no-csv", dest="csv", action="store_false", default=None,
help="no spreadsheet")
ap.add_argument("--kml", dest="kml", action="store_true", default=None,
help="also write the stations and tracks for Google Earth")
ap.add_argument("--no-kml", dest="kml", action="store_false", default=None,
help="no map")
# -- packets --------------------------------------------------------------
pk = sub.add_parser("packets",
help="read an APRS log: report, spreadsheet, map")
pk.add_argument("path", nargs="*",
help="packet logs (default: the newest in the output "
"directory)")
pk.add_argument("--csv", nargs="?", const="", default=None, metavar="FILE",
help="write the packets as CSV (default: beside the log)")
pk.add_argument("--kml", nargs="?", const="", default=None, metavar="FILE",
help="write the stations and tracks for Google Earth")
pk.add_argument("--units", default=None, choices=("metric", "imperial"),
help="what to show readings in")
pk.add_argument("--station", default=None, metavar="CALL",
help="only this station, by callsign")
pk.add_argument("--at", dest="location", default=None, metavar="LAT,LON",
help="where the aerial was, so distances can be shown")
pk.add_argument("--no-report", dest="report", action="store_false",
default=True, help="write the files and say nothing")
# -- weather -------------------------------------------------------------
we = sub.add_parser("weather",
help="read the AcuRite weather sensors on 433 MHz")
@ -1472,6 +1560,104 @@ def _name_sensors(book, given, quiet: bool = False) -> int:
return done
def cmd_aprs(args) -> int:
"""Park on the APRS channel and write down everything that passes.
A command of its own because a scan cannot do this: APRS is a two-second
transmission every few minutes from a hundred stations sharing one
frequency, and a sweep catches whichever one happened to key up while the
sweep was pointed there.
"""
from . import aprs as ap
cfg, _ = load_default()
options = ap.load_options()
for flag, key in (("seconds", "seconds"), ("rate", "rate"),
("gain", "gain"), ("device", "device"),
("region", "region"), ("frequency", "frequency"),
("simulate", "simulate"), ("log_packets", "log"),
("packets_seen", "packets_seen"), ("hold", "hold"),
("location", "location"), ("units", "units"),
("unparsed", "unparsed"), ("digipeated", "digipeated"),
("report", "report"), ("csv", "csv"), ("kml", "kml")):
value = getattr(args, flag, None)
if value is not None:
setattr(options, key, value)
# The region picks the frequency unless the frequency was given outright,
# which is the one order that lets both flags mean what they say.
if getattr(args, "region", None) and getattr(args, "frequency", None) is None:
options.frequency = ap.channel_named(options.region)
errs = options.validate()
if errs:
for e in errs:
console.print(f"[red]{e}[/red]")
return 2
heard = ap.listen(console, options, cfg.output_dir, log_path=args.log)
if not heard.stations:
console.print("[grey62]nothing decoded — check the region with "
"`bandsaunter aprs --region`, and try "
"`--simulate` to see what a working channel looks "
"like[/grey62]")
return 0 if heard.stations else 1
def cmd_packets(args) -> int:
"""Read an APRS log back: what was heard, and where it was."""
from . import aprs as ap
from .aprslog import logs_in, read_logs, write_csv, write_kml
cfg, _ = load_default()
paths = [Path(p).expanduser() for p in args.path] if args.path \
else logs_in(cfg.output_dir)[:1]
if not paths:
console.print("[yellow]no APRS logs found. Record one with "
"`bandsaunter aprs`.[/yellow]")
return 1
for path in paths:
if not path.exists():
console.print(f"[red]no such file: {path}[/red]")
return 1
heard = read_logs(paths)
if not heard:
console.print(f"[yellow]{paths[0].name} holds no packets[/yellow]")
return 1
options = ap.load_options()
for flag, key in (("units", "units"), ("location", "location")):
value = getattr(args, flag, None)
if value is not None:
setattr(options, key, value)
if args.station:
wanted = args.station.strip().upper()
heard = [p for p in heard
if wanted in (p.source.upper(), p.station.upper())]
if not heard:
console.print(f"[yellow]nothing in the log from "
f"{args.station!r}[/yellow]")
return 1
if args.report:
ap.report(console, ap.Net.of(heard), options)
for flag, writer, suffix in ((args.csv, write_csv, ".csv"),
(args.kml, write_kml, ".kml")):
if flag is None:
continue
where = Path(flag).expanduser() if flag else paths[0].with_suffix(suffix)
try:
written = writer(where, heard, options.imperial)
except OSError as exc:
console.print(f"[red]cannot write {where}: {exc}[/red]")
return 1
if written is None:
console.print("[yellow]no station said where it was, so there "
"is no map to draw[/yellow]")
else:
console.print(f"[green]wrote {written}[/green] "
f"[grey62]{len(heard):,} packets[/grey62]")
return 0
def cmd_weather(args) -> int:
"""Park the receiver on 433.92 MHz and read the weather sensors.
@ -1906,6 +2092,7 @@ def main(argv=None) -> int:
"adsb": cmd_adsb, "waterfall": cmd_waterfall,
"flights": cmd_flights, "weather": cmd_weather,
"readings": cmd_readings, "sensors": cmd_sensors,
"aprs": cmd_aprs, "packets": cmd_packets,
}
try:
return handlers[args.command](args)

1213
bandsaunter/packets.py Normal file

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,8 @@ from .config import (DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_PATH,
from .ranges import RangeError, ScanRange, parse_frequency
__all__ = ["run_tui", "show_ranges", "settings_menu", "help_screen",
"aircraft_menu", "weather_menu", "first_run_setup", "TUIAbort"]
"aircraft_menu", "weather_menu", "aprs_menu", "first_run_setup",
"TUIAbort"]
_BACK = ("", "b", "back", "q", "quit", "x")
@ -676,6 +677,32 @@ 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
@ -971,6 +998,152 @@ def option_help(console: Console, option: st.Setting, options,
# ---------------------------------------------------------------------------
# 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
# ---------------------------------------------------------------------------
@ -1377,6 +1550,9 @@ def _main_loop(console: Console, cfg: ScanConfig) -> ScanConfig | None:
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")
@ -1394,6 +1570,8 @@ def _main_loop(console: Console, cfg: ScanConfig) -> ScanConfig | None:
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"):

View file

@ -22,8 +22,8 @@ from .flightlog import in_speed, speed_label
from .recorder import HitRecord
from .scanner import Detection, Scanner
__all__ = ["ScanDisplay", "AircraftDisplay", "WeatherDisplay", "KeyReader",
"print_hit", "print_band_table"]
__all__ = ["ScanDisplay", "AircraftDisplay", "WeatherDisplay",
"AprsDisplay", "KeyReader", "print_hit", "print_band_table"]
_SPARK = " ▁▂▃▄▅▆▇█"
@ -945,3 +945,129 @@ class WeatherDisplay:
if station.unread and not station.values:
out.append("framed, not understood", style="grey62")
return out
class AprsDisplay:
"""One line per station on the APRS channel, updated in place.
Ordered by when each was last heard, newest at the top, which is the
opposite of the other two displays in this program and is deliberate.
A weather sensor speaks every sixteen seconds and a station's row should
stay where the eye left it; an APRS channel is a hundred stations
beaconing every few minutes, and what somebody watching wants to know is
what just came in.
"""
def __init__(self, console: Console, hold: float = 3600.0,
imperial: bool = False, frequency: float = 144.39e6,
home=None):
self.console = console
self.hold = hold
self.imperial = imperial
self.frequency = frequency
self.home = home
self.packets = 0
self.started = time.time()
self.log_path = None
self.net = None
def update(self, net, packets_seen: int, log_path=None) -> None:
self.net = net
self.packets = packets_seen
if log_path is not None:
self.log_path = log_path
def showing(self, now: float | None = None) -> list:
return [] if self.net is None else self.net.showing(self.hold, now)
def render(self, now: float | None = None, width: int | None = None):
now = time.time() if now is None else now
width = self.console.size.width if width is None else width
here = self.showing(now)
parts = [self._header(here, now)]
if here:
parts.append(self._table(here, now, width))
else:
parts.append(Panel(_one_line(
"[grey62]nothing heard yet — a station beacons every few "
"minutes, so give it a while, and check the region: on the "
"wrong channel there is silence rather than a bad signal"
"[/grey62]"), border_style="grey37", padding=(0, 1)))
return Group(*parts)
def _header(self, here, now: float) -> Panel:
elapsed = max(0.001, now - self.started)
heard = len(self.net) if self.net is not None else 0
messages = len(self.net.messages) if self.net is not None else 0
where = f" [grey62]{self.log_path.name}[/grey62]" if self.log_path \
else ""
return Panel(_one_line(
f"[bold cyan]{self.frequency / 1e6:g} MHz[/bold cyan] "
f"[bold]{len(here)}[/bold] station"
f"{'s' if len(here) != 1 else ''} "
f"[grey62]{heard} seen[/grey62] "
f"[bold]{self.packets}[/bold] packet"
f"{'s' if self.packets != 1 else ''} "
f"[grey62]{messages} message{'s' if messages != 1 else ''}"
f" {_dur(elapsed)}[/grey62]{where} "
f"[grey62]control-C to stop[/grey62]"),
border_style="blue", padding=(0, 1))
def _table(self, here, now: float, width: int) -> Table:
"""As many columns as the terminal has room for, widest first."""
from .acurite import Measure, compass, format_measure
from .aprs import signal_text
t = Table(box=None, header_style="bold", pad_edge=False, expand=False)
t.add_column("station", width=10, no_wrap=True)
if width >= 96:
t.add_column("what", width=15, style="grey62", no_wrap=True)
t.add_column("said", overflow="fold")
if self.home is not None and width >= 76:
t.add_column("away", width=11, justify="right", no_wrap=True)
if width >= 66:
t.add_column("signal", width=6, justify="right")
if width >= 86:
t.add_column("pkts", width=4, justify="right", style="grey62")
t.add_column("ago", width=5, justify="right", style="grey62")
for station in here:
row = [Text(station.call, style="bold")]
if width >= 96:
row.append(station.symbol or station.kind)
row.append(self._said(station))
if self.home is not None and width >= 76:
away = station.away(self.home)
row.append("" if away is None else Text(
f"{format_measure(Measure('', away[0], 'km'), self.imperial)}"
f" {compass(away[1])}"))
if width >= 66:
row.append(Text.from_markup(signal_text(station.snr)))
if width >= 86:
row.append(f"{station.packets:,}")
row.append(_dur(max(0.0, now - station.last)))
t.add_row(*row)
return t
def _said(self, station) -> Text:
"""The most recent thing worth reading from this station."""
from .acurite import Measure, compass, format_measure
out = Text()
if station.position is not None:
out.append(station.position.describe(), style="white")
if station.moving:
out.append(f" {compass(station.course or 0.0)} ", style="grey62")
out.append(format_measure(Measure("", station.speed, "km/h"),
self.imperial), style="cyan")
if station.weather:
for name, measure in list(station.weather.items())[:3]:
out.append(f" {name} ", style="grey62")
out.append(format_measure(measure, self.imperial),
style="white")
for words in (station.status, station.comment):
if words:
out.append(" " + words[:40], style="grey70")
break
if not out.plain:
out.append(station.kind, style="grey62")
return out

View file

@ -1,5 +1,5 @@
.\" Generated by packaging/make-man.py -- do not edit by hand.
.TH BANDSAUNTER 1 "2026-09-20" "bandsaunter 2026-09-20_01" "User Commands"
.TH BANDSAUNTER 1 "2026-09-20" "bandsaunter 2026-09-20_02" "User Commands"
.SH NAME
bandsaunter \- scan, record and identify radio signals with an RTL-SDR
.SH SYNOPSIS
@ -99,6 +99,17 @@ below.
.B sensors
List every weather sensor heard, and give them names.
.TP
.B aprs
Listen to the APRS channel on 144 MHz: positions, weather, messages, objects
and telemetry from amateur stations. See
.B APRS
below.
.TP
.B packets
Read an APRS log back: the report, a spreadsheet and a map. See
.B APRS
below.
.TP
.B analyze
Identify a signal in an already-recorded file, decode Morse from it, or write
out the picture it turns out to be.
@ -2566,6 +2577,231 @@ Also write a spreadsheet \[em] write the readings as CSV beside the log.
.br
Setting name \fBcsv\fR, default \fBno\fR.
.PP
.SH APRS
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, and
from every hilltop digipeater repeating them onward \[em] which is most of what
will actually be heard.
.PP
A mode of its own for the same reason the other two are: a scan stops on a
signal, records it and moves on, and this is a two-second transmission every
few minutes from a hundred stations sharing one frequency. A sweep catches
whichever one happened to key up while it was pointed there.
.PP
Unlike the others it is a conversation rather than a broadcast, so what is
shown is not only who is out there but what was said. And nothing here needs
naming: a station broadcasts a callsign issued by a government, which is
already the name.
.SS Which channel
The frequency is agreed between amateurs rather than allocated, so it differs
by region and there is no way to discover it from the air: on the wrong one
there is silence, not a bad signal.
.B \-\-region
covers north-america (144.390), europe (144.800), australia (145.175), japan,
brazil and thailand, and
.B \-\-frequency
takes a number for anything else.
.SS What it reads
Positions, uncompressed and compressed into thirteen characters of base-91;
Mic-E, which every Kenwood and Yaesu mobile sends; weather, attached to a
position or without one; messages, acknowledgements, rejections and bulletins;
objects and items; status reports; telemetry; and third-party traffic relayed
in from another network, credited to whoever originally sent it. Riding in the
comment: course and speed, altitude, transmitter power and antenna height,
pre-computed range, direction-finding reports and the precision extension.
.PP
Mic-E deserves a note, being a quarter of everything on the channel and the
least readable thing in amateur radio. In 1995 the destination address of an
APRS frame carried nothing but the word "APRS", and somebody noticed that six
bytes is exactly enough for a latitude \[em] so a Mic-E packet puts the
latitude, the north/south bit, the east/west bit, a hundred degrees of
longitude and a three-bit status message into the callsign it is addressed to.
It is also why APRS fits in a two-second transmission.
.SS Refusing to guess
A packet whose format does not match what its first character promised comes
back as unparsed with its text kept, rather than as a position. Thirteen
characters of a malformed uncompressed position are perfectly good base-91, so
a decoder that tries one format and falls back to the other does not fail on a
bad packet \[em] 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, so the rule is read rather than
guessed at.
.SS Getting it off the air
APRS is Bell 202: 1200 Hz for a mark and 2200 Hz for a space, twelve hundred a
second, inside an ordinary FM transmission. Two correlators, one at each tone,
and the difference between them \[em] a correlator rather than a frequency
discriminator, the tones being less than an octave apart and radio audio
distorted enough that instantaneous frequency wanders.
.PP
De-emphasis is turned off, which matters and is easy to miss: voice FM lifts
the high frequencies on transmit and drops them again on receive, and packet
radio takes its audio from the discriminator before that happens. Dropping the
highs would take four decibels off the 2200 Hz tone and leave the 1200 Hz one
alone, which is exactly the difference being measured.
.PP
The soft symbol is sampled once a bit, at an instant held in the middle of the
bit by a loop nudged at every zero crossing, and that loop carries its phase
from one block of audio to the next \[em] a packet is most of a second and a
block is about one, so frames straddling the boundary are most of them. Then
NRZI, where a zero is a change of tone and a one is no change, which makes the
whole thing immune to being wired up backwards; then HDLC framing with its bit
stuffing; then sixteen bits of CRC, and nothing without a correct one is
reported. That last is what makes it safe to leave running for hours with the
squelch open.
.SS Afterwards
Three tables. Stations heard is about the band and the aerial: where each was,
how far off, how many packets, how many of those arrived directly rather than
through a digipeater, and how strongly. What they said is the weather, the
speeds and the status lines. What passed between them is the messages, in
order, which is the only part of APRS that is a conversation.
.PP
.BI \-\-at " LAT,LON"
turns on the distance and bearing columns.
.B \-\-direct\-only
leaves out anything relayed, which is a much shorter list and the honest
measure of what an aerial can reach.
.B \-\-csv
writes a row per packet and
.B \-\-kml
a pin per station with a line for anything that moved; both can be made later
from a log with
.BR "bandsaunter packets" ,
which also takes
.BI \-\-station " CALL"
to narrow either to one callsign.
.PP
The log keeps the whole AX.25 frame in hexadecimal under whatever was made of
it, because the list of APRS formats is still growing and a packet this
version cannot read should be on the disk in full for a version that can.
.SS If nothing is heard
Check the region first: it is the one fault that looks like a dead aerial and
is not. Then give it time \[em] a fixed station beacons every twenty or thirty
minutes and a mobile every minute or two, so five minutes of an ordinary
suburb might be three packets. A quarter-wave whip for 144 MHz is 49 cm, which
is longer than the aerial most dongles ship with.
.B \-\-packets
shows each frame as it arrives, which is what to watch while moving an aerial
about.
.SH APRS OPTIONS
Every option the APRS side takes, in the four groups the menu shows them in.
Each is a flag here and a line in the menu, and both come from one table in
the program, so they cannot disagree.
.SS Receiver
.TP
.B --device
Receiver \[em] which receiver to use, when more than one is plugged in.
.br
Setting name \fBdevice\fR, default \fB0\fR.
.br
Accepts: at least 0.
.TP
.B --gain
Gain \[em] tuner gain in dB, or automatic.
.br
Setting name \fBgain\fR, default \fBauto\fR.
.TP
.B --rate
Sample rate \[em] how fast to sample; 96 kS/s is the least that holds the channel (Hz).
.br
Setting name \fBrate\fR, default \fB240 kHz\fR.
.br
Accepts: at least 96000.
.TP
.B --region
Region \[em] which APRS channel to listen on.
.br
Setting name \fBregion\fR, default \fBnorth-america\fR.
.br
Accepts: one of: north-america, europe, australia, japan, brazil, thailand.
.TP
.B --frequency --freq
Listen on \[em] the exact frequency, if the region's channel is not what you want (Hz).
.br
Setting name \fBfrequency\fR, default \fB144.39 MHz\fR.
.br
Accepts: at least 1e+06, at most 2e+09.
.TP
.B --simulate / --no-simulate
Invent a channel \[em] put imaginary stations on an imaginary band.
.br
Setting name \fBsimulate\fR, default \fBno\fR.
.RS
.PP
Turn this on to see what the whole thing does without an aerial. Turn it off to hear real stations.
.RE
.PP
.SS Listening
.TP
.B --seconds
Listen for \[em] how long to listen before stopping (0 = until interrupted) (s).
.br
Setting name \fBseconds\fR, default \fBuntil stopped\fR.
.br
Accepts: at least 0.
.TP
.B --log / --no-log
Write a log \[em] write every packet down as it arrives.
.br
Setting name \fBlog\fR, default \fByes\fR.
.TP
.B --packets / --no-packets
Print every packet \[em] one line per packet instead of a table that updates in place.
.br
Setting name \fBpackets_seen\fR, default \fBno\fR.
.TP
.B --hold
Keep on screen for \[em] how long a station stays on the display after its last packet (s).
.br
Setting name \fBhold\fR, default \fB3600 s\fR.
.br
Accepts: at least 1.
.TP
.B --at
Receiver at \[em] where the aerial is, as latitude,longitude (blank = no distances).
.br
Setting name \fBlocation\fR, default \fBblank\fR.
.PP
.SS Showing
.TP
.B --units
Show readings in \[em] metric or imperial, for the display and the export.
.br
Setting name \fBunits\fR, default \fBmetric\fR.
.br
Accepts: one of: metric, imperial.
.TP
.B --unparsed / --no-unparsed
Show what cannot be read \[em] list packets whose format this does not understand.
.br
Setting name \fBunparsed\fR, default \fByes\fR.
.TP
.B --digipeated / --direct-only
Include relayed packets \[em] count packets that reached here through a digipeater.
.br
Setting name \fBdigipeated\fR, default \fByes\fR.
.RS
.PP
Leave it on for a picture of the network; turn it off to find out what you can actually hear.
.RE
.PP
.SS Afterwards
.TP
.B --report / --no-report
Report at the end \[em] print what each station said when the listening stops.
.br
Setting name \fBreport\fR, default \fByes\fR.
.TP
.B --csv / --no-csv
Also write a spreadsheet \[em] write the packets as CSV beside the log.
.br
Setting name \fBcsv\fR, default \fBno\fR.
.TP
.B --kml / --no-kml
Also write a map \[em] write the stations and their tracks for Google Earth.
.br
Setting name \fBkml\fR, default \fBno\fR.
.PP
.SH FILES
.TP
.I ~/.config/bandsaunter/config.yaml
@ -2581,6 +2817,9 @@ The weather options, as saved from the menus.
What each weather sensor is called. The only file here holding anything a
person typed; safe to edit by hand.
.TP
.I ~/.config/bandsaunter/aprs.yaml
The APRS options, as saved from the menus.
.TP
.I ~/.config/bandsaunter/*.yaml
Named profiles.
.TP
@ -2594,6 +2833,13 @@ Every weather sensor message heard in one listening session, with a
.I .csv
of the readings beside it where one was asked for.
.TP
.IR aprs_ * .jsonl
Every APRS packet heard in one listening session, with a
.I .csv
and a
.I .kml
beside it where they were asked for.
.TP
.I ~/bandsaunter/
Where recordings, transcripts and logs are written, unless
.B \-\-output

View file

@ -70,6 +70,13 @@ def weather_section() -> list[str]:
return options_section(wx)
def aprs_section() -> list[str]:
"""Every APRS option, from the same table again."""
from bandsaunter import aprs as ap
return options_section(ap)
def options_section(air) -> list[str]:
"""One section's options, written out from the table the program uses.
@ -208,6 +215,17 @@ below.
.B sensors
List every weather sensor heard, and give them names.
.TP
.B aprs
Listen to the APRS channel on 144 MHz: positions, weather, messages, objects
and telemetry from amateur stations. See
.B APRS
below.
.TP
.B packets
Read an APRS log back: the report, a spreadsheet and a map. See
.B APRS
below.
.TP
.B analyze
Identify a signal in an already-recorded file, decode Morse from it, or write
out the picture it turns out to be.
@ -1557,6 +1575,117 @@ Every option the weather side takes, in the four groups the menu shows them
in. Each is a flag here and a line in the menu, and both come from one table
in the program, so they cannot disagree.
.WEATHER_OPTIONS_HERE
.SH APRS
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, and
from every hilltop digipeater repeating them onward \[em] which is most of what
will actually be heard.
.PP
A mode of its own for the same reason the other two are: a scan stops on a
signal, records it and moves on, and this is a two-second transmission every
few minutes from a hundred stations sharing one frequency. A sweep catches
whichever one happened to key up while it was pointed there.
.PP
Unlike the others it is a conversation rather than a broadcast, so what is
shown is not only who is out there but what was said. And nothing here needs
naming: a station broadcasts a callsign issued by a government, which is
already the name.
.SS Which channel
The frequency is agreed between amateurs rather than allocated, so it differs
by region and there is no way to discover it from the air: on the wrong one
there is silence, not a bad signal.
.B \-\-region
covers north-america (144.390), europe (144.800), australia (145.175), japan,
brazil and thailand, and
.B \-\-frequency
takes a number for anything else.
.SS What it reads
Positions, uncompressed and compressed into thirteen characters of base-91;
Mic-E, which every Kenwood and Yaesu mobile sends; weather, attached to a
position or without one; messages, acknowledgements, rejections and bulletins;
objects and items; status reports; telemetry; and third-party traffic relayed
in from another network, credited to whoever originally sent it. Riding in the
comment: course and speed, altitude, transmitter power and antenna height,
pre-computed range, direction-finding reports and the precision extension.
.PP
Mic-E deserves a note, being a quarter of everything on the channel and the
least readable thing in amateur radio. In 1995 the destination address of an
APRS frame carried nothing but the word "APRS", and somebody noticed that six
bytes is exactly enough for a latitude \[em] so a Mic-E packet puts the
latitude, the north/south bit, the east/west bit, a hundred degrees of
longitude and a three-bit status message into the callsign it is addressed to.
It is also why APRS fits in a two-second transmission.
.SS Refusing to guess
A packet whose format does not match what its first character promised comes
back as unparsed with its text kept, rather than as a position. Thirteen
characters of a malformed uncompressed position are perfectly good base-91, so
a decoder that tries one format and falls back to the other does not fail on a
bad packet \[em] 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, so the rule is read rather than
guessed at.
.SS Getting it off the air
APRS is Bell 202: 1200 Hz for a mark and 2200 Hz for a space, twelve hundred a
second, inside an ordinary FM transmission. Two correlators, one at each tone,
and the difference between them \[em] a correlator rather than a frequency
discriminator, the tones being less than an octave apart and radio audio
distorted enough that instantaneous frequency wanders.
.PP
De-emphasis is turned off, which matters and is easy to miss: voice FM lifts
the high frequencies on transmit and drops them again on receive, and packet
radio takes its audio from the discriminator before that happens. Dropping the
highs would take four decibels off the 2200 Hz tone and leave the 1200 Hz one
alone, which is exactly the difference being measured.
.PP
The soft symbol is sampled once a bit, at an instant held in the middle of the
bit by a loop nudged at every zero crossing, and that loop carries its phase
from one block of audio to the next \[em] a packet is most of a second and a
block is about one, so frames straddling the boundary are most of them. Then
NRZI, where a zero is a change of tone and a one is no change, which makes the
whole thing immune to being wired up backwards; then HDLC framing with its bit
stuffing; then sixteen bits of CRC, and nothing without a correct one is
reported. That last is what makes it safe to leave running for hours with the
squelch open.
.SS Afterwards
Three tables. Stations heard is about the band and the aerial: where each was,
how far off, how many packets, how many of those arrived directly rather than
through a digipeater, and how strongly. What they said is the weather, the
speeds and the status lines. What passed between them is the messages, in
order, which is the only part of APRS that is a conversation.
.PP
.BI \-\-at " LAT,LON"
turns on the distance and bearing columns.
.B \-\-direct\-only
leaves out anything relayed, which is a much shorter list and the honest
measure of what an aerial can reach.
.B \-\-csv
writes a row per packet and
.B \-\-kml
a pin per station with a line for anything that moved; both can be made later
from a log with
.BR "bandsaunter packets" ,
which also takes
.BI \-\-station " CALL"
to narrow either to one callsign.
.PP
The log keeps the whole AX.25 frame in hexadecimal under whatever was made of
it, because the list of APRS formats is still growing and a packet this
version cannot read should be on the disk in full for a version that can.
.SS If nothing is heard
Check the region first: it is the one fault that looks like a dead aerial and
is not. Then give it time \[em] a fixed station beacons every twenty or thirty
minutes and a mobile every minute or two, so five minutes of an ordinary
suburb might be three packets. A quarter-wave whip for 144 MHz is 49 cm, which
is longer than the aerial most dongles ship with.
.B \-\-packets
shows each frame as it arrives, which is what to watch while moving an aerial
about.
.SH APRS OPTIONS
Every option the APRS side takes, in the four groups the menu shows them in.
Each is a flag here and a line in the menu, and both come from one table in
the program, so they cannot disagree.
.APRS_OPTIONS_HERE
.SH FILES
.TP
.I ~/.config/bandsaunter/config.yaml
@ -1572,6 +1701,9 @@ The weather options, as saved from the menus.
What each weather sensor is called. The only file here holding anything a
person typed; safe to edit by hand.
.TP
.I ~/.config/bandsaunter/aprs.yaml
The APRS options, as saved from the menus.
.TP
.I ~/.config/bandsaunter/*.yaml
Named profiles.
.TP
@ -1585,6 +1717,13 @@ Every weather sensor message heard in one listening session, with a
.I .csv
of the readings beside it where one was asked for.
.TP
.IR aprs_ * .jsonl
Every APRS packet heard in one listening session, with a
.I .csv
and a
.I .kml
beside it where they were asked for.
.TP
.I ~/bandsaunter/
Where recordings, transcripts and logs are written, unless
.B \-\-output
@ -1698,6 +1837,7 @@ def main() -> int:
"\n".join(aircraft_section()))
text = text.replace(".WEATHER_OPTIONS_HERE",
"\n".join(weather_section()))
text = text.replace(".APRS_OPTIONS_HERE", "\n".join(aprs_section()))
text = text.replace("\n\n", "\n") # troff dislikes blank lines
target = Path(sys.argv[1] if len(sys.argv) > 1
else Path(__file__).parent / "bandsaunter.1")

629
tests/test_aprs.py Normal file
View file

@ -0,0 +1,629 @@
"""The APRS section: the registry, the log, the report and the two front ends.
The radio is in test_ax25.py and the formats are in test_packets.py. What is
here is everything between a parsed packet and a person.
"""
import json
import time
import numpy as np
import pytest
from rich.console import Console
from bandsaunter import aprs as ap
from bandsaunter import aprslog as al
from bandsaunter import ax25, packets
from bandsaunter.ui import AprsDisplay
RATE = 240_000.0
def packet(info="=4903.50N/07201.75W>088/036 mobile", source="W1AW-9",
at=1_000.0, snr=20.0, path=(), destination="APRS"):
got = packets.parse_info(info, destination)
got.source, got.at, got.snr = source, at, snr
got.path, got.destination = tuple(path), destination
return got
# ---------------------------------------------------------------------------
# The options
# ---------------------------------------------------------------------------
def test_every_option_names_a_field_that_exists():
fields = set(ap.AprsOptions().__dict__)
for option in ap.OPTIONS:
assert option.key in fields, f"{option.key} is not an option"
def test_every_field_is_an_option_somebody_can_reach():
assert set(ap.AprsOptions().__dict__) == {o.key for o in ap.OPTIONS}
def test_every_option_is_in_a_group_and_says_what_it_does():
for option in ap.OPTIONS:
assert option.group in ap.OPTION_GROUPS
assert option.help and option.detail and option.flags
if option.kind == "bool":
assert option.off_flags, f"{option.key} cannot be turned off"
for group in ap.OPTION_GROUPS:
assert ap.in_group(group)
def test_every_option_flag_is_one_the_parser_accepts():
from bandsaunter.cli import build_parser
known = set()
for action in build_parser()._subparsers._group_actions[0].choices[
"aprs"]._actions:
known.update(action.option_strings)
for option in ap.OPTIONS:
for flag in option.flags + option.off_flags:
assert flag in known, f"{flag} is in the table and not the parser"
def test_the_options_survive_being_saved_and_read_back(tmp_path):
options = ap.AprsOptions(units="imperial", region="europe", hold=90.0,
location="51.5,-0.1", digipeated=False)
ap.save_options(options, tmp_path)
assert ap.load_options(tmp_path) == options
def test_a_settings_file_with_a_mistake_in_it_costs_the_defaults(tmp_path):
(tmp_path / "aprs.yaml").write_text("units: [not a unit\n")
assert ap.load_options(tmp_path) == ap.AprsOptions()
@pytest.mark.parametrize("options,broken", [
(ap.AprsOptions(rate=48_000.0), "sample rate"),
(ap.AprsOptions(seconds=-1.0), "negative"),
(ap.AprsOptions(hold=0.0), "display"),
(ap.AprsOptions(frequency=10.0), "frequency"),
])
def test_a_setting_that_cannot_work_is_refused(options, broken):
assert any(broken in err for err in options.validate())
def test_the_defaults_are_all_workable():
assert ap.AprsOptions().validate() == []
@pytest.mark.parametrize("region,megahertz", [
("north-america", 144.390), ("europe", 144.800), ("australia", 145.175),
])
def test_each_region_has_its_own_channel(region, megahertz):
assert ap.channel_named(region) == pytest.approx(megahertz * 1e6)
def test_an_unknown_region_falls_back_rather_than_failing():
"""Refusing to listen over a misspelt region would be the wrong trade."""
assert ap.channel_named("narnia") == ax25.APRS_HZ
def test_the_region_sets_the_frequency_unless_one_was_given():
from bandsaunter.cli import build_parser
args = build_parser().parse_args(["aprs", "--region", "europe"])
assert args.region == "europe" and args.frequency is None
args = build_parser().parse_args(["aprs", "--region", "europe",
"--freq", "144900000"])
assert args.frequency == 144_900_000.0
# ---------------------------------------------------------------------------
# How far off, and which way
# ---------------------------------------------------------------------------
def test_a_distance_is_the_great_circle_one():
london, paris = (51.5074, -0.1278), (48.8566, 2.3522)
assert ap.distance_km(london, paris) == pytest.approx(343.0, abs=5.0)
assert ap.bearing_deg(london, paris) == pytest.approx(148.0, abs=3.0)
def test_a_station_at_the_aerial_is_no_distance_away():
here = (47.55, -122.30)
assert ap.distance_km(here, here) == pytest.approx(0.0, abs=0.001)
def test_distances_are_only_worked_out_when_there_is_somewhere_to_measure_from():
station = ap.Station(call="W1AW")
station.add(packet())
assert station.away(None) is None
assert station.away((47.55, -122.30))[0] > 0
@pytest.mark.parametrize("text,ok", [
("47.55,-122.30", True), ("47.55, -122.30", True), ("", False),
("nowhere", False), ("91,0", False), ("0,181", False),
])
def test_a_location_that_is_not_one_is_refused(text, ok):
assert (ap.coordinates(text) is not None) is ok
# ---------------------------------------------------------------------------
# Who is out there
# ---------------------------------------------------------------------------
def test_a_station_keeps_the_latest_of_each_kind_and_not_the_latest_packet():
"""A station sends a position, then a status, then weather; a display
showing only the newest packet loses two of the three every time."""
net = ap.Net()
net.add(packet(at=1_000.0))
net.add(packet(">Monitoring 146.52", at=1_016.0))
station = net.stations["W1AW-9"]
assert station.position is not None # kept from the first
assert station.status == "Monitoring 146.52"
assert station.packets == 2
def test_a_moving_station_keeps_a_track_and_a_still_one_does_not_repeat_itself():
net = ap.Net()
for i in range(5):
net.add(packet(packets.position_report(49.0 + i * 0.01, -72.0, "/>"),
at=1_000.0 + i * 20))
assert len(net.stations["W1AW-9"].track) == 5
for i in range(5):
net.add(packet(packets.position_report(49.0, -72.0, "/-"),
source="KU0W", at=2_000.0 + i * 20))
assert len(net.stations["KU0W"].track) == 1
def test_a_track_cannot_grow_without_limit():
# A step of a thousandth of a degree, which is coarser than the
# hundredth of a minute the format resolves to -- a finer one would be
# rounded to the same place and correctly not recorded twice.
net = ap.Net()
for i in range(ap.TRACK_POINTS + 50):
net.add(packet(packets.position_report(49.0 + i * 0.001, -72.0),
at=1_000.0 + i))
assert len(net.stations["W1AW-9"].track) == ap.TRACK_POINTS
def test_a_station_that_has_not_moved_is_not_recorded_as_having_moved():
"""Two packets from the same place are one point, not two."""
net = ap.Net()
for i in range(6):
net.add(packet(packets.position_report(49.0, -72.0),
at=1_000.0 + i * 60))
assert len(net.stations["W1AW-9"].track) == 1
def test_a_packet_that_arrived_through_a_digipeater_is_counted_apart():
"""Most of what a receiver hears is a hilltop repeating somebody, which
is the whole design; what was heard directly is the honest measure of
what the aerial can reach."""
net = ap.Net()
net.add(packet(at=1_000.0, path=("WIDE1-1*", "WIDE2-1")))
net.add(packet(at=1_060.0, path=()))
station = net.stations["W1AW-9"]
assert station.packets == 2 and station.direct == 1
def test_an_object_is_filed_under_its_own_name_not_its_senders():
net = ap.Net()
net.add(packet(packets.object_report("LEADER", 49.0, -72.0),
source="W1AW-9", at=1_000.0))
assert "LEADER" in net.stations and "W1AW-9" not in net.stations
assert net.stations["LEADER"].object_of == "W1AW-9"
def test_messages_are_kept_in_order_as_a_conversation():
net = ap.Net()
net.add(packet(packets.message_text("KU0W", "first"), at=1_000.0))
net.add(packet(packets.message_text("W1AW", "second"), source="KU0W",
at=1_060.0))
assert [m.message.text for m in net.messages] == ["first", "second"]
def test_a_station_that_has_gone_quiet_leaves_the_display_but_not_the_log():
net = ap.Net()
net.add(packet(at=1_000.0))
assert len(net.showing(300.0, now=1_200.0)) == 1
assert len(net.showing(300.0, now=1_400.0)) == 0
assert len(net.all()) == 1
def test_the_newest_station_is_at_the_top():
"""The opposite of the other displays, and deliberately: what somebody
watching a busy channel wants to know is what just came in."""
net = ap.Net()
net.add(packet(source="OLD", at=1_000.0))
net.add(packet(source="NEW", at=2_000.0))
assert [s.call for s in net.showing(1e6, now=2_000.0)] == ["NEW", "OLD"]
def test_a_net_can_be_rebuilt_from_a_log():
heard = [packet(at=1_000.0), packet(source="KU0W", at=1_001.0)]
assert {s.call for s in ap.Net.of(heard).all()} == {"W1AW-9", "KU0W"}
# ---------------------------------------------------------------------------
# The log
# ---------------------------------------------------------------------------
def test_a_packet_survives_being_written_and_read_back(tmp_path):
log = al.AprsLog(tmp_path / "aprs_x.jsonl", frequency=ax25.APRS_HZ)
sent = packet(path=("WIDE1-1*",))
log.append(sent, ax25.frame_from(ax25.frame_bytes("W1AW-9", "APRS",
sent.info)))
log.close()
back = al.read_logs([log.path])
assert len(back) == 1
got = back[0]
assert got.source == "W1AW-9" and got.kind == "position"
assert got.position.latitude == pytest.approx(49.0583, abs=0.0002)
assert got.course == 88 and got.path == ("WIDE1-1*",)
assert got.snr == pytest.approx(20.0)
def test_the_whole_frame_goes_down_underneath_whatever_was_understood(tmp_path):
"""APRS has a long tail of formats, so a packet this version cannot read
is kept in full for a version that can."""
log = al.AprsLog(tmp_path / "aprs_x.jsonl")
raw = ax25.frame_bytes("W1AW", "APRS", "!!! not a format !!!")
frame = ax25.frame_from(raw)
log.append(packets.parse(frame), frame)
log.close()
body = json.loads(log.path.read_text().splitlines()[1])
assert bytes.fromhex(body["hex"]) == raw
assert body["kind"] == "unparsed"
assert body["info"] == "!!! not a format !!!"
def test_weather_and_messages_survive_the_log(tmp_path):
log = al.AprsLog(tmp_path / "aprs_x.jsonl")
log.append(packet("@092345z4903.50N/07201.75W_220/004g005t077h50b09900",
source="KB1XYZ"))
log.append(packet(packets.message_text("KU0W", "on my way", "7")))
log.close()
back = al.read_logs([log.path])
assert back[0].weather["temperature"].value == pytest.approx(25.0, abs=0.1)
assert back[1].message.to == "KU0W" and back[1].message.number == "7"
def test_a_half_written_last_line_costs_that_line_and_not_the_evening(tmp_path):
log = al.AprsLog(tmp_path / "aprs_x.jsonl")
for i in range(5):
log.append(packet(at=1_000.0 + i))
log.close()
with open(log.path, "a") as fh:
fh.write('{"t": 9, "src": "W1A')
assert len(al.read_logs([log.path])) == 5
def test_the_header_line_is_not_read_back_as_a_packet(tmp_path):
log = al.AprsLog(tmp_path / "aprs_x.jsonl", receiver="device 0")
log.close()
head = json.loads(log.path.read_text().splitlines()[0])
assert head["log"] == "bandsaunter-aprs"
assert al.read_logs([log.path]) == []
def test_a_log_is_written_as_it_goes_and_not_when_it_closes(tmp_path):
log = al.AprsLog(tmp_path / "aprs_x.jsonl")
log.append(packet())
assert len(log.path.read_text().splitlines()) == 2
log.close()
# ---------------------------------------------------------------------------
# Out to a spreadsheet and a globe
# ---------------------------------------------------------------------------
def test_the_spreadsheet_has_a_column_for_everything_anything_reported(tmp_path):
heard = [packet(at=1_000.0),
packet("@092345z4903.50N/07201.75W_220/004g005t077h50b09900",
source="KB1XYZ", at=1_001.0)]
where = al.write_csv(tmp_path / "a.csv", heard)
head = where.read_text().splitlines()[0].split(",")
assert "latitude" in head and "speed (km/h)" in head
assert any(h.startswith("temperature") for h in head)
def test_the_spreadsheet_can_be_written_the_other_way_round(tmp_path):
heard = [packet("@092345z4903.50N/07201.75W_220/004t032", source="KB1XYZ",
at=1_000.0)]
where = al.write_csv(tmp_path / "a.csv", heard, imperial=True)
head, row = where.read_text().splitlines()[:2]
columns = head.split(",")
assert "temperature (F)" in columns
assert row.split(",")[columns.index("temperature (F)")] == "32.0"
def test_a_map_has_a_pin_for_every_station_and_a_line_for_what_moved(tmp_path):
heard = [packet(packets.position_report(49.0 + i * 0.01, -72.0, "/>"),
at=1_000.0 + i * 20) for i in range(4)]
heard.append(packet(packets.position_report(50.0, -73.0), source="KU0W",
at=1_100.0))
where = al.write_kml(tmp_path / "a.kml", heard)
text = where.read_text()
assert text.count("<Placemark>") == 3 # a track and two pins
assert "<LineString>" in text and "W1AW-9" in text and "KU0W" in text
def test_a_map_of_stations_that_never_said_where_they_were_is_not_drawn(tmp_path):
"""A pin at nowhere puts a station off the west coast of Africa."""
heard = [packet(">Monitoring 146.52", at=1_000.0)]
assert al.write_kml(tmp_path / "a.kml", heard) is None
# ---------------------------------------------------------------------------
# Listening
# ---------------------------------------------------------------------------
class Silence:
"""A receiver that hears nothing, for testing the loop rather than the air."""
def __init__(self, blocks=2):
self.blocks = blocks
self.tuned = 0.0
def tune(self, hz, settle=True):
self.tuned = hz
return int(hz)
def read_samples(self, count, flush=False):
if self.blocks <= 0:
return np.zeros(0, dtype=np.complex64)
self.blocks -= 1
return np.zeros(count, dtype=np.complex64)
def close(self):
return None
class Channel:
"""The invented channel, wrapped so a test can drive it a block at a time."""
def __init__(self, blocks, rate=RATE, seed=3):
self.sky = ap.SimulatedChannel(sample_rate=rate, seed=seed)
self.left = blocks
def tune(self, hz, settle=True):
return int(hz)
def read_samples(self, count, flush=False):
if self.left <= 0:
return np.zeros(0, dtype=np.complex64)
self.left -= 1
return self.sky.read_samples(count)
def close(self):
return None
def test_the_receiver_is_tuned_to_the_channel():
device = Silence()
ap.pump(device, ap.AprsOptions(rate=RATE, region="europe",
frequency=ap.channel_named("europe")),
ap.Net(), None, time.time())
assert device.tuned == pytest.approx(144_800_000.0)
def test_listening_stops_when_the_receiver_does():
device = Silence(blocks=3)
assert ap.pump(device, ap.AprsOptions(rate=RATE), ap.Net(), None,
time.time()) == 0
assert device.blocks == 0
def test_a_whole_session_hears_the_invented_channel(tmp_path, monkeypatch):
monkeypatch.setattr(ap, "open_device",
lambda console, opts: Channel(120))
options = ap.AprsOptions(rate=RATE, simulate=True, packets_seen=True,
csv=True, kml=True, report=False)
console = Console(width=120, force_terminal=False)
with console.capture():
heard = ap.listen(console, options, str(tmp_path))
assert heard.stations >= 4
assert heard.log_path.exists() and heard.csv_path.exists()
assert heard.kml_path.exists()
assert len(al.read_logs([heard.log_path])) == heard.packets
kinds = {s.kind for s in heard.net.all()}
assert {"position", "weather", "object"} <= kinds
assert heard.net.messages
def test_a_transmission_that_straddles_a_block_is_still_heard():
"""A packet is most of a second and a block is about one, so this is not
an edge case -- it is most of them. A simulated clock advancing in exact
seconds hides it by putting every transmission at a block boundary.
"""
sky = ap.SimulatedChannel(sample_rate=RATE, seed=3)
demod, receiver = ap.make_receiver(ap.AprsOptions(rate=RATE))
found = 0
for _ in range(50):
# Blocks of an awkward length, so nothing lines up.
audio, _iq = demod.step(sky.read_samples(int(RATE * 0.77)))
found += len(receiver.feed(audio))
assert found >= 3, "transmissions are being cut off at the block boundary"
def test_relayed_packets_can_be_left_out(tmp_path, monkeypatch):
monkeypatch.setattr(ap, "open_device", lambda console, opts: Channel(120))
console = Console(width=120, force_terminal=False)
options = ap.AprsOptions(rate=RATE, packets_seen=True, log=False,
report=False, digipeated=False)
with console.capture():
heard = ap.listen(console, options, str(tmp_path))
for station in heard.net.all():
assert station.direct == station.packets
def test_a_receiver_that_will_not_open_is_a_message_and_not_a_traceback(
tmp_path, monkeypatch):
monkeypatch.setattr(ap, "open_device", lambda console, opts: None)
console = Console(width=120, force_terminal=False)
with console.capture():
heard = ap.listen(console, ap.AprsOptions(), str(tmp_path))
assert heard.stations == 0 and heard.log_path is None
def test_hearing_nothing_says_what_to_check(tmp_path, monkeypatch):
monkeypatch.setattr(ap, "open_device", lambda console, opts: Silence(2))
console = Console(width=120, force_terminal=False)
with console.capture() as cap:
ap.listen(console, ap.AprsOptions(rate=RATE, packets_seen=True,
log=False), str(tmp_path))
assert "region" in cap.get()
# ---------------------------------------------------------------------------
# The report and the display
# ---------------------------------------------------------------------------
def rendered(net, options=None):
console = Console(width=130, force_terminal=False)
with console.capture() as cap:
ap.report(console, net, options or ap.AprsOptions())
return cap.get()
def test_the_report_says_who_was_heard_and_what_they_said():
net = ap.Net()
net.add(packet(at=1_000.0))
net.add(packet("@092345z4903.50N/07201.75W_220/004g005t077h50b09900",
source="KB1XYZ", at=1_001.0))
net.add(packet(packets.message_text("KU0W", "on my way"), at=1_002.0))
out = rendered(net)
assert "W1AW-9" in out and "KB1XYZ" in out
assert "stations heard" in out and "what they said" in out
assert "what passed between them" in out
assert "on my way" in out
def test_the_report_shows_distances_only_when_it_knows_where_the_aerial_is():
net = ap.Net()
net.add(packet(at=1_000.0))
assert "away" not in rendered(net)
assert "away" in rendered(net, ap.AprsOptions(location="47.55,-122.30"))
def test_the_report_counts_what_it_could_not_read():
net = ap.Net()
net.add(packet("!!! not a format !!!", at=1_000.0))
assert "cannot read" in rendered(net)
@pytest.mark.parametrize("level,colour", [
(4.0, "red"), (12.0, "yellow"), (24.0, "green"),
])
def test_the_signal_is_coloured_so_an_aerial_can_be_aimed_by_it(level, colour):
assert colour in ap.signal_text(level)
def test_no_signal_is_shown_as_nothing_rather_than_as_zero():
assert ap.signal_text(0.0) == ""
def shown(net, width=120, now=None, **kw):
console = Console(width=width, force_terminal=False)
display = AprsDisplay(console, **kw)
display.started = (now or time.time()) - 60
display.update(net, net.packets)
with console.capture() as cap:
console.print(display.render(now=now))
return cap.get()
def test_the_display_shows_a_station_and_what_it_last_said():
net = ap.Net()
now = time.time()
net.add(packet(at=now))
out = shown(net, now=now)
assert "W1AW-9" in out and "49.0583N" in out and "144.39 MHz" in out
def test_the_display_still_fits_a_narrow_terminal():
net = ap.Net()
now = time.time()
net.add(packet(at=now))
for width in (60, 70, 86, 100, 140):
out = shown(net, width=width, now=now, home=(47.55, -122.30))
assert max(len(line) for line in out.splitlines()) <= width
assert "W1AW-9" in out
def test_an_empty_display_says_what_to_check():
assert "region" in shown(ap.Net())
# ---------------------------------------------------------------------------
# The command line and the menu
# ---------------------------------------------------------------------------
def test_reading_a_log_back_prints_it_and_writes_the_files(tmp_path,
monkeypatch):
from bandsaunter.cli import build_parser, cmd_packets
import bandsaunter.cli as cli
log = tmp_path / "aprs_x.jsonl"
with al.AprsLog(log) as fh:
for i in range(4):
fh.append(packet(packets.position_report(49.0 + i * 0.01, -72.0),
at=1_000.0 + i * 20))
console = Console(width=130, force_terminal=False)
monkeypatch.setattr(cli, "console", console)
args = build_parser().parse_args(["packets", str(log), "--csv", "--kml"])
with console.capture() as cap:
assert cmd_packets(args) == 0
assert "W1AW-9" in cap.get()
assert log.with_suffix(".csv").exists() and log.with_suffix(".kml").exists()
def test_reading_a_log_back_can_be_narrowed_to_one_station(tmp_path,
monkeypatch):
from bandsaunter.cli import build_parser, cmd_packets
import bandsaunter.cli as cli
log = tmp_path / "aprs_x.jsonl"
with al.AprsLog(log) as fh:
fh.append(packet(at=1_000.0))
fh.append(packet(source="KU0W", at=1_001.0))
console = Console(width=130, force_terminal=False)
monkeypatch.setattr(cli, "console", console)
args = build_parser().parse_args(["packets", str(log), "--station", "KU0W"])
with console.capture() as cap:
assert cmd_packets(args) == 0
out = cap.get()
assert "KU0W" in out and "W1AW-9" not in out
def test_asking_for_a_log_that_is_not_there_is_a_message(tmp_path,
monkeypatch):
from bandsaunter.cli import build_parser, cmd_packets
import bandsaunter.cli as cli
console = Console(width=120, force_terminal=False)
monkeypatch.setattr(cli, "console", console)
args = build_parser().parse_args(["packets", str(tmp_path / "no.jsonl")])
with console.capture() as cap:
assert cmd_packets(args) == 1
assert "no such file" in cap.get()
def test_the_menu_can_be_opened_and_left(monkeypatch):
import bandsaunter.tui as tui
from bandsaunter.config import ScanConfig
answers = iter(["b"])
monkeypatch.setattr(tui, "_ask",
lambda console, prompt, default="": next(answers))
console = Console(width=120, force_terminal=False)
with console.capture() as cap:
tui.aprs_menu(console, ScanConfig())
out = cap.get()
assert "144.390 MHz" in out
for group in ap.OPTION_GROUPS:
assert group.lower() in out
def test_one_set_of_option_screens_drives_all_three_sections():
import bandsaunter.tui as tui
from bandsaunter import aircraft, weather
for module in (aircraft, weather, ap):
assert tui._section(module) is module
assert callable(module.defaults)
assert module.OPTION_GROUPS and module.OPTIONS

260
tests/test_ax25.py Normal file
View file

@ -0,0 +1,260 @@
"""AX.25: the frames APRS rides in, and getting them off the air.
Every frame here is built by the encoder that sits beside the decoder, keyed
out as real Bell 202 audio, and read back. That proves the framing, the bit
stuffing, the NRZI, the checksum and the clock recovery; it does not prove
anything a description and an implementation of it might both get wrong, and
the module says so.
The other half is about what must not be read. This runs for hours with the
squelch open, so a frame either satisfies sixteen bits of CRC or it never
existed.
"""
import numpy as np
import pytest
from bandsaunter import ax25
RATE = 22_050.0
def heard(frames, rate=RATE, chunk=None, noise=0.02, amplitude=0.5):
"""Frames keyed out and read back, optionally a block at a time."""
if isinstance(frames, (bytes, bytearray)):
frames = [frames]
audio = ax25.modulate(frames, rate, amplitude=amplitude, noise=noise)
receiver = ax25.Receiver(rate)
if chunk is None:
return receiver.feed(audio, when=1_000.0)
out = []
for i in range(0, audio.size, chunk):
out += receiver.feed(audio[i:i + chunk], when=1_000.0)
return out
# ---------------------------------------------------------------------------
# What a frame is made of
# ---------------------------------------------------------------------------
def test_a_frame_comes_back_with_everything_it_was_sent_with():
raw = ax25.frame_bytes("W1AW-5", "APRS", "=4123.45N/07203.12W-hi",
path=("WIDE1-1*", "WIDE2-1"))
frame = ax25.frame_from(raw)
assert frame is not None
assert frame.source.plain == "W1AW-5" and frame.source.ssid == 5
assert frame.destination.plain == "APRS"
assert [str(h) for h in frame.path] == ["WIDE1-1*", "WIDE2-1"]
assert frame.text() == "=4123.45N/07203.12W-hi"
assert frame.route() == "W1AW-5>APRS,WIDE1-1*,WIDE2-1"
def test_a_station_with_no_ssid_is_written_without_one():
frame = ax25.frame_from(ax25.frame_bytes("W1AW", "APRS", "x"))
assert frame.source.plain == "W1AW"
assert str(frame.source) == "W1AW"
@pytest.mark.parametrize("ssid", range(16))
def test_every_ssid_survives(ssid):
call = f"KU0W-{ssid}" if ssid else "KU0W"
frame = ax25.frame_from(ax25.frame_bytes(call, "APRS", "x"))
assert frame.source.ssid == ssid
assert frame.source.plain == call
def test_a_digipeater_that_has_repeated_a_frame_says_so():
"""The H bit, which is how the path records where a frame has been.
The hops with it set are where the frame went; the rest are where it was
asked to go and has not been yet.
"""
frame = ax25.frame_from(ax25.frame_bytes(
"W1AW", "APRS", "x", path=("WIDE1-1*", "WIDE2-1")))
assert [str(h) for h in frame.heard_through] == ["WIDE1-1*"]
assert frame.path[0].repeated and not frame.path[1].repeated
def test_the_frame_type_apris_uses_is_recognised_and_others_are_named():
ui = ax25.frame_from(ax25.frame_bytes("W1AW", "APRS", "x"))
assert ui.unnumbered_information and ui.kind == "unnumbered information"
other = ax25.frame_from(ax25.frame_bytes("W1AW", "APRS", "x",
control=0x2F, pid=0xF0))
assert not other.unnumbered_information
assert other.kind == "set async balanced"
def test_a_frame_with_a_broken_check_is_refused():
raw = bytearray(ax25.frame_bytes("W1AW", "APRS", "hello"))
for i in range(len(raw)):
broken = bytearray(raw)
broken[i] ^= 0x01
assert ax25.frame_from(bytes(broken)) is None, f"byte {i} got through"
def test_a_frame_whose_addresses_are_not_callsigns_is_refused():
"""Sixteen bits of CRC is strong and this band is busy.
A frame whose addresses are unprintable passed the check by accident,
and there is no reason to put it on a display.
"""
raw = bytearray(ax25.frame_bytes("W1AW", "APRS", "x"))
raw[0] = 0x02 # an unprintable callsign
body = bytes(raw[:-2])
check = ax25.fcs(body)
assert ax25.frame_from(body + bytes([check & 0xFF, check >> 8])) is None
def test_a_frame_too_short_to_be_one_is_refused():
assert ax25.frame_from(b"") is None
assert ax25.frame_from(b"\x00" * 10) is None
@pytest.mark.parametrize("info", ["", "x", "!" * 256, "\x00\xff binary"])
def test_an_information_field_of_any_shape_survives(info):
frame = ax25.frame_from(ax25.frame_bytes("W1AW", "APRS", info))
assert frame is not None and frame.text() == info
# ---------------------------------------------------------------------------
# HDLC
# ---------------------------------------------------------------------------
def test_a_zero_is_stuffed_after_five_ones_and_taken_back_out():
assert ax25.stuff("11111" + "1") == "111110" + "1"
assert ax25.unstuff(ax25.stuff("1" * 40)) == "1" * 40
assert ax25.stuff("0" * 40) == "0" * 40
def test_stuffing_is_what_stops_a_flag_appearing_inside_a_frame():
assert ax25.FLAG not in ax25.stuff("0" + ax25.FLAG + "0")
def test_nrzi_is_the_same_data_read_from_either_polarity():
"""A zero is a change of tone and a one is no change, so inverting the
whole stream -- swapping mark for space, or wiring a discriminator up
backwards -- decodes to exactly the same bits. Nothing here ever has to
guess at polarity, and that is why."""
bits = "110100111000101"
sent = ax25.nrzi(bits)
upside_down = "".join("1" if b == "0" else "0" for b in sent)
assert ax25.un_nrzi("1" + sent) == bits
assert ax25.un_nrzi("0" + upside_down) == bits
def test_a_stream_is_consumed_up_to_the_last_flag_and_no_further():
"""What a caller reading a continuous signal may forget.
Trimming to before a frame that has already been reported hands it back
on the next block, and every packet is counted twice for ever.
"""
raw = ax25.frame_bytes("W1AW", "APRS", "hello")
bits = ax25.bits_of(raw, flags=2)
frames, used = ax25.hdlc_frames(bits)
assert frames == [raw]
assert used > 0
again, _ = ax25.hdlc_frames(bits[used:])
assert again == []
def test_a_frame_still_arriving_is_kept_rather_than_thrown_away():
raw = ax25.frame_bytes("W1AW", "APRS", "hello")
bits = ax25.bits_of(raw, flags=2)
half = bits[:len(bits) // 2]
frames, used = ax25.hdlc_frames(half)
assert frames == []
rest, _ = ax25.hdlc_frames(half[used:] + bits[len(bits) // 2:])
assert rest == [raw]
# ---------------------------------------------------------------------------
# Off the air
# ---------------------------------------------------------------------------
def test_a_packet_survives_being_keyed_out_and_read_back():
raw = ax25.frame_bytes("W1AW-5", "APRS", "=4123.45N/07203.12W-hi",
path=("WIDE1-1*",))
got = heard(raw)
assert [f.raw for f in got] == [raw]
assert got[0].at == 1_000.0
@pytest.mark.parametrize("chunk", [220, 1_102, 2_205, 11_025, 44_100])
def test_a_packet_is_read_once_however_the_audio_is_cut_into_blocks(chunk):
"""A packet is most of a second and a block is about one, so a frame
straddling the boundary is not an edge case -- it is most of them."""
raw = ax25.frame_bytes("W1AW-5", "APRS", "=4123.45N/07203.12W-hi")
got = heard(raw, chunk=chunk)
assert [f.raw for f in got] == [raw], f"{len(got)} frames at {chunk}"
def test_several_packets_back_to_back_all_come_through():
raws = [ax25.frame_bytes("W1AW", "APRS", f">beacon {i}") for i in range(4)]
got = heard(raws, chunk=2_205)
assert [f.text() for f in got] == [f">beacon {i}" for i in range(4)]
@pytest.mark.parametrize("rate", [11_025.0, 22_050.0, 24_000.0, 48_000.0])
def test_it_works_at_the_audio_rates_a_demodulator_might_hand_over(rate):
raw = ax25.frame_bytes("W1AW", "APRS", "=4123.45N/07203.12W-")
assert [f.raw for f in heard(raw, rate=rate, chunk=int(rate // 10))] == [raw]
def test_a_weak_packet_is_still_read():
raw = ax25.frame_bytes("W1AW", "APRS", "=4123.45N/07203.12W-")
got = heard(raw, noise=0.2, amplitude=0.5) # about 8 dB
assert [f.raw for f in got] == [raw]
def test_nothing_is_read_out_of_noise():
rng = np.random.default_rng(1)
for _ in range(80):
receiver = ax25.Receiver(RATE)
assert receiver.feed(rng.normal(0.0, 0.3, int(RATE))) == []
def test_a_receiver_can_be_reset_and_carries_nothing_over():
raw = ax25.frame_bytes("W1AW", "APRS", "hello")
audio = ax25.modulate(raw, RATE, noise=0.02)
receiver = ax25.Receiver(RATE)
receiver.feed(audio[:audio.size // 2])
receiver.reset()
assert receiver.feed(audio[audio.size // 2:]) == []
def test_the_receiver_counts_what_it_has_seen():
raw = ax25.frame_bytes("W1AW", "APRS", "hello")
receiver = ax25.Receiver(RATE)
receiver.feed(ax25.modulate(raw, RATE, noise=0.02))
assert receiver.frames == 1
assert receiver.bytes_seen >= len(raw)
# ---------------------------------------------------------------------------
# Where APRS is
# ---------------------------------------------------------------------------
def test_every_region_has_a_channel_and_they_are_all_different():
frequencies = [hz for _key, hz, _where in ax25.APRS_CHANNELS]
assert len(set(frequencies)) == len(frequencies)
assert all(144e6 < hz < 146e6 for hz in frequencies)
assert ax25.APRS_CHANNELS[0][1] == ax25.APRS_HZ == 144_390_000.0
def test_a_block_holding_more_frames_than_one_pass_takes_repeats_none():
"""The framer returns at most so many at a time, and says how far it got.
If it stopped at the limit without saying it had consumed the frames it
just returned, the caller would keep them and hand them back on the next
pass -- every packet in a busy second counted twice.
"""
raws = [ax25.frame_bytes("W1AW", "APRS", f">beacon {i}") for i in range(9)]
bits = "".join(ax25.bits_of(raw, flags=2) for raw in raws)
seen, at = [], 0
for _ in range(6):
frames, used = ax25.hdlc_frames(bits[at:], most=3)
if not frames:
break
seen += frames
at += used
assert seen == raws, f"{len(seen)} frames out of {len(raws)}"

View file

@ -42,11 +42,13 @@ def test_every_setting_explains_itself_in_plain_words(page):
def test_the_commands_and_the_keys_are_documented(page):
for word in ("scan", "bands", "config", "transcribe", "devices",
"profiles", "analyze", "weather", "readings", "sensors"):
"profiles", "analyze", "weather", "readings", "sensors",
"aprs", "packets"):
assert f".B {word}\n" in page, f"command {word} undocumented"
for section in ("SYNOPSIS", "DESCRIPTION", "COMMANDS", "OPTIONS",
"SETTINGS", "FILES", "ENVIRONMENT", "EXAMPLES",
"AIRCRAFT OPTIONS", "WEATHER SENSORS", "WEATHER OPTIONS"):
"AIRCRAFT OPTIONS", "WEATHER SENSORS", "WEATHER OPTIONS",
"APRS", "APRS OPTIONS"):
assert f".SH {section}" in page
@ -161,8 +163,20 @@ def test_the_manual_lists_every_weather_option(page):
assert option.key in page, f"{option.key} is not named in the manual"
def test_the_manual_lists_every_aprs_option(page):
"""The same again, for the third section, from the third table."""
from bandsaunter import aprs as ap
for option in ap.OPTIONS:
flags = tuple(option.flags) + tuple(option.off_flags)
assert any(flag in page for flag in flags), \
f"{option.key} ({', '.join(flags)}) is not in the manual"
assert option.key in page, f"{option.key} is not named in the manual"
def test_the_manual_says_where_the_sensor_names_are_kept(page):
"""They are the only thing this program stores that somebody typed."""
assert "sensors.yaml" in page
assert "weather.yaml" in page
assert "weather_" in page
assert "aprs.yaml" in page and "aprs_" in page

365
tests/test_packets.py Normal file
View file

@ -0,0 +1,365 @@
"""The APRS information field: about twenty formats, and what must not happen.
Every format here has a writer beside its reader, so a position goes in and
the same position comes out. That proves the arithmetic and the framing and
proves nothing about anything the specification and this both get wrong --
which is worth saying, because the last section of this program shipped
unable to decode anything at all for exactly that reason.
The other half is about refusing to guess. A packet whose format does not
match what its first character promised comes back as unparsed, with its text
intact, rather than as a confident position a thousand miles from where the
station is.
"""
import math
import pytest
from bandsaunter import packets as p
# Every quadrant, the prime meridian, the equator, and the longitudes either
# side of the boundaries Mic-E re-maps to keep its bytes printable.
PLACES = [
(49.0583, -72.0292), (-33.8688, 151.2093), (51.5074, -0.1278),
(35.6762, 139.6503), (5.0, -5.0), (0.0, 0.0), (-45.0, -179.5),
(64.1466, -21.9426), (-1.2921, 36.8219), (47.55, -122.30),
]
# ---------------------------------------------------------------------------
# Positions
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("latitude,longitude", PLACES)
def test_an_uncompressed_position_comes_back_where_it_was_sent(latitude,
longitude):
info = p.position_report(latitude, longitude, "/>", "hello")
packet = p.parse_info(info)
assert packet.kind == "position"
assert packet.position.latitude == pytest.approx(latitude, abs=0.0002)
assert packet.position.longitude == pytest.approx(longitude, abs=0.0002)
assert packet.position.symbol == "car"
assert packet.comment == "hello"
@pytest.mark.parametrize("latitude,longitude", PLACES)
def test_a_compressed_position_comes_back_where_it_was_sent(latitude,
longitude):
packet = p.parse_info(p.compressed_report(latitude, longitude, "/>"))
assert packet.kind == "position"
assert packet.position.compressed
assert packet.position.latitude == pytest.approx(latitude, abs=0.0002)
assert packet.position.longitude == pytest.approx(longitude, abs=0.0002)
@pytest.mark.parametrize("latitude,longitude", PLACES)
def test_a_mic_e_position_comes_back_where_it_was_sent(latitude, longitude):
"""The awkward one: half of it lives in the destination callsign, and
the longitude is re-mapped in three ranges to keep the bytes printable."""
destination, info = p.mic_e_report(latitude, longitude, course=251,
speed=37.0, symbol="/j",
status="returning")
packet = p.parse_info(info, destination)
assert packet.kind == "position"
assert packet.position.latitude == pytest.approx(latitude, abs=0.0002)
assert packet.position.longitude == pytest.approx(longitude, abs=0.0002)
assert packet.course == 251
assert packet.speed == pytest.approx(37.0, abs=1.0)
assert packet.status == "returning"
assert packet.position.symbol == "jeep"
def test_the_compressed_position_from_the_specification_reads_correctly():
"""The example in the specification itself: 49 30.00 N, 72 45.00 W, with
a pre-computed radio range of 20.13 miles."""
packet = p.parse_info("!/5L!!<*e7>{?!")
assert packet.position.latitude == pytest.approx(49.5, abs=0.0001)
assert packet.position.longitude == pytest.approx(-72.75, abs=0.0001)
assert packet.range == pytest.approx(20.13 * 1.609344, rel=0.01)
@pytest.mark.parametrize("blanked,within_km", [(0, 0.0), (1, 0.34), (2, 3.4),
(3, 34.0), (4, 340.0)])
def test_a_station_that_blanks_its_minutes_is_not_drawn_as_a_point(blanked,
within_km):
"""Blanking the minute digits is a deliberate act by the operator.
Drawing a fuzzy position as a sharp one is a lie they specifically asked
not to be told, so the count is kept and turned into a distance.
"""
info = p.position_report(49.0583, -72.0292, "/-", ambiguity=blanked)
packet = p.parse_info(info)
assert packet.position.ambiguity == blanked
assert packet.position.uncertainty_km == within_km
@pytest.mark.parametrize("info", [
"=4760.37N/07201.75W-", # sixty minutes is not a minute
"=4903.50X/07201.75W-", # not a hemisphere
"=49 3.50N/07201.75W-", # a gap in the middle, not ambiguity
"=9903.50N/07201.75W-", # past the pole
"=4903.50N/19201.75W-", # past the antimeridian
])
def test_a_position_that_cannot_be_one_is_not_reported_as_a_position(info):
"""And in particular is not quietly re-read as a compressed position.
Thirteen characters of a malformed uncompressed position are perfectly
good base-91, so falling back does not fail -- it succeeds, as a
confident and completely different place.
"""
packet = p.parse_info(info)
assert packet.kind == "unparsed"
assert packet.position is None
assert packet.info == info # the text is kept regardless
def test_a_leading_digit_always_means_an_uncompressed_position():
"""Which is why the compressed format writes a numeric overlay as a
letter: so the two can never be confused by anything that reads the rule."""
overlaid = p.parse_info("!a5L!!<*e7> sT")
assert overlaid.position.table == "0" # the overlay, as a digit
assert overlaid.position.compressed
@pytest.mark.parametrize("timestamp", ["092345z", "092345/", "234500h"])
def test_a_position_with_a_timestamp_keeps_both(timestamp):
info = p.position_report(49.0583, -72.0292, "/-", timestamp=timestamp)
packet = p.parse_info(info, now=1_600_000_000.0)
assert packet.position is not None
assert packet.reported > 0.0
def test_a_timestamp_with_no_year_lands_on_the_nearest_side_of_today():
"""None of the four formats carries a year, so a packet stamped the
thirty-first heard on the first is from yesterday, not four weeks on."""
import calendar
now = calendar.timegm((2026, 3, 1, 0, 30, 0, 0, 0, 0))
when, _rest = p.timestamp_from("282345z", now)
assert now - when < 3 * 24 * 3600 # late February, not next year
assert when < now
# ---------------------------------------------------------------------------
# What rides in the comment
# ---------------------------------------------------------------------------
def test_a_course_and_speed_are_read_in_the_units_they_are_sent_in():
"""Knots here, which is not the same as the miles an hour a weather
report uses for wind, and the two differ by fifteen per cent."""
packet = p.parse_info(p.position_report(49.0, -72.0, "/>", course=88,
speed=66.672))
assert packet.course == 88
assert packet.speed == pytest.approx(66.672, abs=1.0)
def test_an_antenna_description_is_read_rather_than_shown_as_letters():
extra, rest = p.extensions_from("PHG5132Hi")
assert extra["power"] == 25 # watts, from a single digit
assert extra["height"] == pytest.approx(10.0 * 2 ** 1 * 0.3048, rel=0.01)
assert extra["gain"] == 3 and extra["beam"] == "E"
assert rest == "Hi"
def test_a_pre_computed_range_is_read():
extra, rest = p.extensions_from("RNG0050here")
assert extra["range"] == pytest.approx(50 * 1.609344, rel=0.01)
assert rest == "here"
def test_a_comment_that_is_only_a_comment_is_left_alone():
extra, rest = p.extensions_from("Hello there")
assert extra == {} and rest == "Hello there"
def test_an_altitude_is_pulled_out_of_wherever_in_the_comment_it_sits():
extra, rest = p.comment_from("climbing /A=012345 steadily")
assert extra["altitude"] == pytest.approx(12345 * 0.3048, rel=0.001)
assert "A=" not in rest and "climbing" in rest and "steadily" in rest
def test_an_altitude_is_shown_in_metres_and_not_rounded_to_a_kilometre():
"""Four hundred metres and the ground both read as "0 km", which is the
sort of rounding that makes a number worse than no number."""
assert p.height_text(376.0) == "376 m"
assert p.height_text(376.0, imperial=True) == "1,234 ft"
# ---------------------------------------------------------------------------
# Weather
# ---------------------------------------------------------------------------
def test_a_weather_report_with_a_position_reads_both():
info = "@092345z4903.50N/07201.75W_220/004g005t077r000p000P000h50b09900"
packet = p.parse_info(info)
assert packet.kind == "weather"
assert packet.position is not None
wx = packet.weather
assert wx["temperature"].value == pytest.approx(25.0, abs=0.1)
assert wx["humidity"].value == 50
assert wx["pressure"].value == pytest.approx(990.0, abs=0.1)
assert wx["wind from"].value == 220
assert wx["wind"].value == pytest.approx(4 * 1.852, abs=0.1)
def test_a_positionless_weather_report_reads_the_numbers():
packet = p.parse_info("_10090556c220s004g005t077r000p000P000h50b09900")
assert packet.kind == "weather" and packet.position is None
assert packet.weather["wind"].value == pytest.approx(4 * 1.609344, abs=0.1)
def test_the_letter_s_means_wind_speed_or_snow_depending_on_the_form():
"""The same letter, and the two differ by a factor of forty.
In a positionless report the wind arrives as "c" then "s"; in a position
report it arrives in the course-and-speed field, so a later "s" is
snowfall. Guessing is not an option.
"""
positionless = p.parse_info("_10090556c220s004g005t077")
assert "wind" in positionless.weather and "snow" not in positionless.weather
with_position = p.parse_info(
"@092345z4903.50N/07201.75W_220/004g005t077s010")
assert with_position.weather["snow"].value == pytest.approx(254.0, abs=1)
assert with_position.weather["wind"].value == pytest.approx(4 * 1.852,
abs=0.1)
def test_a_humidity_of_zero_means_a_hundred_per_cent():
packet = p.parse_info("_10090556c220s004g005t077h00")
assert packet.weather["humidity"].value == 100
def test_a_weather_report_comes_back_as_it_was_written():
info = p.weather_report(49.0583, -72.0292, timestamp="092345z",
wind_from=220, wind=7.4, gust=18.0,
temperature=25.0, humidity=50, pressure=990.0)
packet = p.parse_info(info)
assert packet.weather["temperature"].value == pytest.approx(25.0, abs=0.3)
assert packet.weather["humidity"].value == 50
assert packet.weather["pressure"].value == pytest.approx(990.0, abs=0.1)
# ---------------------------------------------------------------------------
# Messages, objects, items, status, telemetry
# ---------------------------------------------------------------------------
def test_a_message_reads_with_its_addressee_and_its_number():
packet = p.parse_info(p.message_text("KU0W", "on my way", number="42"))
assert packet.kind == "message"
assert packet.message.to == "KU0W"
assert packet.message.text == "on my way"
assert packet.message.number == "42"
@pytest.mark.parametrize("body,field,value", [
("ack42", "acknowledges", "42"),
("rej42", "rejects", "42"),
])
def test_an_acknowledgement_is_not_read_as_a_message_saying_ack(body, field,
value):
packet = p.parse_info(":W1AW :" + body)
assert getattr(packet.message, field) == value
assert packet.message.text == ""
def test_a_bulletin_is_addressed_to_everybody_and_says_so():
packet = p.parse_info(":BLN1 :Net tonight at eight")
assert packet.message.is_bulletin and packet.message.bulletin == "1"
assert "Net tonight" in packet.message.describe()
def test_an_object_carries_a_name_that_is_not_the_station_that_placed_it():
info = p.object_report("LEADER", 49.0583, -72.0292, "/>",
timestamp="092345z")
packet = p.parse_info(info)
assert packet.kind == "object"
assert packet.name == "LEADER"
assert packet.station == "LEADER" # the object, not the sender
assert packet.position.latitude == pytest.approx(49.0583, abs=0.0002)
assert packet.live
def test_an_object_can_be_killed():
info = p.object_report("LEADER", 49.0583, -72.0292, live=False)
assert p.parse_info(info).live is False
def test_an_item_is_an_object_without_a_timestamp():
packet = p.parse_info(p.item_report("AID", 49.0583, -72.0292))
assert packet.kind == "item" and packet.name == "AID"
assert packet.position is not None
def test_a_status_report_is_kept_as_what_the_operator_typed():
packet = p.parse_info(">Monitoring 146.52")
assert packet.kind == "status" and packet.status == "Monitoring 146.52"
def test_telemetry_reads_as_five_channels_and_eight_bits():
packet = p.parse_info(p.telemetry_report("005", [199, 0, 255, 73, 123],
"01101001"))
assert packet.kind == "telemetry"
assert packet.telemetry.analogue == (199.0, 0.0, 255.0, 73.0, 123.0)
assert packet.telemetry.digital == "01101001"
def test_a_relayed_packet_is_credited_to_whoever_originally_sent_it():
inner = p.position_report(49.0583, -72.0292, "/>")
packet = p.parse_info("}W1AW-5>APRS,TCPIP*:" + inner)
assert packet.source == "W1AW-5"
assert packet.position is not None
assert "relayed" in packet.comment
# ---------------------------------------------------------------------------
# Refusing to guess
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("info", [
"", "x", "!", "=short", ":notamessage", ";tooshort", "T#", ">",
"@notatimestamp", "}", "_", "`", "'",
])
def test_a_packet_that_cannot_be_read_keeps_its_text_and_says_so(info):
packet = p.parse_info(info)
assert packet.position is None
assert packet.info == info
assert packet.kind in p.KINDS
def test_nothing_is_read_out_of_random_text():
import random
rng = random.Random(4)
alphabet = "".join(chr(c) for c in range(32, 127))
placed = 0
for _ in range(4000):
info = "".join(rng.choice(alphabet) for _ in range(rng.randint(5, 60)))
packet = p.parse_info(info)
if packet.position is not None:
placed += 1
# Some random text really is a valid compressed position -- thirteen
# printable characters is all one takes -- so the bar is a rate. What
# reaches this off the air has also had to satisfy a sixteen-bit CRC.
assert placed <= 120, f"{placed} of 4000 random strings became a place"
# ---------------------------------------------------------------------------
# Symbols
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("table,code,name", [
("/", ">", "car"), ("/", "_", "weather station"), ("/", "#", "digipeater"),
("/", "O", "balloon"), ("\\", "s", "boat"), ("/", "[", "person"),
])
def test_a_station_is_described_by_what_it_draws_itself_as(table, code, name):
assert p.symbol_name(table, code) == name
def test_an_overlaid_symbol_says_which_character_is_over_it():
assert "(T)" in p.symbol_name("T", "#")
def test_a_symbol_nobody_named_is_reported_by_its_characters():
assert p.symbol_name("/", "\x01") == "symbol /\x01"