A new section, alongside the aircraft, the weather sensors and APRS. FT8 is the odd one out among the things this program listens to, and the reason is worth stating because it shapes everything below. Every station on the band transmits in the same quarter-minute slots, on the same dial frequency, fifty hertz wide each, stacked across three kilohertz of audio. One receiver parked on one frequency therefore hears the whole band's worth of stations at once -- and hears most of them well below the noise, because half of what is sent is error-correcting code. That is the entire trick: a rate of about one half buys a mode that decodes twenty-odd decibels under what an operator can hear. A receiver that took the loudest tone of each symbol and hoped would decode almost nothing, which is why the tone detector reports how confident it is bit by bit rather than what it thinks it heard. Written from first principles except for two tables. The checksum, the belief propagation over the sparse graph, the Costas sync search, the waterfall, the soft-bit metric, and the seventy-seven bits that hold two callsigns and a grid square are all here. The generator and the parity-check matrix are not: they cannot be derived, being the code itself rather than consequences of anything, so they are taken from ft8_lib under its MIT licence with the attribution it asks for, and said so in the readme, the manual and the file. No decoding logic came with them. That the two agree -- and they are not derivable from one another, the generator's parity half running to fifty-odd bits a row against the sparse matrix's six or seven -- is a test rather than an assumption. Tested against the air, not against itself. Eleven off-air recordings with published decodes: ninety-seven of a hundred and fifty messages, no false decodes, timing within a hundredth of a second, frequency within a hertz, signal reports within half a decibel on average. The third not decoded are the weakest in each slot; a mature decoder subtracts what it has decoded and looks again in the remainder, and does ordered-statistics decoding where belief propagation fails, and neither is built here. What is here decodes nothing that other receivers did not also hear, which is the property that matters in a log. Ten whole codewords lifted off the air are in the tests as a permanent fixture, so the recordings can go missing and the regression cannot. Three things that looked like bugs and were not, and three that were. The half-second timing discrepancy was the convention: a transmission is 12.64 seconds in a slot of fifteen and everybody starts half a second in, so lateness is reported against that. Synthetic signals at known offsets proved the clock self-consistent before anything was changed. The signal reports were twenty-one decibels optimistic because those recordings have a receiver passband above three kilohertz, putting a whole-band median twelve to sixteen decibels below the real noise floor -- so noise is now measured beside the signal, and in the tone that was actually sent rather than the loudest of eight, the largest of eight noisy numbers being well above their mean even with no signal at all. And the test transmitter was thirteen decibels pessimistic, scaling its noise into a fifty-hertz reference instead of the sampled bandwidth, which made the decoder look deaf when it was the test signal that had been quietly attenuated. The real bug the simulator caught was a one-block timestamp error: samples were dated a block earlier than they were taken, which slid every slot slice a second late and cut the first half-second -- three symbols, part of the opening Costas array -- off every transmission on the band. One decode a slot became six. Reachable both ways, as everything here is. Twenty-one options, every one of them a command-line flag and a line in the menu, both built from one table so they cannot disagree -- and a test that says so, since an option in no group would be settable from the command line and invisible in the menu. The band list says which channels a plain dongle can reach and which need an upconverter, because almost all the activity is on shortwave and finding that out by listening to silence for ten minutes is the wrong way to learn it. The default is two metres, which a plain dongle can hear. --grid turns decodes into geography: every CQ says where it is, so each gets a distance and a bearing and the furthest is named. --adif writes the log in the form every amateur logging program imports, marked as heard rather than worked, because nothing here transmits and an ADIF that let a logging program treat these as contacts would put claims into somebody's log that they cannot make. One bug shipped and found by being used rather than by being tested: the line that opens the receiver called a function this program has never had. Every test reached it through the simulator, which takes the other branch, so the one line that matters to somebody with an aerial was the one line never run. There is now a check that every name these modules import actually exists -- it names the missing one rather than failing somewhere downstream -- and two that say a receiver which cannot be opened is reported rather than raised, and that nothing claims to be listening before there is one. It had been announcing the frequency first, so a dongle that would not open read as listening that had gone wrong. Ninety-six new tests. Full suite 2781 passed. Built as 2026-09-21_04. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
712 lines
26 KiB
Python
712 lines
26 KiB
Python
"""What an FT8 transmission carries, and how it is wrapped.
|
|
|
|
No radio in here at all. This is the part between a string of one hundred
|
|
and seventy-four bits and a line somebody can read: the checksum, the
|
|
error-correcting code that makes FT8 work at signal levels where the
|
|
operator hears nothing, the Gray mapping onto eight tones, and the
|
|
seventy-seven bits that hold two callsigns and a grid square.
|
|
|
|
The shape of it, outward from the message:
|
|
|
|
77 bits what was said: two callsigns and a report, or free text
|
|
+ 14 bits a CRC, so a wrong answer is caught rather than printed
|
|
= 91 bits
|
|
+ 83 bits LDPC parity, so a wrong answer is usually *repaired*
|
|
= 174 bits
|
|
/ 3 three bits to a tone, in Gray order
|
|
= 58 tones
|
|
+ 21 tones three Costas arrays, at the start, the middle and the end
|
|
= 79 tones at 6.25 Hz apart and 6.25 to the second: 12.64 seconds
|
|
|
|
The error correction is the whole trick. Fifty-eight tones of payload
|
|
carried in one hundred and seventy-four bits is a rate of about one half:
|
|
half of what is transmitted is redundancy, and that is what buys a protocol
|
|
that decodes at twenty-odd decibels below the noise in the same bandwidth.
|
|
A receiver that only took the strongest tone in each symbol and hoped would
|
|
decode almost nothing -- which is why the tone detector below reports how
|
|
confident it is, bit by bit, rather than just what it thinks it heard.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
|
|
import numpy as np
|
|
|
|
from .ft8tables import (BITS, CHECKS, COSTAS, CRC_BITS, CRC_POLYNOMIAL,
|
|
GENERATOR, GRAY, PARITY, PAYLOAD, TONES)
|
|
|
|
__all__ = ["crc14", "with_crc", "crc_holds", "encode", "repair",
|
|
"parity_holds", "tones_of",
|
|
"bits_of", "unpack", "pack", "CallBook", "Message", "MESSAGE_BITS",
|
|
"SYMBOL_HZ", "SYMBOL_S", "SLOT_S", "SENDING_S", "COSTAS", "TONES",
|
|
"hash_of", "free_text", "is_standard_call"]
|
|
|
|
MESSAGE_BITS = 77 # what is actually said, before the checksum
|
|
|
|
# The channel, in numbers. Six and a quarter of everything: the tones are
|
|
# 6.25 Hz apart and there are 6.25 of them a second, which makes each tone
|
|
# exactly one cycle of separation long and the whole thing orthogonal.
|
|
SYMBOL_HZ = 6.25
|
|
SYMBOL_S = 1.0 / SYMBOL_HZ
|
|
SENDING_S = TONES * SYMBOL_S # 12.64 s of transmission
|
|
SLOT_S = 15.0 # in a slot of fifteen
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# The checksum
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def crc14(bits) -> int:
|
|
"""CRC-14 over a sequence of bits, most significant first.
|
|
|
|
The one thing standing between a repaired codeword and a confident lie.
|
|
The error correction below will happily converge on *a* valid codeword
|
|
from noise; whether it is the codeword that was sent is what this
|
|
answers, and one in sixteen thousand wrong answers gets through, which
|
|
over an evening is a handful of lines nobody should trust. Every
|
|
decoder prints them anyway, and so does this one -- but only after the
|
|
CRC has agreed, which is the difference between a handful and a flood.
|
|
"""
|
|
top = 1 << (CRC_BITS - 1)
|
|
mask = (top << 1) - 1
|
|
remainder = 0
|
|
for i, bit in enumerate(bits):
|
|
if i % 8 == 0:
|
|
# A byte at a time into the top of the register, exactly as the
|
|
# specification frames it: the message is a byte sequence and
|
|
# the odd bits at the end are zeros.
|
|
byte = 0
|
|
for k in range(8):
|
|
byte = (byte << 1) | (bits[i + k] if i + k < len(bits) else 0)
|
|
remainder ^= byte << (CRC_BITS - 8)
|
|
remainder = ((remainder << 1) ^ CRC_POLYNOMIAL if remainder & top
|
|
else remainder << 1)
|
|
return remainder & mask
|
|
|
|
|
|
def with_crc(payload) -> np.ndarray:
|
|
"""The seventy-seven bits said, plus the fourteen that check them.
|
|
|
|
The checksum covers eighty-two bits rather than seventy-seven: the
|
|
message zero-extended by five, which is what the specification says and
|
|
is not the same answer as checksumming seventy-seven.
|
|
"""
|
|
payload = np.asarray(payload, dtype=np.uint8)
|
|
if payload.size != MESSAGE_BITS:
|
|
raise ValueError(f"a message is {MESSAGE_BITS} bits, not "
|
|
f"{payload.size}")
|
|
extended = np.concatenate([payload, np.zeros(5, dtype=np.uint8)])
|
|
check = crc14(extended.tolist())
|
|
tail = np.array([(check >> (CRC_BITS - 1 - k)) & 1
|
|
for k in range(CRC_BITS)], dtype=np.uint8)
|
|
return np.concatenate([payload, tail])
|
|
|
|
|
|
def crc_holds(bits91) -> bool:
|
|
"""Whether the checksum on a decoded block agrees with its message."""
|
|
bits91 = np.asarray(bits91, dtype=np.uint8)
|
|
if bits91.size != PAYLOAD:
|
|
return False
|
|
return bool((with_crc(bits91[:MESSAGE_BITS]) == bits91).all())
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# The error-correcting code
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _generator() -> np.ndarray:
|
|
"""The parity half of the generator, unpacked to bits."""
|
|
rows = np.zeros((PARITY, PAYLOAD), dtype=np.uint8)
|
|
for m, row in enumerate(GENERATOR):
|
|
packed = bytes.fromhex(row)
|
|
for k in range(PAYLOAD):
|
|
rows[m, k] = (packed[k // 8] >> (7 - k % 8)) & 1
|
|
return rows
|
|
|
|
|
|
GEN = _generator()
|
|
|
|
|
|
def encode(bits91) -> np.ndarray:
|
|
"""Ninety-one bits in, one hundred and seventy-four out.
|
|
|
|
Systematic: the message comes out unchanged at the front and the parity
|
|
is appended, which is why the decoder can read the message straight off
|
|
a repaired codeword without undoing anything.
|
|
"""
|
|
bits91 = np.asarray(bits91, dtype=np.uint8)
|
|
if bits91.size != PAYLOAD:
|
|
raise ValueError(f"expected {PAYLOAD} bits, got {bits91.size}")
|
|
parity = (GEN @ bits91) & 1
|
|
return np.concatenate([bits91, parity.astype(np.uint8)])
|
|
|
|
|
|
def _sparse():
|
|
"""The parity-check matrix as flat slots, for the message passing.
|
|
|
|
Every codeword bit sits in exactly three checks and every check covers
|
|
six or seven bits, so the whole graph fits in two small index arrays and
|
|
the decoding never needs a scatter-add. The short checks are padded to
|
|
seven with a slot pointing at a dummy bit that is held at no opinion.
|
|
"""
|
|
width = max(len(c) for c in CHECKS)
|
|
bit_of_slot = np.full(PARITY * width, BITS, dtype=np.int64) # BITS = dummy
|
|
live = np.zeros(PARITY * width, dtype=bool)
|
|
for m, check in enumerate(CHECKS):
|
|
for j, one_based in enumerate(check):
|
|
bit_of_slot[m * width + j] = one_based - 1
|
|
live[m * width + j] = True
|
|
# And the other way: for each bit, the slots that talk about it.
|
|
per_bit = [[] for _ in range(BITS)]
|
|
for slot in np.flatnonzero(live):
|
|
per_bit[bit_of_slot[slot]].append(slot)
|
|
degree = max(len(s) for s in per_bit)
|
|
slots_of_bit = np.zeros((BITS, degree), dtype=np.int64)
|
|
for n, slots in enumerate(per_bit):
|
|
slots_of_bit[n] = slots + [slots[-1]] * (degree - len(slots))
|
|
return width, bit_of_slot, live, slots_of_bit
|
|
|
|
|
|
WIDTH, BIT_OF_SLOT, LIVE, SLOTS_OF_BIT = _sparse()
|
|
|
|
|
|
def parity_holds(bits174) -> bool:
|
|
"""Whether every one of the eighty-three checks comes out even.
|
|
|
|
Here rather than left to callers because the padding convention -- short
|
|
checks point their spare slots at a dummy bit past the end -- is an
|
|
implementation detail of the message passing, and anything outside this
|
|
module that had to know about it would be a bug waiting to be written.
|
|
"""
|
|
bits174 = np.asarray(bits174, dtype=np.uint8)
|
|
if bits174.size != BITS:
|
|
return False
|
|
padded = np.concatenate([bits174, np.zeros(1, dtype=np.uint8)])
|
|
sums = padded[BIT_OF_SLOT].copy()
|
|
sums[~LIVE] = 0
|
|
return bool((sums.reshape(PARITY, WIDTH).sum(axis=1) % 2 == 0).all())
|
|
|
|
|
|
def repair(llr, rounds: int = 30, alpha: float = 0.75):
|
|
"""Belief propagation over one or many candidate codewords.
|
|
|
|
``llr`` is how strongly each bit is believed to be a zero: positive for
|
|
zero, negative for one, and the size of it is the confidence. Shape
|
|
(174,) for one candidate or (n, 174) for a batch, which is how it is
|
|
actually used -- a busy slot throws up hundreds of candidates and doing
|
|
them one at a time is most of the decoding time.
|
|
|
|
Normalised min-sum rather than the exact sum-product: it is within a
|
|
few tenths of a decibel of it, and it is multiplication-free in the
|
|
inner loop, which at this size matters more than the tenths.
|
|
|
|
Returns the repaired bits, or None where the checks never came out
|
|
even. An answer here still has to pass the CRC before it is believed:
|
|
this finds *a* codeword, and noise has valid codewords in it too.
|
|
"""
|
|
single = np.ndim(llr) == 1
|
|
belief = np.atleast_2d(np.asarray(llr, dtype=np.float32))
|
|
n = belief.shape[0]
|
|
if belief.shape[1] != BITS:
|
|
raise ValueError(f"a codeword is {BITS} bits, not {belief.shape[1]}")
|
|
|
|
messages = np.zeros((n, PARITY * WIDTH), dtype=np.float32)
|
|
dead = ~LIVE
|
|
dead_grid = dead.reshape(PARITY, WIDTH)
|
|
out = np.zeros((n, BITS), dtype=np.uint8)
|
|
done = np.zeros(n, dtype=bool)
|
|
|
|
def totals(msgs):
|
|
"""What every bit is believed to be, once its three checks are in.
|
|
|
|
A gather and a sum rather than a scatter-add: every bit sits in
|
|
exactly three checks, so the three places to look are known in
|
|
advance and np.add.at -- which is where an earlier version of this
|
|
spent most of its time -- is not needed at all.
|
|
"""
|
|
return belief + msgs[:, SLOTS_OF_BIT].sum(axis=2)
|
|
|
|
for _ in range(rounds):
|
|
total = totals(messages)
|
|
# What each check hears about a bit, less what it said itself.
|
|
wide = np.concatenate([total, np.zeros((n, 1), dtype=np.float32)],
|
|
axis=1)
|
|
heard = (wide[:, BIT_OF_SLOT] - messages).reshape(n, PARITY, WIDTH)
|
|
|
|
size = np.abs(heard)
|
|
size[:, dead_grid] = np.inf
|
|
# The smallest and the next smallest in each check, so "the
|
|
# smallest of the others" is a lookup rather than a loop.
|
|
order = np.argsort(size, axis=2)
|
|
smallest = np.take_along_axis(size, order[:, :, :1], axis=2)
|
|
next_up = np.take_along_axis(size, order[:, :, 1:2], axis=2)
|
|
others = np.where(size == smallest, next_up, smallest)
|
|
|
|
odd = (heard < 0).sum(axis=2, keepdims=True) % 2 == 1
|
|
mine = np.where(heard < 0, -1.0, 1.0).astype(np.float32)
|
|
whole = np.where(odd, -1.0, 1.0).astype(np.float32)
|
|
messages = (alpha * whole * mine
|
|
* np.minimum(others, 1e4)).astype(np.float32)
|
|
messages = messages.reshape(n, -1)
|
|
messages[:, dead] = 0.0
|
|
|
|
hard = (totals(messages) < 0).astype(np.uint8)
|
|
wide_hard = np.concatenate([hard, np.zeros((n, 1), dtype=np.uint8)],
|
|
axis=1)
|
|
sums = wide_hard[:, BIT_OF_SLOT].reshape(n, PARITY, WIDTH).copy()
|
|
sums[:, dead_grid] = 0
|
|
even = (sums.sum(axis=2) % 2 == 0).all(axis=1)
|
|
fresh = even & ~done
|
|
if fresh.any():
|
|
out[fresh] = hard[fresh]
|
|
done |= fresh
|
|
if done.all():
|
|
break
|
|
|
|
if single:
|
|
return out[0] if done[0] else None
|
|
return out, done
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Tones
|
|
# ---------------------------------------------------------------------------
|
|
|
|
UNGRAY = np.zeros(8, dtype=np.uint8)
|
|
for _value, _tone in enumerate(GRAY):
|
|
UNGRAY[_tone] = _value
|
|
|
|
SYNC_AT = (0, 36, 72) # where the three Costas arrays sit
|
|
|
|
|
|
def tones_of(bits174) -> np.ndarray:
|
|
"""The seventy-nine tones that carry these bits, sync included."""
|
|
bits174 = np.asarray(bits174, dtype=np.uint8)
|
|
if bits174.size != BITS:
|
|
raise ValueError(f"a codeword is {BITS} bits, not {bits174.size}")
|
|
trips = bits174.reshape(-1, 3)
|
|
values = trips[:, 0] * 4 + trips[:, 1] * 2 + trips[:, 2]
|
|
data = np.array([GRAY[v] for v in values], dtype=np.uint8)
|
|
out = np.zeros(TONES, dtype=np.uint8)
|
|
costas = np.array(COSTAS, dtype=np.uint8)
|
|
taken = 0
|
|
for i in range(TONES):
|
|
which = i // 36 if i % 36 < 7 else -1
|
|
if i in range(0, 7) or i in range(36, 43) or i in range(72, 79):
|
|
out[i] = costas[(i - (0 if i < 7 else 36 if i < 43 else 72))]
|
|
else:
|
|
out[i] = data[taken]
|
|
taken += 1
|
|
return out
|
|
|
|
|
|
def bits_of(tones) -> np.ndarray:
|
|
"""The bits those tones carry, sync thrown away."""
|
|
tones = np.asarray(tones, dtype=np.uint8)
|
|
if tones.size != TONES:
|
|
raise ValueError(f"a transmission is {TONES} tones, not {tones.size}")
|
|
data = [tones[i] for i in range(TONES)
|
|
if not (i < 7 or 36 <= i < 43 or 72 <= i)]
|
|
out = np.zeros(BITS, dtype=np.uint8)
|
|
for k, tone in enumerate(data):
|
|
value = UNGRAY[tone]
|
|
out[3 * k] = (value >> 2) & 1
|
|
out[3 * k + 1] = (value >> 1) & 1
|
|
out[3 * k + 2] = value & 1
|
|
return out
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Callsigns
|
|
# ---------------------------------------------------------------------------
|
|
|
|
ALPHANUM_SPACE = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" # 37
|
|
ALPHANUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" # 36
|
|
NUMERIC = "0123456789" # 10
|
|
LETTERS_SPACE = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" # 27
|
|
FULL = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?" # 42
|
|
WITH_SLASH = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/" # 38
|
|
|
|
TOKENS = 2_063_592 # DE, QRZ, CQ and the CQ-with-an-argument forms
|
|
MAX22 = 4_194_304 # room for a hashed callsign
|
|
MAX_GRID = 32_400 # four-character grids, before the report forms
|
|
|
|
|
|
def hash_of(call: str, width: int = 22) -> int:
|
|
"""The short hash a compound callsign is carried as.
|
|
|
|
A callsign that will not fit in twenty-eight bits -- anything with a
|
|
slash in it, and anything long -- travels as a hash, and the receiver
|
|
is expected to have heard the full call earlier in the exchange and to
|
|
remember it. That is why a fresh receiver prints <...>: not a decoding
|
|
failure, but a station whose full name has not been said yet in
|
|
anything this receiver heard.
|
|
"""
|
|
packed = 0
|
|
padded = (call.upper() + " ")[:11]
|
|
for ch in padded:
|
|
packed = packed * 38 + (WITH_SLASH.index(ch) if ch in WITH_SLASH else 0)
|
|
return int((47_055_833_459 * packed) >> (64 - width)) & ((1 << width) - 1)
|
|
|
|
|
|
def is_standard_call(call: str) -> bool:
|
|
"""Whether a callsign fits the twenty-eight bit form.
|
|
|
|
One or two characters of prefix, a digit, and up to three letters. Most
|
|
callsigns on earth; not the ones with a slash in them.
|
|
"""
|
|
return _pack_standard(call) is not None
|
|
|
|
|
|
def _pack_standard(call: str):
|
|
"""A plain callsign as its number, or None if it is not a plain one.
|
|
|
|
The form is one or two characters of prefix, exactly one digit, and up
|
|
to three letters -- and the twenty-eight bit packing wants the digit in
|
|
the third place. Which character is *the* digit cannot be found by
|
|
looking at the second one: Z33Z has a digit there and it belongs to the
|
|
prefix. It is the last character that is not one of the trailing
|
|
letters, so that is how it is found.
|
|
"""
|
|
call = (call or "").strip().upper()
|
|
if not call or "/" in call or len(call) > 6:
|
|
return None
|
|
at = len(call) - 1
|
|
while at >= 0 and call[at].isalpha():
|
|
at -= 1
|
|
if at < 0 or at > 2 or not call[at].isdigit():
|
|
return None
|
|
call = " " * (2 - at) + call
|
|
if len(call) > 6:
|
|
return None
|
|
call = (call + " ")[:6]
|
|
if (call[0] not in ALPHANUM_SPACE or call[1] not in ALPHANUM
|
|
or call[2] not in NUMERIC):
|
|
return None
|
|
if any(c not in LETTERS_SPACE for c in call[3:6]):
|
|
return None
|
|
n = ALPHANUM_SPACE.index(call[0])
|
|
n = n * 36 + ALPHANUM.index(call[1])
|
|
n = n * 10 + NUMERIC.index(call[2])
|
|
n = n * 27 + LETTERS_SPACE.index(call[3])
|
|
n = n * 27 + LETTERS_SPACE.index(call[4])
|
|
n = n * 27 + LETTERS_SPACE.index(call[5])
|
|
return n
|
|
|
|
|
|
def _unpack_standard(n: int) -> str:
|
|
out = [""] * 6
|
|
out[5] = LETTERS_SPACE[n % 27]
|
|
n //= 27
|
|
out[4] = LETTERS_SPACE[n % 27]
|
|
n //= 27
|
|
out[3] = LETTERS_SPACE[n % 27]
|
|
n //= 27
|
|
out[2] = NUMERIC[n % 10]
|
|
n //= 10
|
|
out[1] = ALPHANUM[n % 36]
|
|
n //= 36
|
|
out[0] = ALPHANUM_SPACE[n % 37]
|
|
return "".join(out).strip()
|
|
|
|
|
|
@dataclass
|
|
class CallBook:
|
|
"""Full callsigns heard earlier, so a hash can be turned back into one.
|
|
|
|
A compound callsign travels as a hash and is expected to be remembered
|
|
from earlier in the same exchange. This is that memory. It is only
|
|
ever added to by callsigns that arrived in full and passed their CRC,
|
|
so a station that was never heard properly stays <...> rather than being
|
|
guessed at -- a wrong callsign in a log is worse than a missing one.
|
|
"""
|
|
|
|
by_hash: dict = field(default_factory=dict)
|
|
|
|
def remember(self, call: str) -> None:
|
|
call = (call or "").strip().upper()
|
|
if len(call) < 3 or call in ("CQ", "DE", "QRZ"):
|
|
return
|
|
for width in (10, 12, 22):
|
|
self.by_hash[(width, hash_of(call, width))] = call
|
|
|
|
def look_up(self, value: int, width: int = 22) -> str:
|
|
return self.by_hash.get((width, value), "<...>")
|
|
|
|
|
|
def _unpack28(n: int, book: CallBook) -> str:
|
|
"""One of the two callsign fields of a standard message."""
|
|
if n < TOKENS:
|
|
if n == 0:
|
|
return "DE"
|
|
if n == 1:
|
|
return "QRZ"
|
|
if n == 2:
|
|
return "CQ"
|
|
if n <= 1002:
|
|
return f"CQ {n - 3:03d}"
|
|
if n <= 532_443:
|
|
rest = n - 1003
|
|
letters = [""] * 4
|
|
for i in (3, 2, 1, 0):
|
|
letters[i] = LETTERS_SPACE[rest % 27]
|
|
rest //= 27
|
|
return "CQ " + "".join(letters).strip()
|
|
return "<...>"
|
|
n -= TOKENS
|
|
if n < MAX22:
|
|
return book.look_up(n, 22)
|
|
return _unpack_standard(n - MAX22)
|
|
|
|
|
|
def _unpack_grid(value: int, rover: int) -> str:
|
|
"""The fifteen-bit field: a grid square, a signal report, or a sign-off."""
|
|
if value <= MAX_GRID:
|
|
n = value
|
|
out = ["", "", "", ""]
|
|
out[3] = NUMERIC[n % 10]
|
|
n //= 10
|
|
out[2] = NUMERIC[n % 10]
|
|
n //= 10
|
|
out[1] = chr(ord("A") + n % 18)
|
|
n //= 18
|
|
out[0] = chr(ord("A") + n % 18)
|
|
grid = "".join(out)
|
|
return ("R " + grid) if rover else grid
|
|
report = value - MAX_GRID
|
|
if report == 1:
|
|
return ""
|
|
if report == 2:
|
|
return "RRR"
|
|
if report == 3:
|
|
return "RR73"
|
|
if report == 4:
|
|
return "73"
|
|
decibels = report - 35
|
|
return f"{'R' if rover else ''}{decibels:+03d}"
|
|
|
|
|
|
def _pack_grid(text: str):
|
|
"""The inverse: a grid, a report or a token as fifteen bits and a flag."""
|
|
text = (text or "").strip().upper()
|
|
if not text:
|
|
return MAX_GRID + 1, 0
|
|
if text == "RRR":
|
|
return MAX_GRID + 2, 0
|
|
if text == "RR73":
|
|
return MAX_GRID + 3, 0
|
|
if text == "73":
|
|
return MAX_GRID + 4, 0
|
|
rover = 0
|
|
if text.startswith("R ") or (text.startswith("R") and len(text) > 1
|
|
and text[1] in "+-"):
|
|
rover, text = 1, text[2:].strip() if text[1] == " " else text[1:]
|
|
if (len(text) == 4 and "A" <= text[0] <= "R" and "A" <= text[1] <= "R"
|
|
and text[2].isdigit() and text[3].isdigit()):
|
|
value = ((ord(text[0]) - 65) * 18 + (ord(text[1]) - 65)) * 10
|
|
value = (value + int(text[2])) * 10 + int(text[3])
|
|
return value, rover
|
|
try:
|
|
return MAX_GRID + 35 + int(text), rover
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Messages
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@dataclass
|
|
class Message:
|
|
"""One decoded line, and what could be picked out of it."""
|
|
|
|
text: str = ""
|
|
kind: str = "" # standard, free text, telemetry, ...
|
|
calls: tuple = () # the callsigns in it, in order
|
|
grid: str = "" # a four-character grid, where there was one
|
|
report: str = "" # a signal report, where there was one
|
|
calling: bool = False # whether this is a CQ
|
|
|
|
|
|
def _number(bits, start: int, count: int) -> int:
|
|
value = 0
|
|
for k in range(count):
|
|
value = (value << 1) | int(bits[start + k])
|
|
return value
|
|
|
|
|
|
def _put(bits, start: int, count: int, value: int) -> None:
|
|
for k in range(count):
|
|
bits[start + k] = (value >> (count - 1 - k)) & 1
|
|
|
|
|
|
def free_text(bits77) -> str:
|
|
"""The thirteen-character form: anything at all, at a price.
|
|
|
|
Base forty-two over seventy-one bits, which is thirteen characters and
|
|
no callsign structure -- so a receiver cannot tell who sent it from the
|
|
message alone, and nor can the network that reports these things.
|
|
"""
|
|
n = _number(bits77, 0, 71)
|
|
out = [""] * 13
|
|
for i in range(12, -1, -1):
|
|
out[i] = FULL[n % 42]
|
|
n //= 42
|
|
return "".join(out).strip()
|
|
|
|
|
|
def unpack(bits77, book: CallBook | None = None) -> Message:
|
|
"""Seventy-seven bits as something to read.
|
|
|
|
The type is the last three bits, which is an odd place for it until you
|
|
remember that everything before it is a different length in each form.
|
|
"""
|
|
bits77 = np.asarray(bits77, dtype=np.uint8)
|
|
book = book or CallBook()
|
|
i3 = _number(bits77, 74, 3)
|
|
|
|
if i3 == 0:
|
|
n3 = _number(bits77, 71, 3)
|
|
if n3 == 0:
|
|
return Message(text=free_text(bits77), kind="free text")
|
|
if n3 == 5:
|
|
value = _number(bits77, 0, 71)
|
|
return Message(text=f"{value:018X}", kind="telemetry")
|
|
return Message(text=free_text(bits77), kind="free text")
|
|
|
|
if i3 in (1, 2):
|
|
a = _number(bits77, 0, 28)
|
|
a_rover = _number(bits77, 28, 1)
|
|
b = _number(bits77, 29, 28)
|
|
b_rover = _number(bits77, 57, 1)
|
|
rover = _number(bits77, 58, 1)
|
|
grid = _number(bits77, 59, 15)
|
|
one = _unpack28(a, book)
|
|
two = _unpack28(b, book)
|
|
if a_rover:
|
|
one += "/R"
|
|
if b_rover:
|
|
two += "/R"
|
|
extra = _unpack_grid(grid, rover)
|
|
text = " ".join(x for x in (one, two, extra) if x)
|
|
looks_like_grid = (len(extra) == 4 and extra[:2].isalpha()
|
|
and extra[2:].isdigit())
|
|
return Message(text=text, kind="standard",
|
|
calls=tuple(c for c in (one, two)
|
|
if c not in ("CQ", "DE", "QRZ")
|
|
and not c.startswith("CQ ")),
|
|
grid=extra if looks_like_grid else "",
|
|
report="" if looks_like_grid else extra,
|
|
calling=one.startswith("CQ") or one == "QRZ")
|
|
|
|
if i3 == 4:
|
|
# A compound callsign: one hashed, one carried in full as eleven
|
|
# characters of base thirty-eight.
|
|
short = _number(bits77, 0, 12)
|
|
n58 = _number(bits77, 12, 58)
|
|
flip = _number(bits77, 70, 1)
|
|
kind = _number(bits77, 71, 2)
|
|
rest = n58
|
|
letters = [""] * 11
|
|
for i in range(10, -1, -1):
|
|
letters[i] = WITH_SLASH[rest % 38]
|
|
rest //= 38
|
|
full = "".join(letters).strip()
|
|
other = book.look_up(short, 12)
|
|
one, two = (full, other) if flip else (other, full)
|
|
tail = {1: "RRR", 2: "RR73", 3: "73"}.get(kind, "")
|
|
text = " ".join(x for x in (one, two, tail) if x)
|
|
return Message(text=text, kind="non-standard",
|
|
calls=tuple(c for c in (one, two) if c != "<...>"),
|
|
report=tail, calling=one.startswith("CQ"))
|
|
|
|
return Message(text=free_text(bits77), kind=f"type {i3}")
|
|
|
|
|
|
def pack(text: str, book: CallBook | None = None):
|
|
"""The inverse, for the standard and free-text forms.
|
|
|
|
Here so the decoder can be tested against something that is not itself.
|
|
A receiver never needs to build a message -- this one does not transmit
|
|
-- but a test that encodes with the same misunderstanding it decodes
|
|
with agrees with itself about anything they are both wrong about.
|
|
"""
|
|
text = (text or "").strip().upper()
|
|
bits = np.zeros(MESSAGE_BITS, dtype=np.uint8)
|
|
words = text.split()
|
|
|
|
if len(words) in (2, 3) or (len(words) == 4 and words[0] == "CQ"):
|
|
made = _pack_standard_message(words, bits)
|
|
if made is not None:
|
|
return made
|
|
return _pack_free_text(text, bits)
|
|
|
|
|
|
def _pack_standard_message(words, bits):
|
|
if words[0] == "CQ" and len(words) >= 3 and len(words[1]) <= 4 \
|
|
and not _is_call(words[1]):
|
|
one, rest = f"CQ {words[1]}", words[2:]
|
|
else:
|
|
one, rest = words[0], words[1:]
|
|
if not rest:
|
|
return None
|
|
two, extra = rest[0], (rest[1] if len(rest) > 1 else "")
|
|
a = _pack28(one)
|
|
b = _pack28(two)
|
|
if a is None or b is None:
|
|
return None
|
|
grid = _pack_grid(extra)
|
|
if grid is None:
|
|
return None
|
|
value, rover = grid
|
|
_put(bits, 0, 28, a)
|
|
_put(bits, 28, 1, 0)
|
|
_put(bits, 29, 28, b)
|
|
_put(bits, 57, 1, 0)
|
|
_put(bits, 58, 1, rover)
|
|
_put(bits, 59, 15, value)
|
|
_put(bits, 74, 3, 1)
|
|
return bits
|
|
|
|
|
|
def _is_call(word: str) -> bool:
|
|
return any(c.isdigit() for c in word) and _pack_standard(word) is not None
|
|
|
|
|
|
def _pack28(call: str):
|
|
call = call.strip().upper()
|
|
if call == "DE":
|
|
return 0
|
|
if call == "QRZ":
|
|
return 1
|
|
if call == "CQ":
|
|
return 2
|
|
if call.startswith("CQ "):
|
|
rest = call[3:].strip()
|
|
if rest.isdigit() and len(rest) == 3:
|
|
return 3 + int(rest)
|
|
if 1 <= len(rest) <= 4 and all(c in LETTERS_SPACE for c in rest):
|
|
n = 0
|
|
for ch in (rest + " ")[:4]:
|
|
n = n * 27 + LETTERS_SPACE.index(ch)
|
|
return 1003 + n
|
|
return None
|
|
plain = _pack_standard(call)
|
|
if plain is not None:
|
|
return TOKENS + MAX22 + plain
|
|
# Deliberately not a hash. A hash always succeeds, and a packer that
|
|
# always succeeds would send "HELLO WORLD" as two hashed callsigns
|
|
# rather than as the free text it plainly is.
|
|
return None
|
|
|
|
|
|
def _pack_free_text(text: str, bits):
|
|
text = "".join(c if c in FULL else " " for c in text)[:13]
|
|
text = text.rjust(13)
|
|
n = 0
|
|
for ch in text:
|
|
n = n * 42 + FULL.index(ch)
|
|
_put(bits, 0, 71, n)
|
|
_put(bits, 71, 3, 0)
|
|
_put(bits, 74, 3, 0)
|
|
return bits
|