bandsaunter/bandsaunter/kml.py
The Dust Council 3d7f76118e Read the pictures, the aircraft, the meters and the sensors
Hexadecimal is a true answer to "what did that say" and not a useful one.
This is the work of turning the rest of what a receiver hears into
something a person can read, and most of it is pictures.

PICTURES

Three of the things on the air are images rather than sounds, and all three
arrive as the audio a scan already records:

  SSTV     14.230 and 144.5 MHz   Martin M1/M2, Scottie S1/S2/DX, Robot 36/72
  APT      137-138 MHz            the NOAA weather satellites
  HF fax   2-20 MHz, sideband     the marine weather charts

Each is written from its published specification, and the generators used to
test them are written from the same specification without reference to the
decoders -- so a picture that comes back matching the one that went in is
evidence about the format.  Every SSTV mode reproduces its published line
time exactly, which is worth failing a test over: a line a few milliseconds
long walks the picture off the screen inside ten lines.  Against synthetic
transmissions at 30 dB SNR, SSTV is 96-98% of pixels exact, APT correlates
at 0.97 and fax at 0.998; all three still read at 6-12 dB.

None of the three is guessed at, and that is what makes it safe to try them
on every recording.  SSTV needs its VIS header, APT needs both line syncs at
the right distance from each other, fax needs the phasing signal.  No false
pictures in 295 attempts over noise, tones, speech and swept whistles.

Two things had to be got right beyond the arithmetic.  A band-pass does not
switch between two tones, it slides between them, so every edge is measured
at the midpoint of the slide rather than at the first sample past a
threshold -- the earlier version was reading the coarse search stride back
as the edge and shifting Martin M1 sideways by a whole colour bar.  And a
picture now keeps its capture whatever the content check made of it: a
satellite is a steady tone with a wobble on it and SSTV is a whistle, so
both were being discarded as "no signal content" having already been
recognised.

PNG is written here rather than pulled in from Pillow.  A scanner that
cannot start because an imaging library is missing is worse than one that
cannot draw.

saunterbrowse marks a picture in the list, gives its path in full -- wrapped
rather than cut off, because half a path opens nothing -- and moves or
deletes the PNGs with the recording.  o prints the picture's path, not the
audio's.

GRIB is not a modulation and is not pretended to be one.  It is the format
weather models are published in and it travels by satellite link and by
e-mail; where a decoded byte stream begins with its magic number it is
named, and that is all.

AIRCRAFT

`bandsaunter adsb` parks the receiver on 1090 MHz and reads Mode S extended
squitter: address, callsign, altitude, position, speed.  A command of its
own because a megabit a second will not go through a channel twelve and a
half kilohertz wide.  Every frame carries a 24-bit checksum so there is no
threshold anywhere in it -- with one trap, which is that a frame of all
zeros satisfies that checksum and silence is exactly that.  Positions round
trip exactly through compact position reporting, and a pair straddling a
longitude-zone boundary is refused rather than resolved against two grids.

METERS AND SENSORS

Itron ERT utility meters on 900 MHz and AcuRite weather sensors on 433 MHz
are named rather than reported as hex, and neither is believed without its
own checksum -- BCH(255,239) for the meter, a checksum and four parity bits
for the sensor.  Both are implemented from published descriptions and
checked against frames built from the same descriptions, which proves the
framing and the arithmetic and is not the same as having held a meter.

HEX INTO WORDS

Everything else that decodes to bits now gets its fields named where the
shape is standard, its text read out where there is text, and its bytes laid
out in groups with the printable characters beside them.

The text search is where the care went, because printability is not
evidence.  Forty framings of each packet, and seven-bit values printable
three in four, meant a bar set on printability called 64% of random payloads
text.  Real text is nearly all one case where random letters are half and
half, two fifths vowels where random is a fifth, and mostly alphanumeric
where random draws punctuation one time in four.  Together: under 0.5%,
measured in the suite.

CALLSIGNS

The licensed address is recorded in full -- the street, not merely the town
-- and goes into the KML with everything else.  US amateur records are
public by law and carry it; holding it and not saying so is worse than
either showing it or not asking, and --no-lookup asks for none of it.

Also here: Morse is decoded again from the whole recording where the capture
was made in cw mode.  The first pass works from the classifier's buffer,
which holds a few seconds -- enough to say "this is Morse", not enough to
catch a callsign whole between two word gaps, so a beacon repeating every
eight seconds through an eight-second window was never identified.

