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

Four layers, three of them new.

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

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

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

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

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

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

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

524 lines
21 KiB
Python

"""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)