Four things asked for in turn, landing together because they run through the same files. THE MAPS. The tiles were already cached and always had been -- a second evening on the same view was measured at nought network requests -- but the work done on them was not. Every window open decoded forty PNGs and resampled a megapixel and a half into this program's own projection, for an answer that cannot have changed, because a coastline does not move. The finished map is kept beside the tiles now: 0.61 seconds become 0.01, byte for byte identical, two hundred kilobytes a view. Both windows and both kinds of still picture get it, all four reaching the ground through one function. A map with squares missing is deliberately not kept, since caching a hole would keep it for a month and the point of calling a partial map provisional is that it is asked for again. And because this adds a disk consumer, the whole cache is now pruned to four hundred megabytes, least recently *used* first: a tile fetched a year ago and looked at last night is the receiver's own neighbourhood, and discarding that to keep last week's holiday is the wrong way round. THE LOOKUPS. APRS and FT8 now ask who each station is licensed to. Every other mode that hears a callsign already did -- speech transcripts, Morse idents, the recording browser -- and all five resolve through one file, so a callsign heard on two bands is asked about once. The rules for finding the licensed callsign inside a heard one are now in one place rather than per band, because getting them wrong is silent: a register asked about W1AW-9 returns nothing, which looks exactly like a station that is not licensed. An SSID, a rover suffix, a guest prefix, a digipeater alias and an unspelled hash all come off or are refused. The bug worth recording is that the first cut of this did the lookups and threw them away. The book has to be told to save and was not, so every evening would have asked the register about the same net again -- which is the one thing caching them was for, and is invisible from inside a single run because the answers are all in memory while it lasts. Caught by looking at the file on disk rather than at the display. There is a test for each side of it now, and a register of which modules resolve callsigns at all, which fails when a new one starts so that somebody has to decide whether it should. THE REGISTER. c in saunterbrowse opens everything ever looked up: sixty-odd callsigns and sixteen hundred aircraft here, every field of each in two columns because a licence has a dozen and a screen is wider than it is tall. tab switches, / searches every field rather than the name -- the question is usually "who was in Arizona" rather than "which callsign" -- and g opens the place in a browser. Only the coordinates go into that link: a map does not need to be told whose licence it is looking at, and the link is the one part of this that leaves the machine. A headless box, which is the normal case for a receiver, gets the coordinates printed instead. Callsigns no register could place are kept rather than dropped, because "asked about, and in no register reachable from here" is a fact about a station. THE FRONT OF IT. A title screen for each program: five rows of blocks cut by hand, a figlet dependency to draw eleven letters being the largest thing that would then be in the requirements, coloured blue to red across the width, which is the ramp every waterfall here already uses because it is what a spectrum looks like. The interesting part is where it does not appear -- everything here can be piped into something else and a banner in the middle of that is corruption rather than decoration, so anything that is not a terminal gets nothing, --help is untouched because it is drawn after parsing, --no-splash turns it off for a run and BANDSAUNTER_NO_SPLASH=1 for good. And the address. INSTALL.md said "git clone <the repository>" for a long time: a placeholder in the first command anybody types, unnoticed because nothing reads install instructions except somebody installing, who then cannot. It is filled in, along with the readme, the metadata, both manuals and the Homepage field of all three packages. The tile server's User-Agent pointed at a topic listing on somebody else's site for want of an address of its own; the usage policy of that service asks for one naming the application and giving somewhere to look it up, so an operator with a question about the traffic has somebody to ask, and now it gives the real one. Seven tests so the placeholder cannot come back, verified by putting it back and watching two of them fail. One thing forced by all this: the keys page in saunterbrowse was exactly as tall as an eighty-by-twenty-four terminal, so the register entry pushed "q quit" off the bottom. A test caught it. Home and End have merged into the Page Up line, which were always the same thought. THE WINDOWS. They open maximised now, this being a map and the thing anybody wants more of being map; f goes to true full screen and back, and is written along the top of the screen because a window with no frame is one somebody has to know a key to get out of. Maximised rather than frameless by default, because the title bar is where the band and the frequency are written. And a map made bigger now gets a sharper map, which it did not. The window only ever re-examined the ground when the view left the box that had been fetched, so a window opened at its default size and taken to the whole screen kept the map it started with until an aircraft wandered far enough to move it -- on a quiet band, a long time to look at a blurred coastline. Measured before it was believed: 1100 to 1920 asked for nothing and stretched a 1364-pixel map across 1920, then across 3840. It now compares map pixels per degree in hand against what the view wants, and asks when it is being blown up by more than fifteen per cent. That comparison has to be per degree rather than pixel against pixel, which a surviving mutation was what established: the fetched box is a quarter wider than the view, so a map with exactly as many pixels as the window is wide has only four fifths of them on the screen. The two ways of measuring agree everywhere except a narrow band, and the realistic case sits inside it. There is a test pinning that case now. Asking is safe at any size, because the request is keyed on the window's dimensions: once answered, nothing more is asked, which is what stops a window larger than the tile budget can cover from asking all evening. The braille, while this was open. The banners were blocks in capitals; they are braille in mixed case, two dots wide and four tall to a character, which is eight times the detail and is what makes room for two heights of letter at once -- a five-row block font has no second height to spend, so the name came out shouted. Two attempts failed first: thin one-dot strokes came out as confetti, because braille dots render as dots and a one-dot stroke reads as a dotted line rather than a line. What worked was cutting the font small, at cap height seven where there is only one way to draw each letter, and doubling it. Coloured deep blue through cyan to a cool white, which is deliberately not the waterfall ramp the rest of the program draws in: that one has to run to red because it stands in for a spectrum, and a title screen stands in for nothing. One hundred and four new tests. Full suite 2892 passed. Built as 2026-09-24_01. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016PsWPTweCT6pwxKngvVxcg
1415 lines
56 KiB
Python
1415 lines
56 KiB
Python
"""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
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Finding the channel
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def test_the_channel_is_named_as_well_as_numbered():
|
|
"""The number alone does not say whether it is the right one, and the
|
|
name alone does not say what will be tuned."""
|
|
options = ap.AprsOptions()
|
|
assert ap.channel_text(options) == "north-america 144.39 MHz"
|
|
ap.use_region(options, "europe")
|
|
assert ap.channel_text(options) == "europe 144.8 MHz"
|
|
|
|
|
|
def test_a_channel_that_is_no_regions_says_so_rather_than_claiming_one():
|
|
options = ap.AprsOptions(frequency=144_500_000.0)
|
|
assert "not a region" in ap.channel_text(options)
|
|
|
|
|
|
def test_choosing_a_region_moves_the_frequency_with_it():
|
|
"""They are separate settings, so they can be made to disagree; every
|
|
place that chooses a region goes through one function so they cannot."""
|
|
options = ap.use_region(ap.AprsOptions(), "australia")
|
|
assert options.region == "australia"
|
|
assert options.frequency == pytest.approx(145_175_000.0)
|
|
|
|
|
|
def test_the_menu_shows_the_channel_without_going_a_level_down():
|
|
"""It is the setting that decides whether anything is heard at all."""
|
|
assert "north-america 144.39 MHz" in ap.describe(ap.AprsOptions())
|
|
|
|
|
|
def test_the_invented_band_only_carries_traffic_on_its_own_channel():
|
|
"""A simulated band that answered the same everywhere would let the
|
|
channel search pass without ever having searched anything."""
|
|
def listened(hz, blocks=40):
|
|
sky = ap.SimulatedChannel(sample_rate=RATE, seed=3)
|
|
demod, receiver = ap.make_receiver(ap.AprsOptions(rate=RATE))
|
|
sky.tune(hz)
|
|
return sum(len(receiver.feed(demod.step(sky.read_samples(int(RATE)))[0]))
|
|
for _ in range(blocks))
|
|
|
|
assert listened(ap.channel_named("europe")) == 0
|
|
assert listened(ax25.APRS_HZ) >= 2
|
|
|
|
|
|
def test_the_search_finds_the_channel_that_has_traffic_on_it():
|
|
"""The one end-to-end search: every channel really listened to.
|
|
|
|
The rest of these build the results directly, because six listens of a
|
|
simulated band is the most expensive thing in this file and searching it
|
|
twice proves nothing the first search did not.
|
|
"""
|
|
console = Console(width=120, force_terminal=False)
|
|
device = ap.SimulatedChannel(sample_rate=RATE, seed=3)
|
|
with console.capture():
|
|
found = ap.find_channel(console, ap.AprsOptions(rate=RATE),
|
|
seconds=16.0, device=device)
|
|
assert len(found) == len(ax25.APRS_CHANNELS)
|
|
busy = [one for one in found if one.busy]
|
|
assert [one.region for one in busy] == ["north-america"]
|
|
assert busy[0].stations >= 1 and busy[0].best > 0
|
|
|
|
|
|
def searched(busiest="north-america", packets=21, stations=6):
|
|
"""What a search came to, without having to run one."""
|
|
return [ap.Found(region=r, frequency=hz, where=w,
|
|
packets=packets if r == busiest else 0,
|
|
stations=stations if r == busiest else 0,
|
|
best=38.0 if r == busiest else 0.0)
|
|
for r, hz, w in ax25.APRS_CHANNELS]
|
|
|
|
|
|
def test_the_search_reports_which_channel_to_use():
|
|
console = Console(width=120, force_terminal=False)
|
|
with console.capture() as cap:
|
|
best = ap.report_channels(console, searched(), 30.0)
|
|
out = cap.get()
|
|
assert best is not None and best.region == "north-america"
|
|
assert "had the most on it" in out
|
|
for region, _hz, _where in ax25.APRS_CHANNELS:
|
|
assert region in out # every channel accounted for
|
|
|
|
|
|
def test_the_busiest_channel_is_the_one_recommended():
|
|
console = Console(width=120, force_terminal=False)
|
|
with console.capture():
|
|
best = ap.report_channels(console, searched(busiest="australia"), 30.0)
|
|
assert best.region == "australia"
|
|
|
|
|
|
def test_a_silent_band_is_reported_as_silent_and_not_as_an_answer():
|
|
"""A quiet channel is not proof of an empty one: a fixed station beacons
|
|
every half hour, so what this finds is traffic and what it misses is only
|
|
the absence of traffic while it listened."""
|
|
console = Console(width=120, force_terminal=False)
|
|
found = [ap.Found(region=r, frequency=hz, where=w)
|
|
for r, hz, w in ax25.APRS_CHANNELS]
|
|
with console.capture() as cap:
|
|
assert ap.report_channels(console, found, 20.0) is None
|
|
out = cap.get()
|
|
assert "not proof of an empty band" in out
|
|
assert "49 cm" in out # and what to check instead
|
|
|
|
|
|
def test_the_search_leaves_the_log_and_the_files_alone():
|
|
"""It is a measurement, not a session: six short listens should not
|
|
leave six logs and six maps behind."""
|
|
from dataclasses import replace
|
|
|
|
options = ap.AprsOptions(rate=RATE, log=True, csv=True, kml=True)
|
|
trial = replace(options, log=False, report=False, csv=False, kml=False)
|
|
assert not (trial.log or trial.csv or trial.kml or trial.report)
|
|
|
|
|
|
def test_the_search_is_reachable_from_the_command_line():
|
|
from bandsaunter.cli import build_parser
|
|
|
|
args = build_parser().parse_args(["aprs", "--find-channel"])
|
|
assert args.find_channel == 20.0 # a default, not a flag
|
|
args = build_parser().parse_args(["aprs", "--find-channel", "5"])
|
|
assert args.find_channel == 5.0
|
|
assert build_parser().parse_args(["aprs"]).find_channel is None
|
|
|
|
|
|
def test_the_search_runs_from_the_command_line_and_says_what_to_do(monkeypatch):
|
|
from bandsaunter.cli import build_parser, cmd_aprs
|
|
import bandsaunter.cli as cli
|
|
|
|
monkeypatch.setattr(ap, "load_options",
|
|
lambda *a, **kw: ap.AprsOptions(rate=RATE))
|
|
monkeypatch.setattr(ap, "find_channel",
|
|
lambda console, options, seconds: searched())
|
|
console = Console(width=130, force_terminal=False)
|
|
monkeypatch.setattr(cli, "console", console)
|
|
args = build_parser().parse_args(["aprs", "--find-channel", "30"])
|
|
with console.capture() as cap:
|
|
assert cmd_aprs(args) == 0
|
|
out = cap.get()
|
|
assert "north-america had the most on it" in out
|
|
assert "--region north-america" in out
|
|
|
|
|
|
def test_hearing_nothing_points_at_the_channel_search(tmp_path, monkeypatch):
|
|
from bandsaunter.cli import build_parser, cmd_aprs
|
|
import bandsaunter.cli as cli
|
|
|
|
monkeypatch.setattr(ap, "load_options",
|
|
lambda *a, **kw: ap.AprsOptions(rate=RATE, log=False,
|
|
packets_seen=True))
|
|
monkeypatch.setattr(ap, "open_device", lambda console, opts: Silence(2))
|
|
console = Console(width=130, force_terminal=False)
|
|
monkeypatch.setattr(cli, "console", console)
|
|
with console.capture() as cap:
|
|
assert cmd_aprs(build_parser().parse_args(["aprs"])) == 1
|
|
assert "--find-channel" in cap.get()
|
|
|
|
|
|
def test_the_channel_can_be_chosen_from_the_menu(monkeypatch):
|
|
import bandsaunter.tui as tui
|
|
|
|
answers = iter(["c", "2", "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, __import__("bandsaunter.config",
|
|
fromlist=["x"]).ScanConfig())
|
|
out = cap.get()
|
|
assert "Channel / region" in out
|
|
assert "Find the channel" in out
|
|
assert "europe 144.8 MHz" in out # the menu adopted the choice
|
|
for region, _hz, _where in ax25.APRS_CHANNELS:
|
|
assert region in out
|
|
|
|
|
|
def test_a_frequency_can_be_typed_straight_into_the_channel_screen(monkeypatch):
|
|
import bandsaunter.tui as tui
|
|
|
|
answers = iter(["144.5", ""])
|
|
monkeypatch.setattr(tui, "_ask",
|
|
lambda console, prompt, default="": next(answers))
|
|
console = Console(width=120, force_terminal=False)
|
|
options = ap.AprsOptions()
|
|
with console.capture() as cap:
|
|
tui._aprs_channel(console, options)
|
|
assert options.frequency == pytest.approx(144_500_000.0)
|
|
assert "not a region" in cap.get()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# The realtime map
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def station_of(info="=4903.50N/07201.75W>088/036 mobile", source="W1AW-9",
|
|
at=1_000.0, snr=24.0, path=("WIDE1-1*",), destination="APRS",
|
|
times=1):
|
|
net = ap.Net()
|
|
for i in range(times):
|
|
net.add(packet(info, source, at + i * 60, snr, path, destination))
|
|
return net.stations[next(iter(net.stations))]
|
|
|
|
|
|
@pytest.mark.parametrize("info,expected", [
|
|
("=4903.50N/07201.75W>088/036 mobile", "moving"),
|
|
("=4903.50N/07201.75W#wide digi", "digipeater"),
|
|
("@092345z4903.50N/07201.75W_220/004g005t077h50b09900", "weather"),
|
|
("=4903.50N/07201.75W-home station", "fixed"),
|
|
])
|
|
def test_a_station_is_sorted_by_what_sort_of_thing_it_is(info, expected):
|
|
assert ap.station_shade(station_of(info)) == expected
|
|
|
|
|
|
def test_an_object_is_sorted_as_an_object_whatever_it_draws_itself_as():
|
|
net = ap.Net()
|
|
net.add(packet(packets.object_report("EVENT1", 49.0, -72.0, "/:"),
|
|
source="W1AW-9", at=1_000.0))
|
|
assert ap.station_shade(net.stations["EVENT1"]) == "object"
|
|
|
|
|
|
def test_each_sort_gets_its_own_colour_off_the_ramp():
|
|
"""The ramp because it is the one set of colours every theme defines: on
|
|
the default map it runs warm to cold and on the phosphor themes dim to
|
|
bright, so a digipeater stays distinguishable from a car on all five."""
|
|
from bandsaunter.flightmap import RAMP, RAMP_STEPS
|
|
|
|
shades = {kind: ap.blip_for(station_of(info)).colour_index
|
|
for kind, info in (
|
|
("moving", "=4903.50N/07201.75W>088/036 x"),
|
|
("digi", "=4903.50N/07201.75W#x"),
|
|
("weather", "@092345z4903.50N/07201.75W_220/004t077"),
|
|
("fixed", "=4903.50N/07201.75W-x"))}
|
|
assert len(set(shades.values())) == 4
|
|
for index in shades.values():
|
|
assert RAMP <= index < RAMP + RAMP_STEPS
|
|
assert shades["moving"] > shades["fixed"]
|
|
|
|
|
|
@pytest.mark.parametrize("info,shape", [
|
|
("=4903.50N/07201.75W>088/036 mobile", "vehicle"),
|
|
("=4903.50N/07201.75W-still here", "station"),
|
|
])
|
|
def test_something_going_somewhere_is_drawn_differently_from_a_place(info,
|
|
shape):
|
|
assert ap.blip_for(station_of(info)).shape == shape
|
|
|
|
|
|
def test_the_box_heading_says_the_callsign_once():
|
|
"""An aeroplane has two names, a flight number and a 24-bit address, and
|
|
the heading prints both. A station has one."""
|
|
blip = ap.blip_for(station_of())
|
|
assert blip.icao == "W1AW-9" and blip.callsign == ""
|
|
assert blip.name == "W1AW-9"
|
|
|
|
|
|
def test_the_box_says_what_a_station_is_and_where_and_what_it_said():
|
|
rows = dict((label, value) for label, value, _flag
|
|
in ap.station_lines(station_of(), home=(49.0, -72.0)))
|
|
assert rows["symbol"] == "car"
|
|
assert "km" in rows["away"]
|
|
assert "km/h" in rows["moving"]
|
|
assert rows["via"] == "WIDE1-1*"
|
|
assert rows["packets"] == "1"
|
|
assert rows["signal"] == "24 dB"
|
|
|
|
|
|
def test_a_weather_station_puts_its_weather_in_the_box():
|
|
station = station_of("@092345z4903.50N/07201.75W_220/004g005t077h50b09900",
|
|
source="KB1XYZ")
|
|
rows = dict((label, value) for label, value, _f
|
|
in ap.station_lines(station))
|
|
assert "temperature" in rows and "humidity" in rows
|
|
assert rows["temperature"].endswith(" C")
|
|
|
|
|
|
def test_the_box_says_who_placed_an_object():
|
|
net = ap.Net()
|
|
net.add(packet(packets.object_report("EVENT1", 49.0, -72.0),
|
|
source="W1AW-9", at=1_000.0))
|
|
rows = dict((label, value) for label, value, _f
|
|
in ap.station_lines(net.stations["EVENT1"]))
|
|
assert rows["placed by"] == "W1AW-9"
|
|
|
|
|
|
def test_the_box_says_how_much_arrived_without_a_relay():
|
|
net = ap.Net()
|
|
net.add(packet(at=1_000.0, path=("WIDE1-1*",)))
|
|
net.add(packet(at=1_060.0, path=()))
|
|
rows = dict((label, value) for label, value, _f
|
|
in ap.station_lines(net.stations["W1AW-9"]))
|
|
assert rows["packets"] == "2 (1 direct)"
|
|
|
|
|
|
def test_the_box_reads_in_either_system():
|
|
station = station_of()
|
|
metric = dict((l, v) for l, v, _f in ap.station_lines(station,
|
|
(49.0, -72.0)))
|
|
imperial = dict((l, v) for l, v, _f in ap.station_lines(station,
|
|
(49.0, -72.0),
|
|
imperial=True))
|
|
assert "km/h" in metric["moving"] and "mph" in imperial["moving"]
|
|
assert "km" in metric["away"] and "mi" in imperial["away"]
|
|
|
|
|
|
def test_a_station_with_no_position_is_not_put_on_the_map():
|
|
"""A pin at nowhere puts a station off the west coast of Africa."""
|
|
net = ap.Net()
|
|
net.add(packet(">Monitoring 146.52", at=1_000.0))
|
|
assert [s for s in net.all() if s.position is not None] == []
|
|
|
|
|
|
# -- the map options --------------------------------------------------------
|
|
|
|
@pytest.mark.parametrize("flags,key,value", [
|
|
(["--radius", "25"], "radius", 25.0),
|
|
(["--theme", "phosphor"], "theme", "phosphor"),
|
|
(["--map-brightness", "40"], "map_brightness", 40),
|
|
(["--no-basemap"], "basemap", False),
|
|
(["--no-window-rings"], "window_rings", False),
|
|
(["--box-opacity", "0"], "box_opacity", 0),
|
|
(["--no-trails"], "trails", False),
|
|
(["--tiles", "http://x/{z}/{x}/{y}.png"], "tile_url",
|
|
"http://x/{z}/{x}/{y}.png"),
|
|
])
|
|
def test_every_map_flag_reaches_the_option_it_names(flags, key, value):
|
|
from bandsaunter.cli import build_parser
|
|
|
|
args = build_parser().parse_args(["aprs"] + flags)
|
|
options = ap.AprsOptions()
|
|
for flag, name in (("radius", "radius"), ("theme", "theme"),
|
|
("map_brightness", "map_brightness"),
|
|
("basemap", "basemap"),
|
|
("window_rings", "window_rings"),
|
|
("box_opacity", "box_opacity"),
|
|
("trails", "trails"), ("tile_url", "tile_url")):
|
|
got = getattr(args, flag, None)
|
|
if got is not None:
|
|
setattr(options, name, got)
|
|
assert getattr(options, key) == value
|
|
|
|
|
|
def test_the_window_is_asked_for_by_a_flag_and_not_a_setting():
|
|
"""Like the aircraft window: whether to open one is a thing you say when
|
|
you run it, not a thing you keep."""
|
|
from bandsaunter.cli import build_parser
|
|
|
|
assert build_parser().parse_args(["aprs", "--window"]).window is True
|
|
assert build_parser().parse_args(["aprs"]).window is False
|
|
assert not hasattr(ap.AprsOptions(), "window")
|
|
|
|
|
|
def test_the_menu_offers_the_map_and_says_the_marks_stay(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 "Realtime map" in out
|
|
assert "they stay" in out
|
|
assert "the map" in out # the option group
|
|
|
|
|
|
def test_the_window_says_so_rather_than_failing_when_qt_is_missing(
|
|
tmp_path, monkeypatch):
|
|
from bandsaunter import livemap
|
|
|
|
monkeypatch.setattr(livemap, "available", lambda: False)
|
|
console = Console(width=120, force_terminal=False)
|
|
with console.capture() as cap:
|
|
heard = ap.watch(console, ap.AprsOptions(), str(tmp_path))
|
|
assert heard.stations == 0
|
|
assert "no window to open" in cap.get()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Where the aerial is
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def test_the_aerial_position_is_taken_from_the_aircraft_settings_if_unset(
|
|
tmp_path, monkeypatch):
|
|
"""One aerial, one roof, one position.
|
|
|
|
Which band it is pointed at today does not move it, so somebody who has
|
|
already told the aircraft side where they are should not have to say it
|
|
again -- and, having said it once, would reasonably expect the flag.
|
|
"""
|
|
from bandsaunter import aircraft
|
|
|
|
aircraft.save_options(
|
|
aircraft.AircraftOptions(location="47.55,-122.30"), tmp_path)
|
|
monkeypatch.setattr(aircraft, "options_path",
|
|
lambda directory=None: tmp_path / "aircraft.yaml")
|
|
assert ap.receiver_at(ap.AprsOptions()) == (47.55, -122.30)
|
|
|
|
|
|
def test_this_sections_own_position_wins_where_it_has_one(tmp_path,
|
|
monkeypatch):
|
|
"""Two receivers in two places is a thing that happens, and is exactly
|
|
what the separate setting is for."""
|
|
from bandsaunter import aircraft
|
|
|
|
aircraft.save_options(
|
|
aircraft.AircraftOptions(location="47.55,-122.30"), tmp_path)
|
|
monkeypatch.setattr(aircraft, "options_path",
|
|
lambda directory=None: tmp_path / "aircraft.yaml")
|
|
here = ap.receiver_at(ap.AprsOptions(location="51.5,-0.13"))
|
|
assert here == (51.5, -0.13)
|
|
|
|
|
|
def test_neither_side_knowing_is_no_position_rather_than_a_wrong_one(
|
|
tmp_path, monkeypatch):
|
|
from bandsaunter import aircraft
|
|
|
|
monkeypatch.setattr(aircraft, "options_path",
|
|
lambda directory=None: tmp_path / "none.yaml")
|
|
assert ap.receiver_at(ap.AprsOptions()) is None
|
|
|
|
|
|
def test_the_window_gets_the_position_so_the_flag_is_drawn(tmp_path,
|
|
monkeypatch):
|
|
from bandsaunter import aircraft, livemap
|
|
|
|
aircraft.save_options(
|
|
aircraft.AircraftOptions(location="47.55,-122.30"), tmp_path)
|
|
monkeypatch.setattr(aircraft, "options_path",
|
|
lambda directory=None: tmp_path / "aircraft.yaml")
|
|
built = {}
|
|
monkeypatch.setattr(livemap, "available", lambda: True)
|
|
monkeypatch.setattr(livemap, "show",
|
|
lambda sky, title: built.update(home=sky.home,
|
|
waiting=sky.waiting))
|
|
monkeypatch.setattr(ap, "open_device", lambda console, opts: Silence(1))
|
|
console = Console(width=120, force_terminal=False)
|
|
with console.capture():
|
|
ap.watch(console, ap.AprsOptions(rate=RATE, log=False, report=False,
|
|
basemap=False), str(tmp_path))
|
|
assert built["home"] == (47.55, -122.30)
|
|
# And the empty picture no longer talks about aeroplanes.
|
|
assert "1090" not in built["waiting"] and "144.39 MHz" in built["waiting"]
|
|
assert "aircraft" not in built["waiting"]
|
|
|
|
|
|
@pytest.mark.parametrize("units, unit, nm", [
|
|
("metric", "kph", 100 / 1.852),
|
|
("imperial", "mph", 100 / 1.150779),
|
|
])
|
|
def test_the_window_is_built_in_the_unit_being_shown(units, unit, nm,
|
|
tmp_path, monkeypatch):
|
|
"""Not just the helpers: the window that actually gets opened. The
|
|
rings, their labels and the scale along the bottom all read off what is
|
|
handed over here."""
|
|
from bandsaunter import livemap
|
|
|
|
built = {}
|
|
monkeypatch.setattr(livemap, "available", lambda: True)
|
|
monkeypatch.setattr(livemap, "show",
|
|
lambda sky, title: built.update(
|
|
unit=sky.unit, radius_nm=sky.radius_nm))
|
|
monkeypatch.setattr(ap, "open_device", lambda console, opts: Silence(1))
|
|
console = Console(width=120, force_terminal=False)
|
|
with console.capture():
|
|
ap.watch(console, ap.AprsOptions(rate=RATE, log=False, report=False,
|
|
basemap=False, units=units,
|
|
radius=100.0), str(tmp_path))
|
|
assert built["unit"] == unit
|
|
assert built["radius_nm"] == pytest.approx(nm, rel=1e-6)
|
|
|
|
|
|
def test_it_says_where_the_position_came_from_rather_than_assuming(
|
|
tmp_path, monkeypatch):
|
|
"""A position inherited from another section is a convenience right up
|
|
until somebody has moved and changed only one of them."""
|
|
from bandsaunter import aircraft, livemap
|
|
|
|
aircraft.save_options(
|
|
aircraft.AircraftOptions(location="47.55,-122.30"), tmp_path)
|
|
monkeypatch.setattr(aircraft, "options_path",
|
|
lambda directory=None: tmp_path / "aircraft.yaml")
|
|
monkeypatch.setattr(livemap, "available", lambda: True)
|
|
monkeypatch.setattr(livemap, "show", lambda sky, title: None)
|
|
monkeypatch.setattr(ap, "open_device", lambda console, opts: Silence(1))
|
|
console = Console(width=120, force_terminal=False)
|
|
with console.capture() as cap:
|
|
ap.watch(console, ap.AprsOptions(rate=RATE, log=False, report=False,
|
|
basemap=False), str(tmp_path))
|
|
assert "from the aircraft settings" in cap.get()
|
|
|
|
|
|
def test_knowing_nowhere_says_what_that_costs(tmp_path, monkeypatch):
|
|
from bandsaunter import aircraft
|
|
|
|
monkeypatch.setattr(aircraft, "options_path",
|
|
lambda directory=None: tmp_path / "none.yaml")
|
|
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, log=False,
|
|
packets_seen=True), str(tmp_path))
|
|
out = cap.get()
|
|
assert "no flag" in out and "--at" in out
|
|
|
|
|
|
def _haversine_km(a, b):
|
|
"""Great-circle distance, written here rather than imported, so that a
|
|
test of how far the rings are drawn is not asking the drawing."""
|
|
import math
|
|
|
|
lat1, lon1 = math.radians(a[0]), math.radians(a[1])
|
|
lat2, lon2 = math.radians(b[0]), math.radians(b[1])
|
|
h = (math.sin((lat2 - lat1) / 2) ** 2
|
|
+ math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2)
|
|
return 2 * 6371.0088 * math.asin(math.sqrt(h))
|
|
|
|
|
|
def _rings_as_drawn(options):
|
|
"""Every ring the window would draw: how far it really is from the flag,
|
|
in kilometres, and what is written beside it."""
|
|
from bandsaunter.flightlog import move
|
|
from bandsaunter.flightmap import ring_labels
|
|
|
|
home = (47.6062, -122.3322)
|
|
out = []
|
|
for nm, text in ring_labels(ap.radius_in_nm(options),
|
|
ap.map_unit(options)):
|
|
edge = move(home[0], home[1], 0.0, nm)
|
|
out.append((_haversine_km(home, edge), text))
|
|
return out
|
|
|
|
|
|
@pytest.mark.parametrize("units, label, per_km", [
|
|
("metric", "km", 1.0),
|
|
("imperial", "mi", 1.609344),
|
|
])
|
|
def test_the_rings_are_drawn_at_the_distance_they_are_labelled(
|
|
units, label, per_km):
|
|
"""Both halves of it. Writing miles beside a ring drawn at kilometres
|
|
is worse than writing nothing: it is a wrong answer given confidently,
|
|
and the ring is the thing a distance gets judged against by eye."""
|
|
options = ap.defaults()
|
|
options.units, options.radius = units, 100.0
|
|
drawn = _rings_as_drawn(options)
|
|
assert [text for _km, text in drawn] == [f"25 {label}", f"50 {label}",
|
|
f"75 {label}"]
|
|
for km, text in drawn:
|
|
said = float(text.split()[0])
|
|
assert abs(km - said * per_km) < 0.5, (km, text)
|
|
|
|
|
|
def test_the_window_reaches_as_far_as_it_was_told_in_the_unit_being_shown():
|
|
"""A hundred set in imperial is a hundred miles, not a hundred
|
|
kilometres with miles written on it."""
|
|
metric, imperial = ap.defaults(), ap.defaults()
|
|
metric.units, metric.radius = "metric", 100.0
|
|
imperial.units, imperial.radius = "imperial", 100.0
|
|
assert ap.radius_in_nm(metric) == pytest.approx(100 / 1.852, rel=1e-6)
|
|
assert ap.radius_in_nm(imperial) == pytest.approx(100 / 1.150779,
|
|
rel=1e-6)
|
|
assert ap.radius_in_nm(imperial) > ap.radius_in_nm(metric)
|
|
|
|
|
|
def test_the_unit_the_window_measures_in_follows_the_one_being_shown():
|
|
"""The scale along the bottom and the rings read off the same setting
|
|
as the tables, so the window cannot disagree with the report."""
|
|
options = ap.defaults()
|
|
options.units = "metric"
|
|
assert ap.map_unit(options) == "kph"
|
|
options.units = "imperial"
|
|
assert ap.map_unit(options) == "mph"
|
|
|
|
|
|
def test_the_box_gives_the_position_in_figures():
|
|
"""A mark shows where a station is; a number is what gets written down."""
|
|
rows = dict((label, value) for label, value, _f
|
|
in ap.station_lines(station_of()))
|
|
assert rows["position"] == "49.0583N 72.0292W"
|
|
|
|
|
|
def test_the_box_shows_a_vague_position_as_vague():
|
|
"""Blanking the minutes is a deliberate act by the operator, and the
|
|
figures are the only place that shows."""
|
|
rows = dict((label, value) for label, value, _f
|
|
in ap.station_lines(station_of("=49 . N/072 . W-vague")))
|
|
assert "±" in rows["position"]
|
|
|
|
|
|
def test_a_station_that_never_said_where_it_is_has_no_position_row():
|
|
rows = dict((label, value) for label, value, _f
|
|
in ap.station_lines(station_of(">Monitoring 146.52")))
|
|
assert "position" not in rows
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Who each station is
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _book(tmp_path, entries=()):
|
|
"""A register that knows what it is told and asks nobody anything."""
|
|
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
|
|
|
book = CallsignBook(online=False, cache=tmp_path / "callsigns.json")
|
|
for call, name, where in entries:
|
|
book._entries[call] = Callsign(
|
|
call=call, name=name, location=where, status="found",
|
|
version=CACHE_VERSION, fetched_at=time.time())
|
|
return book
|
|
|
|
|
|
@pytest.mark.parametrize("given,wanted", [
|
|
("W1AW-9", "W1AW"), ("KU0W", "KU0W"), ("VK4BLE-7*", "VK4BLE"),
|
|
("n0call-15", "N0CALL"), ("", ""),
|
|
])
|
|
def test_the_licensed_callsign_is_found_inside_the_aprs_one(given, wanted):
|
|
"""An SSID says which of a station's radios this is -- the ninth is a
|
|
car, the second a digipeater -- and a star marks the hop a packet came
|
|
through. No licence register has heard of either."""
|
|
assert ap.base_call(given) == wanted
|
|
|
|
|
|
def test_a_station_is_looked_up_once_when_it_is_first_heard(tmp_path):
|
|
book = _book(tmp_path)
|
|
net = ap.Net(book=book)
|
|
for _ in range(5):
|
|
net.add(packet(source="W1AW-9"))
|
|
net.add(packet(source="KU0W"))
|
|
# One entry per licensed callsign, not per packet and not per SSID.
|
|
assert set(book._entries) == {"W1AW", "KU0W"}
|
|
|
|
|
|
def test_an_object_somebody_placed_is_not_looked_up(tmp_path):
|
|
"""An object is a marker one station put on the map on behalf of
|
|
something that has no licence of its own -- a net, a hilltop, a
|
|
storm -- so asking who it is licensed to is asking the wrong question."""
|
|
book = _book(tmp_path)
|
|
net = ap.Net(book=book)
|
|
net.add(packet(";LEADVL *111111z3900.00N/10500.00W- a place",
|
|
source="W1AW"))
|
|
assert "LEADVL" not in book._entries
|
|
|
|
|
|
def test_the_name_arrives_without_the_display_waiting_for_it(tmp_path):
|
|
"""A table that stopped for a network request would stop for every new
|
|
station on a busy channel."""
|
|
book = _book(tmp_path)
|
|
net = ap.Net(book=book)
|
|
net.add(packet(source="W1AW-9"))
|
|
who = ap.licensee(net, "W1AW-9")
|
|
assert who is not None and who.call == "W1AW"
|
|
# Nothing is known yet and that is not an error.
|
|
assert ap.who_text(who) in ("", "…", "United States")
|
|
|
|
|
|
def test_a_name_that_has_arrived_is_shown_with_where_it_is(tmp_path):
|
|
book = _book(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
|
"Newington, CT")])
|
|
net = ap.Net(book=book)
|
|
net.add(packet(source="W1AW-9"))
|
|
assert ap.who_text(ap.licensee(net, "W1AW-9")) == \
|
|
"ARRL HQ Operators Club — Newington, CT"
|
|
|
|
|
|
def test_a_station_the_register_cannot_know_still_says_where_it_is_from():
|
|
"""The databases are United States registers. A blank cell beside an
|
|
Australian callsign reads as a lookup that failed rather than as a
|
|
question that was never going to be answered, and the country comes out
|
|
of the callsign's own structure with no network at all."""
|
|
from bandsaunter.callsign import Callsign
|
|
|
|
who = Callsign(call="VK4BLE", country="Australia", status="unlisted")
|
|
assert ap.who_text(who) == "Australia"
|
|
|
|
|
|
def test_no_lookups_at_all_when_they_are_turned_off():
|
|
book = ap.open_book(ap.AprsOptions(lookup=False))
|
|
assert book.online is False
|
|
|
|
|
|
def test_the_box_on_the_map_says_who_the_station_is(tmp_path):
|
|
book = _book(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
|
"Newington, CT")])
|
|
net = ap.Net(book=book)
|
|
station = net.add(packet(source="W1AW-9"))
|
|
lines = ap.station_lines(station, None, False, ap.licensee(net, "W1AW-9"))
|
|
labels = [label for label, _value, _flag in lines]
|
|
assert labels[:2] == ["licensed to", "at"], labels
|
|
assert lines[0][1] == "ARRL HQ Operators Club"
|
|
assert lines[1][1] == "Newington, CT"
|
|
|
|
|
|
def test_the_box_says_nothing_about_a_licence_it_does_not_have(tmp_path):
|
|
net = ap.Net(book=_book(tmp_path))
|
|
station = net.add(packet(source="W1AW-9"))
|
|
lines = ap.station_lines(station, None, False, None)
|
|
assert "licensed to" not in [label for label, _v, _f in lines]
|
|
|
|
|
|
def test_the_report_gives_a_column_for_who_each_station_is(tmp_path):
|
|
book = _book(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
|
"Newington, CT")])
|
|
net = ap.Net(book=book)
|
|
net.add(packet(source="W1AW-9"))
|
|
console = Console(width=160, force_terminal=False)
|
|
with console.capture() as caught:
|
|
ap.report(console, net, ap.AprsOptions(lookup=True))
|
|
shown = caught.get()
|
|
assert "licensed to" in shown
|
|
assert "ARRL HQ Operators Club" in shown
|
|
|
|
|
|
def test_the_report_leaves_the_column_out_when_lookups_are_off(tmp_path):
|
|
net = ap.Net(book=_book(tmp_path))
|
|
net.add(packet(source="W1AW-9"))
|
|
console = Console(width=160, force_terminal=False)
|
|
with console.capture() as caught:
|
|
ap.report(console, net, ap.AprsOptions(lookup=False))
|
|
assert "licensed to" not in caught.get()
|
|
|
|
|
|
def test_the_answers_are_kept_on_the_disk_and_shared(tmp_path):
|
|
"""The point of the whole thing: the same net logged night after night
|
|
is asked about once a month, and every part of this program that
|
|
resolves a callsign reads the same file."""
|
|
from bandsaunter.callsign import CallsignBook, _cache_path
|
|
|
|
book = _book(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
|
"Newington, CT")])
|
|
book._dirty = True
|
|
book.save()
|
|
again = CallsignBook(online=False, cache=tmp_path / "callsigns.json")
|
|
assert again.get("W1AW").name == "ARRL HQ Operators Club"
|
|
# And by default it is the one file everything else uses.
|
|
assert _cache_path() == ap.open_book(ap.defaults()).cache_path
|
|
|
|
|
|
def test_the_answers_are_written_to_the_disk_when_the_run_ends(tmp_path):
|
|
"""Without this the lookups happen and are thrown away, so every
|
|
evening asks the register about the same net again -- which is the one
|
|
thing caching them was for, and is invisible from inside a single run
|
|
because the answers are all in memory while it lasts."""
|
|
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
|
|
|
where = tmp_path / "callsigns.json"
|
|
book = CallsignBook(online=False, cache=where)
|
|
net = ap.Net(book=book)
|
|
net.add(packet(source="W1AW-9"))
|
|
book._entries["W1AW"] = Callsign(call="W1AW", name="ARRL HQ",
|
|
location="Newington, CT",
|
|
status="found", version=CACHE_VERSION,
|
|
fetched_at=time.time())
|
|
book._dirty = True
|
|
|
|
heard = ap.Heard()
|
|
heard.net = net
|
|
console = Console(width=120, force_terminal=False)
|
|
with console.capture():
|
|
ap.finish(console, ap.AprsOptions(report=False, csv=False, kml=False),
|
|
str(tmp_path), heard)
|
|
assert where.exists(), "the run ended without writing what it learned"
|
|
assert CallsignBook(online=False, cache=where).get("W1AW").name == "ARRL HQ"
|
|
|
|
|
|
def test_a_quiet_evening_still_keeps_what_it_learned(tmp_path):
|
|
"""A run that heard one station and no more still found out who that
|
|
station was. The early return for an empty net used to skip the
|
|
saving with it."""
|
|
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
|
|
|
where = tmp_path / "callsigns.json"
|
|
book = CallsignBook(online=False, cache=where)
|
|
book._entries["KU0W"] = Callsign(call="KU0W", name="Rod R Gowdy",
|
|
status="found", version=CACHE_VERSION,
|
|
fetched_at=time.time())
|
|
book._dirty = True
|
|
heard = ap.Heard()
|
|
heard.net = ap.Net(book=book) # nothing heard at all
|
|
console = Console(width=120, force_terminal=False)
|
|
with console.capture() as caught:
|
|
ap.finish(console, ap.AprsOptions(report=False), str(tmp_path), heard)
|
|
assert "nothing heard" in caught.get()
|
|
assert CallsignBook(online=False, cache=where).get("KU0W").name == \
|
|
"Rod R Gowdy"
|