And classify._psk_order took the logarithm of zero on a silent block.

1318 tests, up from 1161.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
2026-08-29 19:38:37 -07:00

426 lines
16 KiB
Python

"""A map of who was heard, written as KML.
A scan produces a list of callsigns and a licence database knows where each
one is licensed, so the two together are a map. KML is what to write it in:
Google Earth, QGIS, Marble, gpsbabel and OsmAnd all open it without being
told anything, and it is text, so a run that is interrupted leaves a file
that still opens.
The file accumulates. Each callsign becomes one placemark, and hearing the
same station again adds a line to that placemark rather than dropping a
second pin on top of the first -- twenty overs from the same repeater are one
station, not twenty. Loading the existing file first means a scan on Tuesday
adds to what Monday found instead of replacing it.
"""
from __future__ import annotations
import time
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from xml.sax.saxutils import escape, quoteattr
from .bandplan import band_name, fmt_hz
from .callsign import Callsign
__all__ = ["Hearing", "Contact", "KmlLog", "DEFAULT_KML_NAME"]
DEFAULT_KML_NAME = "callsigns.kml"
# Stamped on each placemark so a file written by an older version, or edited
# by hand, is still recognisably ours when it is read back.
_ID_PREFIX = "bandsaunter-"
_STYLES = """\
<Style id="bandsaunter-heard">
<IconStyle>
<color>ff2fbfff</color>
<scale>1.1</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/shapes/target.png</href>
</Icon>
</IconStyle>
<LabelStyle><scale>0.9</scale></LabelStyle>
</Style>"""
def _stamp(when: float) -> str:
"""An ISO time in UTC, which is the only thing KML accepts."""
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(when))
def _local(when: float) -> str:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(when))
@dataclass(frozen=True)
class Hearing:
"""One transmission on which a callsign was heard."""
frequency: float = 0.0
at: float = 0.0 # epoch seconds
band: str = ""
recording: str = "" # filename, not a path: the KML travels
@property
def key(self) -> tuple[int, int]:
return (int(round(self.frequency)), int(self.at))
def describe(self) -> str:
bits = [fmt_hz(self.frequency) if self.frequency else "",
_local(self.at) if self.at else "",
self.band, self.recording]
return " ".join(b for b in bits if b)
@classmethod
def parse(cls, line: str) -> "Hearing | None":
"""Read back a line this class wrote.
Deliberately forgiving: a file someone has edited by hand should lose
the line that was mangled, not the whole history.
"""
parts = [p for p in line.split(" ") if p.strip()]
if not parts:
return None
freq, at, band, recording = 0.0, 0.0, "", ""
for part in parts:
part = part.strip()
if not freq and part[:1].isdigit() and part.endswith("Hz"):
freq = _parse_hz(part)
elif not at and len(part) == 19 and part[4] == "-":
at = _parse_time(part)
elif part.lower().endswith((".wav", ".flac", ".ogg")):
recording = part
elif not band:
band = part
return cls(freq, at, band, recording)
def _parse_hz(text: str) -> float:
try:
number, unit = text.split(" ", 1)
scale = {"hz": 1.0, "khz": 1e3, "mhz": 1e6, "ghz": 1e9}
return float(number) * scale.get(unit.strip().lower(), 1.0)
except (ValueError, KeyError):
return 0.0
def _parse_time(text: str) -> float:
try:
return time.mktime(time.strptime(text, "%Y-%m-%d %H:%M:%S"))
except ValueError:
return 0.0
@dataclass
class Contact:
"""One station, and every time it was heard."""
call: str
name: str = ""
street: str = "" # the first line of the licensed address
postcode: str = ""
location: str = ""
country: str = ""
grid: str = ""
oper_class: str = ""
latitude: float = 0.0
longitude: float = 0.0
coarse: bool = False # position came from the grid square
hearings: list[Hearing] = field(default_factory=list)
@property
def located(self) -> bool:
return bool(self.latitude or self.longitude)
@property
def address(self) -> str:
"""The whole licensed address on one line, as far as it is known."""
parts = [self.street, self.location, self.postcode]
return ", ".join(p for p in parts if p)
@property
def first_heard(self) -> float:
times = [h.at for h in self.hearings if h.at]
return min(times) if times else 0.0
@property
def last_heard(self) -> float:
times = [h.at for h in self.hearings if h.at]
return max(times) if times else 0.0
def add(self, hearing: Hearing) -> bool:
"""Record a hearing; False if it was already there."""
if any(h.key == hearing.key for h in self.hearings):
return False
self.hearings.append(hearing)
self.hearings.sort(key=lambda h: (h.at, h.frequency))
return True
def update_from(self, entry: Callsign) -> None:
"""Fill in what the licence says, without erasing what is known.
A lookup that failed this time must not blank out a name that a
successful lookup wrote last time, which is why every field is only
overwritten when the new value is not empty.
"""
for attr in ("name", "street", "postcode", "location", "country",
"grid", "oper_class"):
value = getattr(entry, attr, "")
if value:
setattr(self, attr, value)
position = entry.position
if position is not None:
self.latitude, self.longitude = position
self.coarse = entry.coarse_position
# -- rendering --------------------------------------------------------
def title(self) -> str:
return f"{self.call} — {self.name}" if self.name else self.call
def summary(self) -> str:
"""The one line that goes under the pin's name."""
bits = [b for b in (self.location or self.country, self.grid) if b]
return " · ".join(bits)
def description(self) -> str:
"""The balloon Google Earth shows when the pin is clicked."""
rows = []
if self.name:
rows.append(("Licensee", self.name))
if self.address:
rows.append(("Licensed at", self.address))
elif self.country:
rows.append(("Country", self.country))
if self.oper_class:
rows.append(("Class", self.oper_class.title()))
if self.grid:
rows.append(("Grid", self.grid))
if self.coarse:
rows.append(("Position", "centre of the grid square, "
"not the licensed address"))
html = ["<h3>{}</h3>".format(escape(self.call))]
if rows:
html.append("<table>")
html += ["<tr><td><b>{}</b></td><td>{}</td></tr>".format(
escape(k), escape(v)) for k, v in rows]
html.append("</table>")
if self.hearings:
html.append("<p><b>Heard {} time{}</b></p><ul>".format(
len(self.hearings), "" if len(self.hearings) == 1 else "s"))
html += ["<li>{}</li>".format(escape(h.describe()))
for h in self.hearings]
html.append("</ul>")
return "".join(html)
def to_xml(self, indent: int = 4) -> str:
ident = quoteattr(_ID_PREFIX + self.call)
out = [f" <Placemark id={ident}>",
f" <name>{escape(self.title())}</name>"]
summary = self.summary()
if summary:
out.append(f" <Snippet>{escape(summary)}</Snippet>")
out.append(" <description>"
f"{escape(self.description())}</description>")
out.append(" <styleUrl>#bandsaunter-heard</styleUrl>")
if self.last_heard:
# A TimeSpan rather than a TimeStamp: the station was heard over a
# period, and Google Earth's time slider can then play the scan
# back rather than showing everything at once.
out.append(" <TimeSpan>")
out.append(f" <begin>{_stamp(self.first_heard)}</begin>")
out.append(f" <end>{_stamp(self.last_heard)}</end>")
out.append(" </TimeSpan>")
out.append(" <ExtendedData>")
for key, value in (("callsign", self.call),
("licensee", self.name),
("address", self.address),
("street", self.street),
("location", self.location),
("postcode", self.postcode),
("country", self.country),
("grid", self.grid),
("class", self.oper_class),
("coarse", "yes" if self.coarse else "")):
if value:
out.append(f" <Data name={quoteattr(key)}>"
f"<value>{escape(value)}</value></Data>")
if self.hearings:
body = "\n".join(escape(h.describe()) for h in self.hearings)
out.append(' <Data name="heard"><value>'
f"{body}</value></Data>")
out.append(" </ExtendedData>")
if self.located:
out.append(" <Point><coordinates>"
f"{self.longitude:.6f},{self.latitude:.6f},0"
"</coordinates></Point>")
out.append(" </Placemark>")
if indent == 4:
return "\n".join(out)
pad = " " * (indent - 4)
return "\n".join(pad + line for line in out)
def _tag(element) -> str:
return element.tag.rsplit("}", 1)[-1]
def _read_placemark(element) -> Contact | None:
"""Rebuild a contact from a placemark this module wrote."""
fields: dict[str, str] = {}
heard: list[str] = []
for data in element.iter():
if _tag(data) != "Data":
continue
name = data.get("name") or ""
value = ""
for child in data:
if _tag(child) == "value":
value = child.text or ""
if name == "heard":
heard = value.splitlines()
elif name:
fields[name] = value
call = fields.get("callsign", "").strip().upper()
if not call:
return None
contact = Contact(call=call,
name=fields.get("licensee", ""),
street=fields.get("street", ""),
postcode=fields.get("postcode", ""),
location=fields.get("location", ""),
country=fields.get("country", ""),
grid=fields.get("grid", ""),
oper_class=fields.get("class", ""),
coarse=bool(fields.get("coarse")))
for point in element.iter():
if _tag(point) == "coordinates" and point.text:
parts = point.text.strip().split(",")
if len(parts) >= 2:
try:
contact.longitude = float(parts[0])
contact.latitude = float(parts[1])
except ValueError:
pass
for line in heard:
hearing = Hearing.parse(line)
if hearing is not None:
contact.add(hearing)
return contact
class KmlLog:
"""The KML file, read on open and rewritten as contacts are added.
Rewritten rather than appended to because a placemark grows: hearing a
station a second time edits the pin that is already there. The file is
one placemark per station and stays small, and the write is atomic, so an
interrupted scan cannot leave half a document behind.
"""
def __init__(self, path, title: str = "bandsaunter",
description: str = ""):
self.path = Path(path).expanduser()
self.title = title
self.description = description
self.contacts: dict[str, Contact] = {}
self.added = 0 # new stations since this log was opened
self.readable = True # cleared if what is there is not KML
self.load()
# -- reading ----------------------------------------------------------
def load(self) -> None:
"""Take up where an earlier run left off.
A file that cannot be parsed is left alone and reported as empty, so
that a scan never destroys a map it did not understand -- the write
below refuses to overwrite in that case.
"""
self.readable = True
try:
text = self.path.read_text()
except OSError:
return
try:
root = ET.fromstring(text)
except ET.ParseError:
self.readable = False
return
for element in root.iter():
if _tag(element) != "Placemark":
continue
contact = _read_placemark(element)
if contact is not None:
self.contacts[contact.call] = contact
# -- writing ----------------------------------------------------------
def add(self, entry: Callsign, frequency: float = 0.0,
when: float = 0.0, band: str = "", recording: str = "") -> bool:
"""Note that ``entry`` was heard. True if anything changed."""
call = (entry.call or "").strip().upper()
if not call:
return False
contact = self.contacts.get(call)
if contact is None:
contact = Contact(call=call)
self.contacts[call] = contact
self.added += 1
changed = True
else:
changed = False
before = (contact.name, contact.latitude, contact.longitude)
contact.update_from(entry)
changed |= (contact.name, contact.latitude,
contact.longitude) != before
if not band and frequency:
band = band_name(frequency)
changed |= contact.add(Hearing(float(frequency), float(when or
time.time()),
band, recording))
return changed
def render(self) -> str:
located = sorted((c for c in self.contacts.values() if c.located),
key=lambda c: c.call)
unlocated = sorted((c for c in self.contacts.values()
if not c.located), key=lambda c: c.call)
out = ['<?xml version="1.0" encoding="UTF-8"?>',
'<kml xmlns="http://www.opengis.net/kml/2.2">',
" <Document>",
f" <name>{escape(self.title)}</name>"]
if self.description:
out.append(f" <description>{escape(self.description)}"
"</description>")
out.append(_STYLES)
out += [c.to_xml() for c in located]
if unlocated:
# Kept rather than dropped: that a station was heard is worth
# recording even when no licence says where it was.
out.append(" <Folder>")
out.append(" <name>no location on file</name>")
out.append(" <visibility>0</visibility>")
out += [c.to_xml(indent=6) for c in unlocated]
out.append(" </Folder>")
out += [" </Document>", "</kml>", ""]
return "\n".join(out)
def save(self) -> Path | None:
"""Write the file, atomically. None when there was nothing to write."""
if not self.contacts:
return None
if not self.readable:
# Something is there that we could not parse. Overwriting it
# would throw away whatever it was.
return None
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_name(self.path.name + ".tmp")
tmp.write_text(self.render())
tmp.replace(self.path)
except OSError:
return None
return self.path
def __len__(self) -> int:
return len(self.contacts)