Cache what has been looked up, make it browsable, and say where this lives
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
This commit is contained in:
parent
93120b80a6
commit
2665a17a22
27 changed files with 3733 additions and 49 deletions
|
|
@ -38,7 +38,7 @@ a Raspberry Pi is the easier answer.
|
|||
## A. Debian, Ubuntu, Mint: the package
|
||||
|
||||
```bash
|
||||
git clone <the repository> bandsaunter
|
||||
git clone https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
cd bandsaunter
|
||||
./packaging/build-deb.sh # writes dist/bandsaunter_<version>_all.deb
|
||||
sudo apt install ./dist/bandsaunter_*.deb
|
||||
|
|
@ -83,7 +83,7 @@ sudo apt install librtlsdr0 # Debian/Ubuntu/Mint
|
|||
# sudo pacman -S rtl-sdr # Arch
|
||||
# brew install librtlsdr # macOS
|
||||
|
||||
git clone <the repository> bandsaunter
|
||||
git clone https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
cd bandsaunter
|
||||
python3 -m venv .venv
|
||||
. .venv/bin/activate
|
||||
|
|
|
|||
257
README.md
257
README.md
|
|
@ -41,6 +41,11 @@ transcripts, identifications and playback, in one screen.
|
|||
**[INSTALL.md](INSTALL.md) has the step-by-step version**, including the
|
||||
optional dependencies and what goes wrong first. The short forms:
|
||||
|
||||
```bash
|
||||
git clone https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
cd bandsaunter
|
||||
```
|
||||
|
||||
### From a package (Debian, Ubuntu, Mint)
|
||||
|
||||
```bash
|
||||
|
|
@ -589,6 +594,54 @@ deliberately not measured from the spectrum -- a spread estimated from the
|
|||
data reads five times higher across the packed broadcast FM band than on empty
|
||||
spectrum, which would suppress exactly the stations you are looking for.
|
||||
|
||||
## The title screen
|
||||
|
||||
Both programs draw one when they start, in a gradient that runs deep blue
|
||||
through electric blue and cyan to a cool white across the width. Deliberately
|
||||
*not* the waterfall ramp the rest of the program draws in: that one carries on
|
||||
through green and yellow to red because it stands in for a spectrum and has to
|
||||
mean something. A title screen means nothing, so it is allowed to be a colour
|
||||
scheme — and blue is never the weakest channel anywhere along it, which is
|
||||
what keeps it cold.
|
||||
|
||||
```
|
||||
⣿⠛⠛⠛⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⠀⣤⠛⠛⠛⠛⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
|
||||
⣿⣤⣤⣤⠛⠀⠀⠛⠛⠛⣤⠀⣿⣤⠛⠛⣤⠀⣤⠛⠛⠛⣤⠀⠛⣤⣤⣤⠀⠀⠀⠛⠛⠛⣤⠀⣿⠀⠀⠀⣿⠀⣿⣤⠛⠛⣤⠀⣤⣿⣤⣤⠀⠀⣤⠛⠛⠛⣤⠀⣿⣤⠛⠛⣤⠀
|
||||
⣿⠀⠀⠀⣿⠀⣤⠛⠛⠛⣿⠀⣿⠀⠀⠀⣿⠀⣿⠀⠀⠀⣿⠀⠀⠀⠀⠀⣿⠀⣤⠛⠛⠛⣿⠀⣿⠀⠀⣤⣿⠀⣿⠀⠀⠀⣿⠀⠀⣿⠀⠀⠀⠀⣿⠛⠛⠛⠛⠀⣿⠀⠀⠀⠀⠀
|
||||
⠛⠛⠛⠛⠀⠀⠀⠛⠛⠛⠛⠀⠛⠀⠀⠀⠛⠀⠀⠛⠛⠛⠀⠀⠛⠛⠛⠛⠀⠀⠀⠛⠛⠛⠛⠀⠀⠛⠛⠀⠛⠀⠛⠀⠀⠀⠛⠀⠀⠛⠛⠛⠀⠀⠀⠛⠛⠛⠀⠀⠛⠀⠀⠀⠀⠀
|
||||
|
||||
Conceived by: The Dust Council
|
||||
100% AI Coded by Claude Code.
|
||||
```
|
||||
|
||||
**Drawn in braille**, two dots wide and four tall to a character. That is eight
|
||||
times the detail a block character gives, and it is what makes room for
|
||||
capitals and lowercase at the same height — a five-row block font has no
|
||||
second height to spend, so the name comes out as BANDSAUNTER, which is not its
|
||||
name. It also reads as something drawn rather than as masonry.
|
||||
|
||||
The font is cut by hand rather than pulled in: twelve letters at cap height
|
||||
seven, and a figlet library to draw that would be the largest thing in the
|
||||
package's requirements. Cut small on purpose — at seven rows there is only one
|
||||
way to draw each letter, and so no room to draw it badly — and then doubled,
|
||||
because **a stroke two dots thick reads as a line where one dot thick reads as
|
||||
a dotted line**. That is the one real difficulty in drawing with braille, and
|
||||
the reason a first attempt at thin elegant strokes came out as confetti.
|
||||
|
||||
**It never appears where it would be in the way.** Everything here can be
|
||||
piped into something else — the band table, the sensor list, a line per packet
|
||||
— and a banner in the middle of that is corruption rather than decoration, so
|
||||
anything that is not a terminal gets nothing at all. `--help` and a bad
|
||||
argument say their piece without one over the top, since it is drawn after the
|
||||
arguments are parsed. `--no-splash` turns it off on a terminal too, and
|
||||
`BANDSAUNTER_NO_SPLASH=1` turns it off for good.
|
||||
|
||||
`saunterbrowse` pauses for a moment on its own banner, because what follows
|
||||
takes the whole screen: the browser runs on the alternate screen, so without a
|
||||
beat there the banner would be replaced in the same tenth of a second it was
|
||||
drawn in. It is still on the normal screen afterwards, and comes back when you
|
||||
quit.
|
||||
|
||||
## Signal identification
|
||||
|
||||
Every recording is classified from its own IQ. The classifier measures
|
||||
|
|
@ -1185,9 +1238,21 @@ only in the same pass as a piece of map, which meant they queued behind a
|
|||
hundred and twenty tiles coming off a network, and once the map was in hand
|
||||
there were no more passes and they were never fetched at all.
|
||||
|
||||
**The window opens maximised.** This is a map, and the thing anybody wants
|
||||
more of is map; it used to open at 1100×800 whatever the screen was. Un-maximise
|
||||
it and you get a sensible window back, because the restored size is set before
|
||||
it maximises rather than left to the toolkit to guess.
|
||||
|
||||
`d` cycles the detail — full box, just height and speed, or symbols alone —
|
||||
for when the sky is busy. `t` toggles trails, `g` the map underneath, `[`/`]`
|
||||
its brightness, `+`/`-` the range, `q` closes it.
|
||||
for when the sky is busy. `t` toggles trails, `g` the map underneath, `f` true
|
||||
full screen and back, `[`/`]` its brightness, `+`/`-` the range, `q` closes it.
|
||||
|
||||
`f` is maximised rather than full screen by default on purpose: the title bar
|
||||
is where the band and the frequency are written, and a window with no frame is
|
||||
one you have to know a key to get out of. The key is along the top of the
|
||||
screen for that reason, not only in the manual. Leaving full screen returns to
|
||||
maximised rather than to the small size it was built at — coming out of full
|
||||
screen should not shrink the map to a quarter of the display.
|
||||
|
||||
Aircraft fade out here too, over `--fade` seconds, keeping their symbol and
|
||||
losing their box as they go — a box at a tenth of its colour is something in
|
||||
|
|
@ -1614,6 +1679,33 @@ are met rather than assumed:
|
|||
- **the attribution is drawn onto the picture**, because a GIF travels
|
||||
without the readme that would otherwise carry it.
|
||||
|
||||
**The finished map is cached too**, in `~/.cache/bandsaunter/ground`. The
|
||||
tiles always were, so a second evening on the same view has never touched the
|
||||
network — but it still cost decoding forty PNGs and resampling a megapixel and
|
||||
a half into this program's own projection, every time a window opened, for an
|
||||
answer that cannot have changed. A coastline does not move. Measured on a
|
||||
150-mile view at 1364×992:
|
||||
|
||||
```
|
||||
first ever 5.12 s 18 tiles off the network
|
||||
tiles cached 0.61 s no network, all the work redone
|
||||
map cached 0.01 s no network, no work
|
||||
```
|
||||
|
||||
Both windows and both kinds of still picture share it, because all four reach
|
||||
the ground through one function. The key is the piece of world, the size of
|
||||
the picture and the number of shades, with the box rounded to about a hundred
|
||||
metres so a view that drifted by a pixel is answered rather than rebuilt. A
|
||||
map with squares missing is **not** kept: caching a hole would keep it for a
|
||||
month, and the whole point of calling a partial map provisional is that it
|
||||
gets asked for again.
|
||||
|
||||
Caches that only grow are a liability, so this one is pruned to 400 MB
|
||||
whenever a map is written, throwing away the least recently *used* files
|
||||
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 would be
|
||||
the wrong way round.
|
||||
|
||||
`--no-basemap` draws the tracks on their own, `--tiles URL` points at another
|
||||
server (your own, if you run one), and when there is no network and nothing
|
||||
cached the picture falls back to the plain grid it drew before.
|
||||
|
|
@ -1624,6 +1716,27 @@ at 960, and about 1.4× the width is fetched deliberately and then averaged
|
|||
down — a downscaled tile is sharp and an upscaled one is not, so it is better
|
||||
to fetch too much and shrink it than to fetch too little and stretch it.
|
||||
|
||||
**A window made bigger fetches a sharper map.** The map underneath is fetched
|
||||
for the size of the window at the time, and a map of the right piece of world
|
||||
goes on being a map of the right piece of world however far it is then
|
||||
stretched — so nothing else notices. A window opened at its default size and
|
||||
taken to the whole screen used to keep the map it started with until an
|
||||
aircraft wandered far enough to move the view out of the fetched box, which on
|
||||
a quiet band is a long time to look at a blurred coastline. It now compares
|
||||
**map pixels per degree in hand against what the view wants**, and asks for a
|
||||
better one when it is being blown up by more than 15%. Less than that and a
|
||||
window nudged a few pixels would send an evening to a tile server.
|
||||
|
||||
The measurement has to be per degree rather than in raw pixels, because the
|
||||
fetched box is a quarter wider than the view: a map with exactly as many
|
||||
pixels as the window is wide has only four fifths of them on the screen, and
|
||||
counting pixel-for-pixel would call that sharp.
|
||||
|
||||
Asking is safe at any size. The request is keyed on the window's dimensions,
|
||||
so once it has been answered nothing more is asked — which is what stops a
|
||||
window bigger than the tile budget can cover from asking all evening. At 4K
|
||||
the map is enlarged by design, as below.
|
||||
|
||||
The window fetches a little more world than it shows, so that panning does not
|
||||
leave the ground blank, and it fetches that bigger piece **at the bigger
|
||||
piece's own size**: what the window then shows comes out pixel for pixel with
|
||||
|
|
@ -2478,7 +2591,7 @@ box beside each station, a leader line to the mark it belongs to, range rings
|
|||
around the aerial and a red flag where you are.
|
||||
|
||||
```
|
||||
144.39 MHz 6 on the map 6 seen 812 packets 1:01:40 d detail t trails g map q quit
|
||||
144.39 MHz 6 on the map 6 seen 812 packets 1:01:40 d detail t trails g map f full q quit
|
||||
┌──────────────────┐
|
||||
┌────────────────────┐ ◈────────┤ W1AW-1 │
|
||||
│ K7XYZ-3 │ │ │ symbol digipeater│
|
||||
|
|
@ -2525,8 +2638,9 @@ evening's accumulation there are usually more marks than there is room for
|
|||
boxes, so the most recently heard get them.
|
||||
|
||||
The same keys as the aircraft map: `d` cycles how much each box says, `t`
|
||||
trails, `g` the map underneath, `[` and `]` its brightness, `+`/`-` the range,
|
||||
`q` quits. `--radius` sets how far it reaches to begin with and `--theme` picks
|
||||
trails, `g` the map underneath, `f` true full screen, `[` and `]` its
|
||||
brightness, `+`/`-` the range, `q` quits. It opens maximised, as that one
|
||||
does. `--radius` sets how far it reaches to begin with and `--theme` picks
|
||||
from the same five.
|
||||
|
||||
**The window measures in whatever unit you are being shown.** `--units
|
||||
|
|
@ -2548,6 +2662,45 @@ aerial on one roof does not move because the receiver was pointed at a
|
|||
different band. It says which it used, because an inherited position is a
|
||||
convenience right up until you have moved and changed only one of them.
|
||||
|
||||
### Who each station is
|
||||
|
||||
An APRS callsign is issued by a government, so unlike a weather sensor it can
|
||||
be looked up. Each station heard is resolved once — the name on the licence,
|
||||
the town, and the licensed position, which is a street address where a beacon
|
||||
only gives a grid square — and the answer appears in the live table, in the
|
||||
information box on the map and in the report.
|
||||
|
||||
```
|
||||
station licensed to what away
|
||||
W1AW-9 ARRL HQ Operators Club — Newington, CT car 3140 km E
|
||||
KU0W Rod R Gowdy — Tucson, AZ digipeater 12 km NNE
|
||||
VK4BLE-7 Australia car 13800 km W
|
||||
```
|
||||
|
||||
Three things make it behave:
|
||||
|
||||
- **The SSID comes off first.** `W1AW-9` is the ninth radio W1AW runs — a car,
|
||||
a digipeater, a weather box — and a digipeated path marks the hop it came
|
||||
through with a star. No licence register has heard of either.
|
||||
- **Nothing waits.** The lookup runs on its own thread and the name appears in
|
||||
a later frame; a table that stopped for a network request would stop for
|
||||
every new station on a busy channel.
|
||||
- **A station the register cannot know still says where it is from.** The
|
||||
databases are United States registers, so `VK4BLE` comes back unlisted — and
|
||||
the country beside it comes out of the callsign's own structure, needing no
|
||||
network at all. A blank cell would read as a lookup that failed rather than
|
||||
as a question that was never going to be answered.
|
||||
|
||||
Objects are not looked up. An object is a marker one station placed on behalf
|
||||
of something with no licence of its own — a net, a hilltop, a storm — so
|
||||
asking who it is licensed to is asking the wrong question.
|
||||
|
||||
**Answers are cached** in `~/.cache/bandsaunter/callsigns.json` for a month,
|
||||
and that file is shared with every other part of this program that resolves a
|
||||
callsign: the scanner's identification, the recording browser and this. The
|
||||
same net logged night after night is asked about once. `--no-lookup` turns the
|
||||
network off entirely and leaves the country and district, which cost nothing.
|
||||
|
||||
### Afterwards
|
||||
|
||||
Three tables, because they answer different questions. **Stations heard** is
|
||||
|
|
@ -2696,6 +2849,37 @@ imports — marked as *heard*, not worked. Nothing here transmits, so nothing
|
|||
here is a contact, and an ADIF that let a logging program treat these as
|
||||
worked would put claims into somebody's log they cannot make.
|
||||
|
||||
### Who each station is
|
||||
|
||||
Every FT8 exchange is two callsigns, and a callsign is issued by a government,
|
||||
so it can be looked up. Both stations in an exchange are resolved — the one
|
||||
being answered may never transmit within earshot and is still a station this
|
||||
receiver knows about — and the name appears in the live table and the report.
|
||||
|
||||
```
|
||||
station licensed to grid away decodes best
|
||||
KU0W Rod R Gowdy — Tucson, AZ DM42 0 km 0° 1 -7
|
||||
VK4BLE Australia QG62 12125 km 249° 1 -7
|
||||
W1AW ARRL HQ Operators Club — Newington, CT FN31 3489 km 62° 1 -7
|
||||
```
|
||||
|
||||
The licensed callsign is found inside the heard one: `ET3RFG/R` is `ET3RFG`
|
||||
operating away from home, `DL/G4ABC` is `G4ABC` as a guest in Germany, and a
|
||||
hashed `<...>` — a compound callsign this receiver has not yet heard spelled
|
||||
out — is not asked about at all, because there is nothing to ask. Those rules
|
||||
are shared with APRS rather than written twice, since getting them wrong is
|
||||
silent: a register asked about `W1AW-9` returns nothing, which looks exactly
|
||||
like a station that is not licensed.
|
||||
|
||||
Nothing waits on the network. A slot has to be decoded in well under fifteen
|
||||
seconds or the next one is missed, so the lookup runs on its own thread and
|
||||
the name appears in a later slot.
|
||||
|
||||
**The databases are United States registers**, so the DX that makes this mode
|
||||
worth listening to comes back unlisted — and the country beside it comes out
|
||||
of the callsign's own structure, needing no network. On a band whose whole
|
||||
interest is distance, that is most of what a name would have added.
|
||||
|
||||
### How well it works
|
||||
|
||||
Checked against eleven off-air recordings with published decodes, which is
|
||||
|
|
@ -3201,6 +3385,67 @@ takes effect on the next scan; one already running read its settings when it
|
|||
started. Locking a frequency out does not delete what has already been
|
||||
recorded on it, so pressing `m` and then `d` is the usual thing to do.
|
||||
|
||||
### The register — everything ever looked up
|
||||
|
||||
`c` opens it. The scanner's identification, the Morse idents, APRS, FT8 and
|
||||
this browser all resolve callsigns into one file, and the aircraft side keeps
|
||||
its own. Between them they are a record of who and what has been heard from
|
||||
this aerial — and until now the only way to read either was to open the JSON.
|
||||
|
||||
```
|
||||
╭─ the register ───────────────────────────────────────────────────────────────╮
|
||||
│ callsigns — 3 of 62 shown, 3 with somewhere to point a map at 'tucson' │
|
||||
╰──────────────────────────────────────────────────────── tab → aircraft ──────╯
|
||||
callsign who where looked up map
|
||||
› AB7IC Thomas G Britton Tucson, AZ 26-09-23 05:32 ◉
|
||||
KC7UGN Roger F Wheaton Tucson, AZ 26-09-23 05:31 ◉
|
||||
KU0W Rod R Gowdy Tucson, AZ 26-09-23 22:59 ◉
|
||||
|
||||
╭─ AB7IC ──────────────────────────────────────────────────────────────────────╮
|
||||
│ licensed to Thomas G Britton district district 7 (Northwest) │
|
||||
│ class EXTRA grid DM42og │
|
||||
│ licence PERSON expires 12/21/2033 │
|
||||
│ street 8410 E Brookwood Dr position 32.27504, -110.81312 │
|
||||
│ town Tucson, AZ status found in a register │
|
||||
│ postcode 85750-2468 answered by callook.info │
|
||||
│ country United States looked up 2026-09-23 05:32 │
|
||||
╰────────────────────────────────── g opens this place in a browser ───────────╯
|
||||
↑↓ move tab switch / search g map c or esc back q quit
|
||||
```
|
||||
|
||||
| key | |
|
||||
|---|---|
|
||||
| `↑` `↓` | move; Page Up/Down a screen, Home/End to the ends |
|
||||
| `tab` | switch between callsigns and aircraft |
|
||||
| `/` | search **every field**, not just the name |
|
||||
| `g` | open where this one is, in a browser |
|
||||
| `r` | read the caches again, after a scan in another window |
|
||||
| `c` `esc` | back to the recordings |
|
||||
|
||||
**`g` opens a map.** Only the coordinates go into the link — a map does not
|
||||
need to be told whose licence it is looking at in order to show a place, and
|
||||
the link is the one part of this that leaves the machine. Where nothing is
|
||||
known about the position it says so rather than guessing, and on a machine
|
||||
with no browser, which is the normal case for a receiver, it prints the
|
||||
coordinates instead.
|
||||
|
||||
**Searching looks at everything**, because the interesting question is usually
|
||||
not *which callsign* but "who was in Arizona" or "what Bombardiers have gone
|
||||
over", and both of those live in the detail. Every word has to match, so a
|
||||
search can be narrowed.
|
||||
|
||||
Callsigns no register could place are **kept rather than dropped**. "Asked
|
||||
about, and in no register reachable from here" is a fact about a station, and a
|
||||
list that quietly dropped them would make an evening of unlisted foreign
|
||||
stations look like an evening when nothing was looked up. An aircraft is put on
|
||||
the map at the airport its flight started from, labelled as such: this is a
|
||||
register of airframes rather than a position report, and the origin is the
|
||||
nearest true thing.
|
||||
|
||||
The addresses are licence records, public by law and already printed in the
|
||||
scanner's own reports; this shows them the same way rather than more
|
||||
prominently.
|
||||
|
||||
### Detected callsigns
|
||||
|
||||
Under the transcript, every callsign heard in it is listed with the name and
|
||||
|
|
@ -3518,6 +3763,8 @@ restricted. Check your local rules.
|
|||
|
||||
## Licence
|
||||
|
||||
The source is at <https://frostwarning.com/git/dustcouncil/bandsaunter>.
|
||||
|
||||
Copyright © 2026 The Dust Council.
|
||||
|
||||
bandsaunter is free software: you can redistribute it and modify it under the
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ and transcribing speech.
|
|||
# Versions are the release date and a revision within that day, so
|
||||
# 2026-08-21_02 is the second build made on the 21st. The revision is padded
|
||||
# to two digits so versions sort as text.
|
||||
VERSION_DATE = "2026-09-21"
|
||||
VERSION_REVISION = 4
|
||||
VERSION_DATE = "2026-09-24"
|
||||
VERSION_REVISION = 1
|
||||
|
||||
__version__ = f"{VERSION_DATE}_{VERSION_REVISION:02d}"
|
||||
|
||||
|
|
|
|||
|
|
@ -34,9 +34,10 @@ from . import ax25, packets
|
|||
from .settings import Setting, format_value
|
||||
|
||||
__all__ = ["AprsOptions", "OPTIONS", "OPTION_GROUPS", "defaults", "in_group",
|
||||
"open_book", "who_text",
|
||||
"channel_text", "find_channel", "report_channels", "Found",
|
||||
"use_region", "receiver_at", "coordinates",
|
||||
"map_unit", "radius_in_nm",
|
||||
"map_unit", "radius_in_nm", "base_call", "licensee",
|
||||
"by_key", "format_option", "describe", "summarise", "Station",
|
||||
"Net", "Heard", "listen", "open_device", "open_log", "pump",
|
||||
"finish", "report", "watch", "windowed", "blip_for",
|
||||
|
|
@ -71,6 +72,7 @@ class AprsOptions:
|
|||
# -- what to show ---------------------------------------------------
|
||||
units: str = "metric"
|
||||
unparsed: bool = True
|
||||
lookup: bool = True # who each callsign is licensed to
|
||||
digipeated: bool = True # count frames that reached here relayed
|
||||
|
||||
# -- the map --------------------------------------------------------
|
||||
|
|
@ -214,6 +216,21 @@ OPTIONS: tuple[Setting, ...] = (
|
|||
flags=("--at",), example="47.55,-122.30", metavar="LAT,LON"),
|
||||
|
||||
# -- what to show ---------------------------------------------------
|
||||
O("lookup", "Look up callsigns", "Showing", "bool",
|
||||
"find out who each station is licensed to, and where",
|
||||
"An APRS callsign is issued by a government, so unlike a weather "
|
||||
"sensor it can be looked up: the name on the licence, the town, and "
|
||||
"the licensed position, which is a street address where a beacon "
|
||||
"only gives a grid square. Answers are kept in "
|
||||
"~/.cache/bandsaunter/callsigns.json and shared with every other "
|
||||
"part of this program that looks a callsign up, so the same net "
|
||||
"logged night after night is asked about once a month. The lookup "
|
||||
"never holds up the display -- it happens on its own thread and the "
|
||||
"name appears when it arrives. The databases are United States "
|
||||
"registers, so stations elsewhere come back unlisted; the country "
|
||||
"and district shown beside them come from the callsign's own "
|
||||
"structure and need no network at all.",
|
||||
flags=("--lookup",), off_flags=("--no-lookup",)),
|
||||
O("units", "Show readings in", "Showing", "choice",
|
||||
"metric or imperial, for the display and the export",
|
||||
"Only what is shown. APRS is imperial almost throughout -- knots, "
|
||||
|
|
@ -453,6 +470,88 @@ def radius_in_nm(options: AprsOptions) -> float:
|
|||
return max(1.0, float(options.radius)) / speed_unit(map_unit(options))[3]
|
||||
|
||||
|
||||
def base_call(call: str) -> str:
|
||||
"""The licensed callsign inside an APRS one.
|
||||
|
||||
The rules are shared with every other mode that hears callsigns -- an
|
||||
SSID here, a rover suffix on FT8, a guest prefix anywhere -- so they
|
||||
live in one place rather than being written out per band and getting
|
||||
quietly different.
|
||||
"""
|
||||
from .callsign import licensed_call
|
||||
|
||||
return licensed_call(call)
|
||||
|
||||
|
||||
def licensee(net: "Net", call: str):
|
||||
"""Who a callsign belongs to, as far as is known right now.
|
||||
|
||||
Never waits. The lookup runs on its own thread and the answer appears
|
||||
in a later frame of the display, which redraws twice a second anyway;
|
||||
a table that stopped for a network request would stop for every new
|
||||
station on a busy channel.
|
||||
"""
|
||||
if net is None or net.book is None:
|
||||
return None
|
||||
bare = base_call(call)
|
||||
return net.book.get(bare) if bare else None
|
||||
|
||||
|
||||
def _keep_lookups(console, net) -> None:
|
||||
"""Write the callsign answers to the disk before the run ends.
|
||||
|
||||
Without this the lookups happen and are then 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 there in memory while it lasts.
|
||||
|
||||
Outstanding lookups are given a moment to land first. A station heard
|
||||
in the last second of a run is still worth knowing tomorrow.
|
||||
"""
|
||||
book = getattr(net, "book", None)
|
||||
if book is None:
|
||||
return
|
||||
try:
|
||||
book.wait(3.0)
|
||||
book.save()
|
||||
except Exception:
|
||||
pass # a cache that cannot be written is not a failed run
|
||||
|
||||
|
||||
def who_text(who) -> str:
|
||||
"""One line about whose licence a callsign is, for a table cell.
|
||||
|
||||
The name and the town when the register knows them; otherwise the
|
||||
country and district the callsign itself implies, which is worth
|
||||
printing because it needs no network and is true everywhere -- a
|
||||
station in Australia will never be in a United States register, and
|
||||
leaving its cell blank would read as a lookup that failed rather than
|
||||
as a database that was never going to have it.
|
||||
"""
|
||||
if who is None:
|
||||
return ""
|
||||
if who.name:
|
||||
where = who.location or who.country
|
||||
return f"{who.name}" + (f" — {where}" if where else "")
|
||||
if who.status == "pending":
|
||||
return "…"
|
||||
bits = [b for b in (who.country, who.district) if b]
|
||||
return " ".join(bits[:1]) if bits else ""
|
||||
|
||||
|
||||
def open_book(options: AprsOptions):
|
||||
"""The callsign register, or nothing if lookups are turned off.
|
||||
|
||||
Offline rather than absent when they are off: an offline book still
|
||||
answers the country and the licensing district, which come out of the
|
||||
callsign's own structure and need no network, and which are most of
|
||||
what there is to say about a station outside the United States anyway.
|
||||
"""
|
||||
from .callsign import CallsignBook
|
||||
|
||||
return CallsignBook(online=bool(options.lookup))
|
||||
|
||||
|
||||
def receiver_at(options: AprsOptions) -> tuple[float, float] | None:
|
||||
"""Where the aerial is standing, from here or from the aircraft settings.
|
||||
|
||||
|
|
@ -598,11 +697,15 @@ class Net:
|
|||
conversation read in order is the thing somebody actually wants to see.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, book=None):
|
||||
self.stations: dict[str, Station] = {}
|
||||
self.messages: list = []
|
||||
self.packets = 0
|
||||
self.unparsed = 0
|
||||
# Where "who is this" is answered from. Shared with every other
|
||||
# part of this program that resolves a callsign, and with every
|
||||
# previous evening, because it is the one on the disk.
|
||||
self.book = book
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.stations)
|
||||
|
|
@ -614,6 +717,14 @@ class Net:
|
|||
station = self.stations[name] = Station(call=name)
|
||||
if packet.name:
|
||||
station.object_of = packet.source
|
||||
# Asked once, when the station is first heard, and never again:
|
||||
# the book remembers, on the disk, for a month. An object
|
||||
# placed by somebody is not itself licensed to anybody, so only
|
||||
# real stations are looked up.
|
||||
elif self.book is not None:
|
||||
bare = base_call(name)
|
||||
if bare:
|
||||
self.book.get(bare)
|
||||
station.add(packet)
|
||||
self.packets += 1
|
||||
if packet.kind == "unparsed":
|
||||
|
|
@ -1026,7 +1137,7 @@ def listen(console, options: AprsOptions, output_dir: str,
|
|||
|
||||
started = time.time()
|
||||
log = open_log(console, options, output_dir, started, log_path)
|
||||
net = Net()
|
||||
net = Net(book=open_book(options))
|
||||
heard.net = net
|
||||
_say_where(console, options, receiver_at(options))
|
||||
console.print(f"[grey62]listening on {options.frequency / 1e6:g} MHz at "
|
||||
|
|
@ -1107,6 +1218,11 @@ def finish(console, options: AprsOptions, output_dir: str,
|
|||
heard: Heard) -> Heard:
|
||||
"""Say what was heard, and leave the files behind."""
|
||||
net = heard.net
|
||||
# Before the early return: a run that heard one station and no more
|
||||
# still learned who that station was, and throwing the answer away
|
||||
# because the evening was quiet would mean asking again tomorrow. The
|
||||
# book writes only if it has something new.
|
||||
_keep_lookups(console, net)
|
||||
if net is None or not len(net):
|
||||
console.print("[yellow]nothing heard. APRS is a two-second "
|
||||
"transmission every few minutes, so give it a while "
|
||||
|
|
@ -1178,6 +1294,9 @@ def report(console, net: Net, options: AprsOptions) -> None:
|
|||
t = Table(box=None, header_style="bold", pad_edge=False,
|
||||
title="[bold]stations heard[/bold]", title_justify="left")
|
||||
t.add_column("station", overflow="fold")
|
||||
named = options.lookup and net.book is not None
|
||||
if named:
|
||||
t.add_column("licensed to", style="grey62", overflow="fold")
|
||||
t.add_column("what", style="grey62", overflow="fold")
|
||||
t.add_column("position", style="grey62", no_wrap=True)
|
||||
if home is not None:
|
||||
|
|
@ -1187,8 +1306,11 @@ def report(console, net: Net, options: AprsOptions) -> None:
|
|||
t.add_column("signal", justify="right")
|
||||
t.add_column("last heard", style="grey62", no_wrap=True)
|
||||
for station in stations:
|
||||
row = [station.call + (" (object)" if station.object_of else ""),
|
||||
station.symbol or station.kind,
|
||||
row = [station.call + (" (object)" if station.object_of else "")]
|
||||
if named:
|
||||
row.append(who_text(licensee(net, station.call))
|
||||
if not station.object_of else "")
|
||||
row += [station.symbol or station.kind,
|
||||
station.position.describe() if station.position else ""]
|
||||
if home is not None:
|
||||
away = station.away(home)
|
||||
|
|
@ -1407,7 +1529,8 @@ def station_shade(station: Station) -> str:
|
|||
return "fixed"
|
||||
|
||||
|
||||
def blip_for(station: Station, home=None, imperial: bool = False):
|
||||
def blip_for(station: Station, home=None, imperial: bool = False,
|
||||
who=None):
|
||||
"""One station as the window wants it: a place, a shape and a box."""
|
||||
from .flightmap import RAMP, RAMP_STEPS
|
||||
from .livemap import Blip
|
||||
|
|
@ -1430,21 +1553,31 @@ def blip_for(station: Station, home=None, imperial: bool = False):
|
|||
first_seen=station.first, last_seen=station.last,
|
||||
shape="vehicle" if station.moving else "station",
|
||||
colour_index=RAMP + int(round(shade * (RAMP_STEPS - 1))),
|
||||
details=tuple(station_lines(station, home, imperial)))
|
||||
details=tuple(station_lines(station, home, imperial, who)))
|
||||
|
||||
|
||||
def station_lines(station: Station, home=None,
|
||||
imperial: bool = False) -> list[tuple[str, str, str]]:
|
||||
imperial: bool = False,
|
||||
who=None) -> list[tuple[str, str, str]]:
|
||||
"""What the information box says about one station.
|
||||
|
||||
The same shape the aircraft boxes use -- a label, a value and a country
|
||||
flag that is always empty here, because a callsign already says which
|
||||
country and saying it twice would cost a line that the weather wants.
|
||||
|
||||
``who`` is the licence record, where one has arrived. It goes at the
|
||||
top, because a name is what somebody reads a callsign to find out.
|
||||
"""
|
||||
from .acurite import Measure, compass, format_measure
|
||||
from .packets import height_text
|
||||
|
||||
out: list[tuple[str, str, str]] = []
|
||||
if who is not None:
|
||||
if who.name:
|
||||
out.append(("licensed to", who.name, ""))
|
||||
where = who.location or who.country
|
||||
if where:
|
||||
out.append(("at", where, ""))
|
||||
if station.object_of:
|
||||
out.append(("placed by", station.object_of, ""))
|
||||
if station.symbol:
|
||||
|
|
@ -1513,7 +1646,7 @@ def watch(console, options: AprsOptions, output_dir: str,
|
|||
|
||||
started = time.time()
|
||||
log = open_log(console, options, output_dir, started, log_path)
|
||||
net = Net()
|
||||
net = Net(book=open_book(options))
|
||||
heard.net = net
|
||||
home = receiver_at(options)
|
||||
# Set before the window is built, because the window reads its colours
|
||||
|
|
@ -1539,7 +1672,8 @@ def watch(console, options: AprsOptions, output_dir: str,
|
|||
sky.note = "simulated"
|
||||
|
||||
def on_block(total: int) -> None:
|
||||
sky.update([blip_for(station, home, options.imperial)
|
||||
sky.update([blip_for(station, home, options.imperial,
|
||||
licensee(net, station.call))
|
||||
for station in net.all() if station.position is not None],
|
||||
total, len(net))
|
||||
|
||||
|
|
|
|||
|
|
@ -39,7 +39,9 @@ from . import __version__
|
|||
__all__ = ["decode_png", "tile_of", "choose_zoom", "fetch_tile", "mosaic",
|
||||
"ground_under", "TILE_URL", "ATTRIBUTION", "MAX_TILES", "MAX_ZOOM",
|
||||
"cache_dir", "PNGError", "airports_in", "AIRPORTS_URL",
|
||||
"tile_span"]
|
||||
"tile_span", "on_disk", "ground_cache_dir", "cache_size",
|
||||
"prune_cache", "forget_ground", "GROUND_CACHE_VERSION",
|
||||
"GROUND_CACHE_DAYS", "CACHE_LIMIT_MB"]
|
||||
|
||||
# The standard OpenStreetMap tiles. Any {z}/{x}/{y} server can be put here
|
||||
# instead; nothing below knows anything about this one in particular.
|
||||
|
|
@ -64,8 +66,13 @@ OVERSAMPLE = 1.4
|
|||
MIN_ZOOM = 2
|
||||
TILE_PIXELS = 256
|
||||
|
||||
# What the tile server is told it is talking to. This is not decoration: the
|
||||
# usage policy of the service the default tiles come from asks for a User-Agent
|
||||
# that identifies the application and gives somewhere to look it up, so that an
|
||||
# operator with a question about the traffic has somebody to ask. It pointed
|
||||
# at a topic listing until the project had an address of its own.
|
||||
USER_AGENT = (f"bandsaunter/{__version__} "
|
||||
"(+https://github.com/topics/rtl-sdr; aircraft map drawing)")
|
||||
f"(+https://frostwarning.com/git/dustcouncil/bandsaunter; offline-cached map tiles for a signal scanner)")
|
||||
|
||||
# Politeness between requests to a volunteer-funded service. Only paid on a
|
||||
# tile that was not already on the disk.
|
||||
|
|
@ -98,6 +105,20 @@ AIRPORT_CACHE_VERSION = 2
|
|||
# list of airstrips.
|
||||
MOST_AIRPORTS = 40
|
||||
|
||||
# The finished map, kept as well as the tiles it was built from. The tiles
|
||||
# are cached already and always have been, so a second evening on the same
|
||||
# view costs nothing on the network -- but it still costs decoding forty
|
||||
# PNGs and resampling a megapixel and a half into the picture's own
|
||||
# projection, every time the window opens, for an answer that cannot have
|
||||
# changed. A coastline does not move.
|
||||
GROUND_CACHE_VERSION = 1
|
||||
GROUND_CACHE_DAYS = 30
|
||||
|
||||
# What the whole cache is allowed to grow to. Tiles are small and a map is
|
||||
# not, so a cache that only ever grew would quietly become the largest thing
|
||||
# this program had ever written.
|
||||
CACHE_LIMIT_MB = 400
|
||||
|
||||
|
||||
class PNGError(ValueError):
|
||||
"""A PNG this decoder cannot read."""
|
||||
|
|
@ -432,6 +453,150 @@ def _resample(values: np.ndarray, edges: np.ndarray, axis: int) -> np.ndarray:
|
|||
return (total / counts.reshape(shape)).astype(np.float32)
|
||||
|
||||
|
||||
def ground_cache_dir() -> Path:
|
||||
root = os.environ.get("XDG_CACHE_HOME") or "~/.cache"
|
||||
return Path(root).expanduser() / "bandsaunter" / "ground"
|
||||
|
||||
|
||||
def _ground_key(south, west, north, east, width, height, shades,
|
||||
zoom) -> str:
|
||||
"""What makes two requests for the ground the same request.
|
||||
|
||||
The box is rounded to three places -- about a hundred metres, which is
|
||||
finer than a tile and far finer than anything visible -- so that a view
|
||||
which has drifted by a pixel is answered from the cache rather than
|
||||
rebuilt. The size is in, because the same box rendered into a bigger
|
||||
window is a different picture and reusing it would be the blur this
|
||||
program went to some trouble to avoid.
|
||||
"""
|
||||
parts = (f"{round(south, 3):+09.3f}", f"{round(west, 3):+09.3f}",
|
||||
f"{round(north, 3):+09.3f}", f"{round(east, 3):+09.3f}",
|
||||
f"{int(width)}x{int(height)}", f"s{int(shades)}",
|
||||
f"z{'auto' if zoom is None else int(zoom)}")
|
||||
return "_".join(parts)
|
||||
|
||||
|
||||
def _read_ground(path: Path):
|
||||
"""A finished map off the disk, or None if there is not a usable one."""
|
||||
try:
|
||||
with np.load(path) as body:
|
||||
if int(body["version"]) != GROUND_CACHE_VERSION:
|
||||
return None
|
||||
if time.time() - float(body["at"]) > GROUND_CACHE_DAYS * 86_400:
|
||||
return None
|
||||
return body["levels"]
|
||||
except Exception:
|
||||
# Deliberately everything. A truncated or half-written file is what
|
||||
# a cache looks like after a power cut, and numpy reports that
|
||||
# through whichever of half a dozen exceptions the zip reader
|
||||
# happened to raise. None of them is an error here: they are all a
|
||||
# cache miss, and the answer to a cache miss is to build the map.
|
||||
return None
|
||||
|
||||
|
||||
def _write_ground(path: Path, levels: np.ndarray) -> None:
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".tmp.npz")
|
||||
np.savez_compressed(tmp, levels=levels, at=time.time(),
|
||||
version=GROUND_CACHE_VERSION)
|
||||
tmp.replace(path)
|
||||
except (OSError, ValueError):
|
||||
return # an unwritable cache is not a reason to stop
|
||||
# And keep the whole thing inside its limit. Done here because this is
|
||||
# the only place that makes the cache bigger by a megabyte at a time --
|
||||
# a tile is small and a map is not -- and because a cache nothing ever
|
||||
# prunes is a disk filling up slowly enough that nobody notices.
|
||||
try:
|
||||
prune_cache()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def forget_ground() -> int:
|
||||
"""Throw away every finished map. The tiles under them are kept."""
|
||||
gone = 0
|
||||
try:
|
||||
for path in ground_cache_dir().glob("*.npz"):
|
||||
try:
|
||||
path.unlink()
|
||||
gone += 1
|
||||
except OSError:
|
||||
pass
|
||||
except OSError:
|
||||
pass
|
||||
return gone
|
||||
|
||||
|
||||
def cache_size() -> dict:
|
||||
"""How much of the disk each cache is using, and how many files.
|
||||
|
||||
Worth being able to answer, because everything here grows and nothing
|
||||
here ever shrank until now.
|
||||
"""
|
||||
root = Path(os.environ.get("XDG_CACHE_HOME") or "~/.cache")
|
||||
root = root.expanduser() / "bandsaunter"
|
||||
out = {}
|
||||
for name, pattern in (("tiles", "tiles/**/*.png"),
|
||||
("ground", "ground/*.npz"),
|
||||
("airports", "airports/*.json")):
|
||||
total = count = 0
|
||||
try:
|
||||
for path in root.glob(pattern):
|
||||
try:
|
||||
total += path.stat().st_size
|
||||
count += 1
|
||||
except OSError:
|
||||
pass
|
||||
except OSError:
|
||||
pass
|
||||
out[name] = {"bytes": total, "files": count}
|
||||
out["total"] = {"bytes": sum(v["bytes"] for v in out.values()),
|
||||
"files": sum(v["files"] for v in out.values())}
|
||||
return out
|
||||
|
||||
|
||||
def prune_cache(limit_mb: float = CACHE_LIMIT_MB) -> int:
|
||||
"""Delete the least recently used files until the cache fits.
|
||||
|
||||
Least recently *used* rather than oldest: a tile fetched a year ago and
|
||||
looked at last night is the receiver's own neighbourhood, and throwing
|
||||
that away to keep last week's holiday is the wrong way round. Reading
|
||||
a file updates its access time on any filesystem not mounted noatime,
|
||||
and where it does not this falls back to when it was written, which is
|
||||
the same thing for a cache that is only ever written once.
|
||||
"""
|
||||
root = Path(os.environ.get("XDG_CACHE_HOME") or "~/.cache")
|
||||
root = root.expanduser() / "bandsaunter"
|
||||
files = []
|
||||
for pattern in ("tiles/**/*.png", "ground/*.npz", "airports/*.json"):
|
||||
try:
|
||||
for path in root.glob(pattern):
|
||||
try:
|
||||
stat = path.stat()
|
||||
files.append((max(stat.st_atime, stat.st_mtime),
|
||||
stat.st_size, path))
|
||||
except OSError:
|
||||
pass
|
||||
except OSError:
|
||||
pass
|
||||
total = sum(size for _when, size, _p in files)
|
||||
limit = limit_mb * 1024 * 1024
|
||||
if total <= limit:
|
||||
return 0
|
||||
gone = 0
|
||||
for _when, size, path in sorted(files):
|
||||
if total <= limit:
|
||||
break
|
||||
try:
|
||||
path.unlink()
|
||||
total -= size
|
||||
gone += 1
|
||||
except OSError:
|
||||
pass
|
||||
return gone
|
||||
|
||||
|
||||
def _airport_cache(box) -> Path:
|
||||
root = os.environ.get("XDG_CACHE_HOME") or "~/.cache"
|
||||
name = "_".join(f"{round(v, 1):+06.1f}" for v in box)
|
||||
|
|
@ -543,7 +708,7 @@ def _ask_overpass(box, url: str, timeout: float) -> dict:
|
|||
def ground_under(south: float, west: float, north: float, east: float,
|
||||
width: int, height: int, shades: int = 32,
|
||||
fetch=fetch_tile, zoom: int | None = None,
|
||||
**kw) -> np.ndarray | None:
|
||||
remember: bool = True, **kw):
|
||||
"""The map for one picture, as ``shades`` levels of brightness.
|
||||
|
||||
The tiles are Web Mercator and the picture is not, so every output pixel
|
||||
|
|
@ -554,6 +719,12 @@ def ground_under(south: float, west: float, north: float, east: float,
|
|||
point of putting a coastline under it is that the coastline is where the
|
||||
aircraft was.
|
||||
|
||||
A whole map is kept on the disk beside the tiles it was built from, so
|
||||
that opening the same window tomorrow costs a file read rather than
|
||||
forty PNG decodes and a resample into this program's own projection.
|
||||
``remember=False`` turns that off, which is what the tests want when
|
||||
they are measuring the building rather than the remembering.
|
||||
|
||||
Returns the levels and whether that is the whole answer. Nothing at all
|
||||
is None, which the caller draws as the plain grid it drew before; a map
|
||||
with squares missing from it is returned all the same, because most of a
|
||||
|
|
@ -562,6 +733,16 @@ def ground_under(south: float, west: float, north: float, east: float,
|
|||
"""
|
||||
if width < 1 or height < 1 or north <= south or east <= west:
|
||||
return None, True
|
||||
|
||||
# The finished map, if this exact picture has been built before. Only
|
||||
# a whole one is ever written, so anything found here is settled.
|
||||
key = _ground_key(south, west, north, east, width, height, shades, zoom)
|
||||
kept = ground_cache_dir() / f"{key}.npz" if remember else None
|
||||
if kept is not None:
|
||||
have = _read_ground(kept)
|
||||
if have is not None and have.shape == (height, width):
|
||||
return have, True
|
||||
|
||||
if zoom is None:
|
||||
zoom = choose_zoom(south, west, north, east, width=width)
|
||||
tiles, origin_x, origin_y, covered = mosaic(south, west, north, east,
|
||||
|
|
@ -621,5 +802,12 @@ def ground_under(south: float, west: float, north: float, east: float,
|
|||
# And the hole itself is drawn as bare ground rather than as the
|
||||
# brightest thing on the picture, which is what inverting black gives.
|
||||
levels = np.where(here, levels, 0.0)
|
||||
return (np.clip((levels * (shades - 1)).round(), 0,
|
||||
shades - 1).astype(np.uint8), bool(covered.all()))
|
||||
out = np.clip((levels * (shades - 1)).round(), 0,
|
||||
shades - 1).astype(np.uint8)
|
||||
settled = bool(covered.all())
|
||||
# Only a whole map is kept. Writing one with squares missing would
|
||||
# cache the hole for a month, and the whole point of treating a partial
|
||||
# map as provisional is that it gets asked for again.
|
||||
if kept is not None and settled:
|
||||
_write_ground(kept, out)
|
||||
return out, settled
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ from rich.table import Table
|
|||
from rich.text import Text
|
||||
|
||||
from . import version_notice
|
||||
from . import __version__
|
||||
from .bandplan import band_names, fmt_hz, shorten_band
|
||||
from .callsign import CallsignBook, HEADING, find_callsigns
|
||||
from .config import DEFAULT_CONFIG_DIR, load_default, remember_lockouts
|
||||
|
|
@ -666,6 +667,13 @@ STAMP = "%y-%m-%d %I:%M:%S %p"
|
|||
STAMP_WIDTH = 20
|
||||
|
||||
|
||||
def _reg_when(value: float) -> str:
|
||||
"""When something was looked up, or nothing if it never was."""
|
||||
if not value:
|
||||
return ""
|
||||
return datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
|
||||
def _stamp(when: datetime | None) -> str:
|
||||
"""One capture's date and time, or an empty string when it has neither."""
|
||||
if when is None:
|
||||
|
|
@ -738,6 +746,17 @@ class Browser:
|
|||
self.show_help = False
|
||||
self.reading = False # full-screen transcript
|
||||
self.read_top = 0
|
||||
# The register: everything ever looked up, on its own screen. Read
|
||||
# the first time it is opened rather than at startup, because a
|
||||
# browser pointed at a directory of recordings should not wait on
|
||||
# two caches somebody may never ask to see.
|
||||
self.showing_register = False
|
||||
self.register: dict | None = None
|
||||
self.reg_kind = "callsigns"
|
||||
self.reg_index = 0
|
||||
self.reg_top = 0
|
||||
self.reg_query = ""
|
||||
self.reg_searching = False
|
||||
self._undo: list[tuple[Path, Path]] = [] # the last move, to reverse
|
||||
self._undo_path: Path | None = None # where its .wav came from
|
||||
self._undo_label = ""
|
||||
|
|
@ -1393,10 +1412,10 @@ class Browser:
|
|||
("space", "stop"), ("/", "search"), ("t", "read"),
|
||||
("S I N", "file"), ("d", "delete"), ("m", "mask"),
|
||||
("s", f"sort by {self.sort}"), ("r", "reload"),
|
||||
("?", "keys"), ("q", "quit")]
|
||||
("c", "register"), ("?", "keys"), ("q", "quit")]
|
||||
# Everything given up here is still on the page ? opens, which is why
|
||||
# ? is among the last to go.
|
||||
expendable = ["r", "s", "space", "m", "d", "S I N", "t", "/",
|
||||
expendable = ["r", "s", "space", "m", "d", "S I N", "c", "t", "/",
|
||||
"⏎", "↑↓", "?"]
|
||||
width = self.console.size.width or 80
|
||||
shown = items
|
||||
|
|
@ -1458,8 +1477,10 @@ class Browser:
|
|||
names += f" or {FILING[-1][1]}/"
|
||||
for key, what in (
|
||||
("↑ ↓ / k j", "move through the recordings"),
|
||||
("PgUp PgDn", "a screenful at a time"),
|
||||
("Home End", "first and last"),
|
||||
# Merged, because the page is exactly as tall as an
|
||||
# eighty-by-twenty-four terminal and the register needed a
|
||||
# row. These two were always the same thought.
|
||||
("PgUp PgDn", "a screenful at a time; Home End for the ends"),
|
||||
("Enter", "play the highlighted recording"),
|
||||
("space", "stop playing"),
|
||||
("t", "read the whole transcript, full screen"),
|
||||
|
|
@ -1475,6 +1496,12 @@ class Browser:
|
|||
("m", "lock this frequency out of every later scan"),
|
||||
("", ""),
|
||||
("callsigns", "found in transcripts and looked up for you"),
|
||||
# One line, not five. Eighty by twenty-four is still what a
|
||||
# new terminal is, and a list of keys that has to be
|
||||
# scrolled to reach "q" has failed at its one job -- so the
|
||||
# register's own keys are named on the register's own screen
|
||||
# rather than here.
|
||||
("c", "every callsign and aircraft ever looked up"),
|
||||
("? h", "this list"),
|
||||
("q", "quit")):
|
||||
t.add_row(key, what)
|
||||
|
|
@ -1544,6 +1571,8 @@ class Browser:
|
|||
return Layout(Align.center(self._help(), vertical="middle"))
|
||||
if self.reading:
|
||||
return Layout(self._reader())
|
||||
if self.showing_register:
|
||||
return self._register()
|
||||
layout = Layout()
|
||||
# One height, computed once: the panel and the region it sits in have
|
||||
# to agree, or the difference shows up as a gap in the middle of the
|
||||
|
|
@ -1573,6 +1602,8 @@ class Browser:
|
|||
return True
|
||||
if self.reading:
|
||||
return self._handle_reader(key)
|
||||
if self.showing_register:
|
||||
return self._handle_register(key)
|
||||
|
||||
rows = self._rows()
|
||||
if key in ("q", "escape") and not self.query:
|
||||
|
|
@ -1613,6 +1644,8 @@ class Browser:
|
|||
self.query = ""
|
||||
elif key in ("?", "h"):
|
||||
self.show_help = not self.show_help
|
||||
elif key == "c":
|
||||
self._open_register()
|
||||
elif key == "t":
|
||||
cap = self.current
|
||||
# Either kind of content: the decoded panel says "press t to read
|
||||
|
|
@ -1663,6 +1696,240 @@ class Browser:
|
|||
self._delete()
|
||||
return True
|
||||
|
||||
# -- the register -----------------------------------------------------
|
||||
def _open_register(self) -> None:
|
||||
from . import register as reg
|
||||
|
||||
if self.register is None:
|
||||
self.register = reg.load_all()
|
||||
self.showing_register = True
|
||||
self.reg_index = self.reg_top = 0
|
||||
counts = ", ".join(f"{len(v)} {k}"
|
||||
for k, v in self.register.items())
|
||||
self.message = counts or "nothing looked up yet"
|
||||
|
||||
# The detail panel's share of the screen: two borders and eight rows of
|
||||
# label-and-value in two columns, which holds the sixteen fields a
|
||||
# licence has. Fixed rather than fitted, so the list above it does not
|
||||
# jump about as the cursor moves between a full record and a bare one.
|
||||
_REG_DETAIL = 11
|
||||
|
||||
def _reg_rows(self) -> int:
|
||||
"""How many list rows the screen has room for beside the detail."""
|
||||
height = self.console.size.height or 24
|
||||
# 3 for the heading panel, the detail panel, 1 for the footer, and
|
||||
# 1 for the table's own column headings.
|
||||
return max(3, height - 3 - self._REG_DETAIL - 1 - 1)
|
||||
|
||||
def _reg_all(self) -> list:
|
||||
from . import register as reg
|
||||
|
||||
if self.register is None:
|
||||
return []
|
||||
return reg.search(self.register.get(self.reg_kind) or [],
|
||||
self.reg_query)
|
||||
|
||||
@property
|
||||
def reg_current(self):
|
||||
found = self._reg_all()
|
||||
if not found:
|
||||
return None
|
||||
return found[min(self.reg_index, len(found) - 1)]
|
||||
|
||||
def _register(self) -> Group:
|
||||
"""The register: a list, and everything known about the current one."""
|
||||
from . import register as reg
|
||||
|
||||
found = self._reg_all()
|
||||
rows = self._reg_rows()
|
||||
if found:
|
||||
self.reg_index = max(0, min(self.reg_index, len(found) - 1))
|
||||
self.reg_top = max(0, min(self.reg_top, max(0, len(found) - rows)))
|
||||
if self.reg_index < self.reg_top:
|
||||
self.reg_top = self.reg_index
|
||||
elif self.reg_index >= self.reg_top + rows:
|
||||
self.reg_top = self.reg_index - rows + 1
|
||||
|
||||
other = "aircraft" if self.reg_kind == "callsigns" else "callsigns"
|
||||
held = len(self.register.get(self.reg_kind) or []) if self.register \
|
||||
else 0
|
||||
mappable = sum(1 for e in found if e.mappable)
|
||||
head = Text.from_markup(
|
||||
f"[bold]{self.reg_kind}[/bold] — "
|
||||
f"[cyan]{len(found)}[/cyan] of {held} shown, "
|
||||
f"{mappable} with somewhere to point a map at"
|
||||
+ (f" [yellow]matching {escape(self.reg_query)!r}[/yellow]"
|
||||
if self.reg_query else ""))
|
||||
|
||||
table = Table(box=None, header_style="bold", pad_edge=False,
|
||||
expand=True)
|
||||
table.add_column(" ", width=1, style="cyan")
|
||||
table.add_column("callsign" if self.reg_kind == "callsigns"
|
||||
else "aircraft", width=12, no_wrap=True)
|
||||
table.add_column("who" if self.reg_kind == "callsigns" else "what",
|
||||
ratio=3, no_wrap=True, style="white")
|
||||
table.add_column("where", ratio=2, no_wrap=True, style="grey62")
|
||||
table.add_column("looked up", width=16, no_wrap=True,
|
||||
style="bright_black")
|
||||
table.add_column("map", width=3, justify="center")
|
||||
for i in range(self.reg_top, min(len(found), self.reg_top + rows)):
|
||||
entry = found[i]
|
||||
here = i == self.reg_index
|
||||
table.add_row(
|
||||
"›" if here else "",
|
||||
Text(entry.title, style="bold reverse" if here else "bold"),
|
||||
entry.what or Text("—", style="grey37"),
|
||||
entry.where or "",
|
||||
_reg_when(entry.when),
|
||||
Text("◉", style="green") if entry.mappable
|
||||
else Text("·", style="grey37"))
|
||||
if not found:
|
||||
table.add_row("", "", Text("nothing here", style="yellow"),
|
||||
"", "", "")
|
||||
|
||||
# A split rather than a group, so the list takes whatever is left
|
||||
# and the footer stays on the bottom line. Grouped, a short list
|
||||
# left the footer floating in the middle of the screen with the
|
||||
# tail of the previous frame under it.
|
||||
layout = Layout()
|
||||
layout.split_column(
|
||||
Layout(Panel(head, border_style="cyan", padding=(0, 1),
|
||||
title="[bold]the register[/bold]",
|
||||
title_align="left",
|
||||
subtitle=f"[bright_black]tab → {other}"
|
||||
f"[/bright_black]",
|
||||
subtitle_align="right"), size=3),
|
||||
Layout(table, ratio=1),
|
||||
Layout(self._reg_detail(self.reg_current),
|
||||
size=self._REG_DETAIL),
|
||||
Layout(Text.from_markup(self._reg_footer()), size=1),
|
||||
)
|
||||
return layout
|
||||
|
||||
def _reg_detail(self, entry) -> Panel:
|
||||
"""Everything known about one entry, in two columns of label and
|
||||
value.
|
||||
|
||||
Two columns rather than one long list because a licence has a dozen
|
||||
fields and a screen is wider than it is tall, and because the thing
|
||||
somebody is looking for is usually further down than the fold.
|
||||
"""
|
||||
if entry is None:
|
||||
return Panel(Text("select something to see what is known "
|
||||
"about it", style="grey62"),
|
||||
border_style="grey37", padding=(0, 1))
|
||||
grid = Table.grid(padding=(0, 2), expand=True)
|
||||
grid.add_column(justify="right", style="grey62", width=16)
|
||||
grid.add_column(ratio=1, overflow="fold")
|
||||
grid.add_column(justify="right", style="grey62", width=16)
|
||||
grid.add_column(ratio=1, overflow="fold")
|
||||
pairs = list(entry.rows)
|
||||
half = (len(pairs) + 1) // 2
|
||||
left, right = pairs[:half], pairs[half:]
|
||||
for i in range(half):
|
||||
a_label, a_value = left[i]
|
||||
b_label, b_value = right[i] if i < len(right) else ("", "")
|
||||
grid.add_row(a_label, Text(a_value), b_label, Text(b_value))
|
||||
where = (f"[green]g[/green] opens this place in a browser"
|
||||
if entry.mappable
|
||||
else "[grey37]no position, so nowhere to open[/grey37]")
|
||||
return Panel(grid, border_style="cyan", padding=(0, 1),
|
||||
title=f"[bold]{escape(entry.title)}[/bold]",
|
||||
title_align="left", subtitle=where,
|
||||
subtitle_align="right")
|
||||
|
||||
def _reg_footer(self) -> str:
|
||||
if self.reg_searching:
|
||||
return (f"[cyan]search[/cyan] {escape(self.reg_query)}[reverse] "
|
||||
f"[/reverse] [bright_black]⏎ done esc clear"
|
||||
f"[/bright_black]")
|
||||
if self.message:
|
||||
return f"[green]{escape(self.message)}[/green]"
|
||||
return ("[bright_black]↑↓ move tab switch / search "
|
||||
"g map c or esc back q quit[/bright_black]")
|
||||
|
||||
def _handle_register(self, key: str) -> bool:
|
||||
if self.reg_searching:
|
||||
return self._handle_reg_search(key)
|
||||
rows = self._reg_rows()
|
||||
if key in ("c", "escape"):
|
||||
self.showing_register = False
|
||||
self.reg_query = ""
|
||||
elif key == "q":
|
||||
return False
|
||||
elif key in ("up", "k"):
|
||||
self.reg_index -= 1
|
||||
elif key in ("down", "j"):
|
||||
self.reg_index += 1
|
||||
elif key in ("pgup", "left"):
|
||||
self.reg_index -= rows
|
||||
elif key in ("pgdn", "right"):
|
||||
self.reg_index += rows
|
||||
elif key == "home":
|
||||
self.reg_index = 0
|
||||
elif key == "end":
|
||||
self.reg_index = 1 << 20 # clamped when the panel is drawn
|
||||
elif key == "tab":
|
||||
self.reg_kind = ("aircraft" if self.reg_kind == "callsigns"
|
||||
else "callsigns")
|
||||
self.reg_index = self.reg_top = 0
|
||||
elif key == "/":
|
||||
self.reg_searching = True
|
||||
self.reg_query = ""
|
||||
elif key == "g":
|
||||
self._open_map()
|
||||
elif key == "r":
|
||||
from . import register as reg
|
||||
|
||||
self.register = reg.load_all()
|
||||
self.message = "read the caches again"
|
||||
self.reg_index = max(0, self.reg_index)
|
||||
return True
|
||||
|
||||
def _handle_reg_search(self, key: str) -> bool:
|
||||
if key == "enter":
|
||||
self.reg_searching = False
|
||||
elif key == "escape":
|
||||
self.reg_searching = False
|
||||
self.reg_query = ""
|
||||
elif key == "backspace":
|
||||
self.reg_query = self.reg_query[:-1]
|
||||
elif len(key) == 1 and key.isprintable():
|
||||
self.reg_query += key
|
||||
self.reg_index = self.reg_top = 0
|
||||
return True
|
||||
|
||||
def _open_map(self) -> None:
|
||||
"""Show where this is, in whatever browser the desktop uses.
|
||||
|
||||
Only the coordinates go into the URL. A map does not need to be
|
||||
told whose licence it is looking at, and the one part of this that
|
||||
leaves the machine should carry as little as it can.
|
||||
"""
|
||||
entry = self.reg_current
|
||||
if entry is None:
|
||||
return
|
||||
url = entry.maps()
|
||||
if not url:
|
||||
self.message = "nothing is known about where this one is"
|
||||
return
|
||||
import contextlib
|
||||
import io
|
||||
import webbrowser
|
||||
|
||||
try:
|
||||
# Quietly: some browsers write to the terminal on startup, and
|
||||
# this one is running a full-screen display that would be left
|
||||
# with somebody else's text through the middle of it.
|
||||
with contextlib.redirect_stdout(io.StringIO()), \
|
||||
contextlib.redirect_stderr(io.StringIO()):
|
||||
opened = webbrowser.open(url)
|
||||
except Exception as exc:
|
||||
self.message = f"could not open a browser: {exc}"
|
||||
return
|
||||
self.message = (f"opened {entry.title} in a browser" if opened
|
||||
else f"no browser to open — the place is {url}")
|
||||
|
||||
def _handle_reader(self, key: str) -> bool:
|
||||
rows = max(3, (self.console.size.height or 24) - 6)
|
||||
if key in ("t", "escape", "q", "space"):
|
||||
|
|
@ -1774,6 +2041,8 @@ def build_parser() -> argparse.ArgumentParser:
|
|||
default=SORTS[0], metavar="ORDER",
|
||||
help="initial order: %s (default: %s, newest first)"
|
||||
% (", ".join(SORTS), SORTS[0]))
|
||||
p.add_argument("--no-splash", action="store_true",
|
||||
help="do not draw the title screen")
|
||||
p.add_argument("--filter", default="", metavar="TEXT",
|
||||
help="start with only recordings matching this")
|
||||
p.add_argument("--player", default=None, metavar="CMD",
|
||||
|
|
@ -1870,6 +2139,18 @@ def _write_kml(console: Console, browser: "Browser", book: CallsignBook,
|
|||
def main(argv: list[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
console = Console()
|
||||
|
||||
# Paused for a moment, because what follows takes the whole screen: the
|
||||
# browser runs on the alternate screen, so without a beat here the
|
||||
# banner is replaced in the same tenth of a second it was drawn in. It
|
||||
# is still on the normal screen afterwards, and comes back on quitting.
|
||||
from . import splash
|
||||
|
||||
splash.show(console, splash.BROWSER_NAME,
|
||||
("Conceived by: The Dust Council",
|
||||
"100% AI Coded by Claude Code.",
|
||||
f"{__version__} · read back what a scan left behind"),
|
||||
no_splash=getattr(args, "no_splash", False), pause=0.9)
|
||||
directory = (Path(args.directory).expanduser() if args.directory
|
||||
else default_directory())
|
||||
if not directory.is_dir():
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ from pathlib import Path
|
|||
|
||||
__all__ = ["Callsign", "CallsignBook", "find_callsigns", "describe_prefix",
|
||||
"grid_to_latlon", "PHONETIC", "LOOKUP_URL", "BACKUP_URL",
|
||||
"is_service_call", "SHAPE", "SERVICE_SHAPE"]
|
||||
"is_service_call", "licensed_call", "SHAPE", "SERVICE_SHAPE"]
|
||||
|
||||
# The FCC's own licence data, served as JSON without an account or a key.
|
||||
# US callsigns only; everything else resolves to what the prefix alone says.
|
||||
|
|
@ -130,6 +130,55 @@ SERVICE_SHAPE = re.compile(
|
|||
SERVICE_LICENCE = "GMRS or business licence"
|
||||
|
||||
|
||||
def licensed_call(call: str) -> str:
|
||||
"""The callsign a register could know, out of one that was heard.
|
||||
|
||||
Every mode dresses a callsign up in its own way and no licensing
|
||||
authority has heard of any of it:
|
||||
|
||||
W1AW-9 APRS: the ninth radio this licence runs
|
||||
WIDE2-1* APRS: the star marks the hop a packet came through
|
||||
ET3RFG/R FT8: a rover, operating away from the licensed address
|
||||
W1AW/4 operating in another district
|
||||
DL/G4ABC a guest in Germany -- G4ABC is the licence
|
||||
<...> FT8: a callsign this receiver has not heard spelled out
|
||||
|
||||
Returns the bare callsign, or "" where there is nothing to look up.
|
||||
Shared rather than written twice because getting it wrong is silent:
|
||||
asking a register about "W1AW-9" returns nothing at all, which looks
|
||||
exactly like a station that is not licensed.
|
||||
"""
|
||||
call = (call or "").strip().upper().rstrip("*")
|
||||
if not call or call.startswith("<"):
|
||||
return ""
|
||||
if call in ("CQ", "DE", "QRZ", "BEACON", "ALL", "MAIL", "TEST"):
|
||||
return ""
|
||||
if call.startswith("CQ "):
|
||||
return ""
|
||||
call = call.split("-", 1)[0] # the SSID is not licensed
|
||||
if "/" in call:
|
||||
# A guest call is prefix/home or home/suffix, and the licensed part
|
||||
# is whichever piece is a callsign in its own right. Longest wins,
|
||||
# because a suffix is one or two characters and a prefix is a
|
||||
# country: neither is ever longer than the callsign itself.
|
||||
pieces = [p for p in call.split("/") if p]
|
||||
real = [p for p in pieces if _looks_licensed(p)]
|
||||
if not real:
|
||||
return ""
|
||||
call = max(real, key=len)
|
||||
return call if _looks_licensed(call) else ""
|
||||
|
||||
|
||||
def _looks_licensed(call: str) -> bool:
|
||||
"""Whether something could be an amateur callsign at all.
|
||||
|
||||
A letter or two, a digit, and a letter or three. Deliberately loose --
|
||||
the register is the authority on whether a callsign exists, and this
|
||||
only has to keep obvious non-callsigns from being asked about.
|
||||
"""
|
||||
return bool(re.fullmatch(r"[A-Z0-9]{1,3}[0-9][A-Z]{1,4}", call or ""))
|
||||
|
||||
|
||||
def is_service_call(call: str) -> bool:
|
||||
"""True for a GMRS, business or public-safety callsign, not a ham one.
|
||||
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ from rich.table import Table
|
|||
from rich.text import Text
|
||||
|
||||
from . import version_notice
|
||||
from . import __version__
|
||||
from .bandplan import CATEGORIES, PRESETS, fmt_hz, in_category, search
|
||||
from .config import (DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_PATH, ScanConfig,
|
||||
is_first_run, list_profiles, load_config, load_default,
|
||||
|
|
@ -75,6 +76,11 @@ examples:
|
|||
# are allowed to do with it and the program is the only thing in front
|
||||
# of them.
|
||||
p.add_argument("--version", action="version", version=version_notice())
|
||||
# Before the subcommand, because it is about the program rather than
|
||||
# about any one thing it does. BANDSAUNTER_NO_SPLASH=1 does the same for
|
||||
# anybody who wants it off for good.
|
||||
p.add_argument("--no-splash", action="store_true",
|
||||
help="do not draw the title screen")
|
||||
sub = p.add_subparsers(dest="command")
|
||||
|
||||
# -- scan ------------------------------------------------------------
|
||||
|
|
@ -316,6 +322,12 @@ examples:
|
|||
default=None, metavar="HZ",
|
||||
help="the exact frequency, if the region's channel is "
|
||||
"not what you want")
|
||||
ap.add_argument("--lookup", dest="lookup", action="store_true",
|
||||
default=None,
|
||||
help="look up who each callsign is licensed to, and "
|
||||
"cache the answers (the default)")
|
||||
ap.add_argument("--no-lookup", dest="lookup", action="store_false",
|
||||
help="do not look callsigns up over the network")
|
||||
ap.add_argument("--window", action="store_true",
|
||||
help="open a window and show the stations on a map as "
|
||||
"they are heard, instead of a table in the terminal")
|
||||
|
|
@ -688,6 +700,12 @@ examples:
|
|||
f8.add_argument("--grid", default=None, metavar="SQUARE",
|
||||
help="your own grid square, so distances can be worked "
|
||||
"out (four characters, like IO91)")
|
||||
f8.add_argument("--lookup", dest="lookup", action="store_true",
|
||||
default=None,
|
||||
help="look up who each callsign is licensed to, and "
|
||||
"cache the answers (the default)")
|
||||
f8.add_argument("--no-lookup", dest="lookup", action="store_false",
|
||||
help="do not look callsigns up over the network")
|
||||
f8.add_argument("--units", default=None, choices=("metric", "imperial"),
|
||||
help="which units to show distances in")
|
||||
f8.add_argument("--calls-only", dest="calls_only", action="store_true",
|
||||
|
|
@ -1683,6 +1701,7 @@ def cmd_aprs(args) -> int:
|
|||
("packets_seen", "packets_seen"), ("hold", "hold"),
|
||||
("location", "location"), ("units", "units"),
|
||||
("unparsed", "unparsed"), ("digipeated", "digipeated"),
|
||||
("lookup", "lookup"),
|
||||
("report", "report"), ("csv", "csv"), ("kml", "kml"),
|
||||
("radius", "radius"), ("theme", "theme"),
|
||||
("map_brightness", "map_brightness"),
|
||||
|
|
@ -2183,6 +2202,17 @@ def main(argv=None) -> int:
|
|||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
# After parsing, so that --help and a bad argument say their piece
|
||||
# without a title screen over the top of it, and so that anything piped
|
||||
# somewhere else gets nothing at all.
|
||||
from . import splash
|
||||
|
||||
splash.show(console, splash.SCANNER_NAME,
|
||||
("Conceived by: The Dust Council",
|
||||
"100% AI Coded by Claude Code.",
|
||||
f"{__version__} · scan, record and identify"),
|
||||
no_splash=getattr(args, "no_splash", False))
|
||||
|
||||
if args.command is None:
|
||||
cfg, source = load_default()
|
||||
if is_first_run() and sys.stdin.isatty() and sys.stdout.isatty():
|
||||
|
|
@ -2250,6 +2280,7 @@ def cmd_ft8(args) -> int:
|
|||
("hold", "hold"), ("lowest", "lowest"),
|
||||
("highest", "highest"), ("most", "most"),
|
||||
("rounds", "rounds"), ("grid", "grid"),
|
||||
("lookup", "lookup"),
|
||||
("units", "units"), ("calls_only", "calls_only"),
|
||||
("report", "report"), ("csv", "csv"),
|
||||
("adif", "adif")):
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ import yaml
|
|||
|
||||
from . import ft8code as code
|
||||
from . import ft8wave as wave
|
||||
from .callsign import licensed_call
|
||||
from .settings import Setting, format_value
|
||||
|
||||
__all__ = ["Ft8Options", "OPTIONS", "OPTION_GROUPS", "defaults", "in_group",
|
||||
|
|
@ -41,7 +42,7 @@ __all__ = ["Ft8Options", "OPTIONS", "OPTION_GROUPS", "defaults", "in_group",
|
|||
"pump", "finish", "report", "load_options", "save_options",
|
||||
"options_path", "logs_in", "BANDS", "band_named", "band_text",
|
||||
"use_band", "slot_start", "next_slot", "grid_at", "grid_away",
|
||||
"SLOT", "audio_from"]
|
||||
"SLOT", "audio_from", "open_register", "licensee", "who_text"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
|
@ -207,6 +208,7 @@ class Ft8Options:
|
|||
|
||||
# -- showing --------------------------------------------------------
|
||||
grid: str = "" # where the aerial is, as a grid square
|
||||
lookup: bool = True # who each callsign is licensed to
|
||||
units: str = "metric"
|
||||
calls_only: bool = False # leave out free text and telemetry
|
||||
|
||||
|
|
@ -369,6 +371,20 @@ OPTIONS: tuple[Setting, ...] = (
|
|||
"the decodes are still recorded; there is simply nothing to measure "
|
||||
"them from.",
|
||||
flags=("--grid",), example="IO91", metavar="SQUARE"),
|
||||
O("lookup", "Look up callsigns", "Showing", "bool",
|
||||
"find out who each station is licensed to, and where",
|
||||
"Every FT8 exchange is two callsigns, and a callsign is issued by a "
|
||||
"government, so it can be looked up: the name on the licence and the "
|
||||
"town. Answers are kept in ~/.cache/bandsaunter/callsigns.json and "
|
||||
"shared with every other part of this program that resolves a "
|
||||
"callsign, so a band worked night after night is asked about once a "
|
||||
"month. The lookup never holds up a decode -- it happens on its own "
|
||||
"thread and the name appears in a later slot. The databases are "
|
||||
"United States registers, so the DX that makes this mode worth "
|
||||
"listening to comes back unlisted; the country shown beside it comes "
|
||||
"from the callsign's own structure and needs no network, which on a "
|
||||
"band full of grid squares is most of what there is to add anyway.",
|
||||
flags=("--lookup",), off_flags=("--no-lookup",)),
|
||||
O("units", "Show readings in", "Showing", "choice",
|
||||
"metric or imperial, for the display and the export",
|
||||
"Distances only. Signal reports are in decibels either way, that "
|
||||
|
|
@ -529,7 +545,13 @@ class Band:
|
|||
|
||||
stations: dict = field(default_factory=dict)
|
||||
decodes: list = field(default_factory=list)
|
||||
# Two different books, and the names are worth keeping straight. This
|
||||
# one turns a twenty-two bit hash back into the callsign that made it,
|
||||
# and is part of the protocol.
|
||||
book: code.CallBook = field(default_factory=code.CallBook)
|
||||
# This one says who that callsign belongs to, and is a licence
|
||||
# register on the far side of a network.
|
||||
register: object = None
|
||||
slots: int = 0
|
||||
|
||||
def add(self, found) -> None:
|
||||
|
|
@ -559,6 +581,14 @@ class Band:
|
|||
station.said.append(found.text)
|
||||
if len(station.said) > 32:
|
||||
del station.said[0]
|
||||
# Asked once, when the station is first heard. Both callsigns in
|
||||
# an exchange are real stations, so both are worth knowing -- the
|
||||
# one being answered may never transmit within earshot.
|
||||
if self.register is not None and station.decodes == 1:
|
||||
for call in found.calls:
|
||||
bare = licensed_call(call)
|
||||
if bare:
|
||||
self.register.get(bare)
|
||||
|
||||
def all(self) -> list:
|
||||
return list(self.stations.values())
|
||||
|
|
@ -582,6 +612,62 @@ class Heard:
|
|||
AUDIO_RATE = 12_000 # what the decoding wants, and a whole division
|
||||
|
||||
|
||||
def open_register(options: Ft8Options):
|
||||
"""The licence register, or an offline one if lookups are turned off.
|
||||
|
||||
Offline rather than absent: an offline register still answers the
|
||||
country and the licensing district, which come out of the callsign's
|
||||
own structure and need no network -- and on a band whose whole point is
|
||||
distance, the country is most of what a name would have added.
|
||||
"""
|
||||
from .callsign import CallsignBook
|
||||
|
||||
return CallsignBook(online=bool(options.lookup))
|
||||
|
||||
|
||||
def licensee(band: Band, call: str):
|
||||
"""Who a callsign belongs to, as far as is known right now.
|
||||
|
||||
Never waits. A slot has to be decoded in well under fifteen seconds or
|
||||
the next one is missed, and a network request in that path would be the
|
||||
one way to turn a working receiver into a deaf one.
|
||||
"""
|
||||
if band is None or band.register is None:
|
||||
return None
|
||||
bare = licensed_call(call)
|
||||
return band.register.get(bare) if bare else None
|
||||
|
||||
|
||||
def who_text(who) -> str:
|
||||
"""One line about whose licence a callsign is, for a table cell."""
|
||||
if who is None:
|
||||
return ""
|
||||
if who.name:
|
||||
where = who.location or who.country
|
||||
return f"{who.name}" + (f" — {where}" if where else "")
|
||||
if who.status == "pending":
|
||||
return "…"
|
||||
return who.country or ""
|
||||
|
||||
|
||||
def keep_lookups(band: Band) -> None:
|
||||
"""Write what was learned to the disk before the run ends.
|
||||
|
||||
Without this the lookups happen and are thrown away, so every evening
|
||||
asks the register about the same band 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.
|
||||
"""
|
||||
register = getattr(band, "register", None)
|
||||
if register is None:
|
||||
return
|
||||
try:
|
||||
register.wait(3.0)
|
||||
register.save()
|
||||
except Exception:
|
||||
pass # a cache that cannot be written is not a failed run
|
||||
|
||||
|
||||
def open_device(console, options: Ft8Options):
|
||||
"""The receiver, or a made-up band, or None if neither can be had."""
|
||||
from rich.panel import Panel
|
||||
|
|
@ -731,6 +817,7 @@ def listen(console, options: Ft8Options, output_dir: str,
|
|||
started = time.time()
|
||||
heard = heard if heard is not None else Heard()
|
||||
heard.started = started
|
||||
heard.band.register = open_register(options)
|
||||
# The receiver first. Announcing that it is listening and then failing
|
||||
# to open a dongle reads as though the listening went wrong, when what
|
||||
# went wrong happened before any of it started.
|
||||
|
|
@ -805,6 +892,7 @@ def finish(console, options: Ft8Options, output_dir: str, heard: Heard,
|
|||
"""Close the log, write the exports, and print the report."""
|
||||
from . import ft8log
|
||||
|
||||
keep_lookups(heard.band)
|
||||
if log is not None:
|
||||
log.close()
|
||||
console.print(f"[grey62]{log.lines} decodes written to "
|
||||
|
|
@ -856,6 +944,9 @@ def report(console, band: Band, options: Ft8Options) -> None:
|
|||
f"{band.slots} slots")
|
||||
t = Table(box=None, header_style="bold", pad_edge=False)
|
||||
t.add_column("station")
|
||||
named = options.lookup and band.register is not None
|
||||
if named:
|
||||
t.add_column("licensed to", style="grey62", overflow="fold")
|
||||
t.add_column("grid")
|
||||
if options.grid:
|
||||
t.add_column("away")
|
||||
|
|
@ -865,7 +956,10 @@ def report(console, band: Band, options: Ft8Options) -> None:
|
|||
t.add_column("audio", justify="right")
|
||||
t.add_column("CQ", justify="right")
|
||||
for s in stations[:60]:
|
||||
row = [s.call, s.grid or "—"]
|
||||
row = [s.call]
|
||||
if named:
|
||||
row.append(who_text(licensee(band, s.call)))
|
||||
row.append(s.grid or "—")
|
||||
if options.grid:
|
||||
row.append(_away_text(s, options) or "—")
|
||||
row += [str(s.decodes), f"{s.best_snr:.0f}", f"{s.worst_snr:.0f}",
|
||||
|
|
|
|||
|
|
@ -72,6 +72,13 @@ RESETTLE_NM = 12.0
|
|||
# the map settling rather than wandering, a little is enough.
|
||||
GROUND_MARGIN = 0.12
|
||||
|
||||
# How much stretching of the map underneath to put up with before fetching a
|
||||
# sharper one. Something is needed: a window dragged one pixel wider must not
|
||||
# refetch, and a window taken from a quarter of the screen to all of it must.
|
||||
# Fifteen per cent is about where the lettering on a coastline starts to look
|
||||
# soft, and is comfortably more than any resize that was not deliberate.
|
||||
GROUND_STRETCH = 0.15
|
||||
|
||||
# What to do about a map that came back with squares missing from it. The
|
||||
# usual cause is a resize: the window grows, a sharper zoom is chosen, and a
|
||||
# hundred tiles that have never been on this disk are asked for at once --
|
||||
|
|
@ -1075,6 +1082,20 @@ def _build():
|
|||
# which is rate-limited inside and does nothing at all once the
|
||||
# map is whole.
|
||||
self.sky.reask_ground()
|
||||
|
||||
# And a map fetched for a smaller window is still a map of the
|
||||
# right piece of world, so nothing above notices that it is now
|
||||
# being stretched. A window opened at its default size and then
|
||||
# taken to the whole screen used to keep the map it started with
|
||||
# until an aircraft wandered far enough to move the view out of
|
||||
# the fetched box, which on a quiet band is a long time to look
|
||||
# at a blurred coastline.
|
||||
if self._stretched(levels, box, view):
|
||||
scale = 1.0 + 2.0 * GROUND_MARGIN
|
||||
self.sky.want_ground(self.ground_key(view),
|
||||
self.ground_box(view),
|
||||
(int(view.width * scale),
|
||||
int(view.height * scale)))
|
||||
# Cutting the view out of the fetched map, dimming it and
|
||||
# looking every level up in the palette is about seventy
|
||||
# milliseconds over two megapixels, and none of it changes
|
||||
|
|
@ -1098,6 +1119,33 @@ def _build():
|
|||
image = QImage(pixels.data, width, height, 3 * width, RGB888)
|
||||
painter.drawImage(0, 0, image)
|
||||
|
||||
@staticmethod
|
||||
def _stretched(levels, box, view: Projection) -> bool:
|
||||
"""Whether the map in hand is being blown up to fill the window.
|
||||
|
||||
Measured as pixels of map per degree of world, in hand against
|
||||
wanted, which is the thing that actually shows: a map fetched
|
||||
for eleven hundred pixels across and drawn across nineteen
|
||||
hundred is the same map with each of its pixels covering nearly
|
||||
two.
|
||||
|
||||
Saying yes here cannot loop. The request that follows is keyed
|
||||
on the window's size, so once it has been answered the key
|
||||
matches and nothing more is asked -- which is what stops a
|
||||
window bigger than the tile budget can cover from asking
|
||||
forever. At that size the map is enlarged by design, and the
|
||||
readme has always said so.
|
||||
"""
|
||||
if levels is None or box is None or view.width < 1:
|
||||
return False
|
||||
across = box[3] - box[1]
|
||||
shown = view.east - view.west
|
||||
if across <= 0 or shown <= 0:
|
||||
return False
|
||||
have = levels.shape[1] / across
|
||||
want = view.width / shown
|
||||
return want > have * (1.0 + GROUND_STRETCH)
|
||||
|
||||
@staticmethod
|
||||
def _crop(levels, box, view: Projection):
|
||||
"""The part of the fetched map this view is looking at.
|
||||
|
|
@ -1654,7 +1702,7 @@ def _build():
|
|||
painter.setFont(self.head_font)
|
||||
painter.setPen(rgb(INK))
|
||||
painter.drawText(10, metrics.ascent() + 4, told)
|
||||
keys = ("d detail t trails g map [ ] bright "
|
||||
keys = ("d detail t trails g map f full [ ] bright "
|
||||
"+/- range q quit")
|
||||
painter.setPen(rgb(GRID))
|
||||
painter.drawText(self.width() - 8
|
||||
|
|
@ -1670,7 +1718,16 @@ def _build():
|
|||
self.view = SkyView(sky, self)
|
||||
self.setCentralWidget(self.view)
|
||||
self.setWindowTitle(title)
|
||||
# The size to come back to when the window is un-maximised, set
|
||||
# before maximising so that there is one.
|
||||
self.resize(1100, 800)
|
||||
# Maximised rather than a fixed size: this is a map, and the
|
||||
# thing somebody wants more of is map. Maximised rather than
|
||||
# true full screen, because the title bar is where the band and
|
||||
# the frequency are written, and a window with no frame is one
|
||||
# somebody has to know a key to get out of -- f is that key,
|
||||
# for anybody who wants the last few rows as well.
|
||||
self.showMaximized()
|
||||
self._timer = QTimer(self)
|
||||
self._timer.timeout.connect(self._tick)
|
||||
self._timer.start(REDRAW_MS)
|
||||
|
|
@ -1692,6 +1749,14 @@ def _build():
|
|||
self.view.trails = not self.view.trails
|
||||
elif text == "g":
|
||||
self.view.show_ground = not self.view.show_ground
|
||||
elif text == "f":
|
||||
# Back to maximised rather than to the small size it was
|
||||
# built at: leaving full screen should not shrink the map to
|
||||
# a quarter of the screen.
|
||||
if self.isFullScreen():
|
||||
self.showMaximized()
|
||||
else:
|
||||
self.showFullScreen()
|
||||
elif text in ("+", "="):
|
||||
self.sky.radius_nm = max(5.0, self.sky.radius_nm / 1.5)
|
||||
elif text == "-":
|
||||
|
|
|
|||
326
bandsaunter/register.py
Normal file
326
bandsaunter/register.py
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
"""Everything this program has ever found out about a callsign or an aircraft.
|
||||
|
||||
Both caches, read back and made browsable. The scanner, the recording
|
||||
browser, APRS and FT8 all resolve callsigns into the same file, and the
|
||||
aircraft side keeps its own; between them they are a record of who and what
|
||||
has been heard from this aerial, and until now the only way to read either
|
||||
was to open the JSON.
|
||||
|
||||
Nothing here writes. It reads two caches and turns them into rows and
|
||||
panels, which keeps it testable without a network, a receiver or a terminal,
|
||||
and means a mistake in here cannot lose an evening's lookups.
|
||||
|
||||
The addresses are licence records, public by law and already printed by the
|
||||
scanner's own reports; this shows them the same way rather than more
|
||||
prominently.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
__all__ = ["Entry", "load_callsigns", "load_aircraft", "load_all",
|
||||
"maps_url", "search", "KINDS", "cache_paths"]
|
||||
|
||||
KINDS = ("callsigns", "aircraft")
|
||||
|
||||
# Google's documented form for "show me this point". Coordinates only: the
|
||||
# callsign and the name stay on this machine, because a map does not need
|
||||
# them to show a place and a URL is the one part of this that leaves.
|
||||
MAPS = "https://www.google.com/maps/search/?api=1&query={lat:.6f},{lon:.6f}"
|
||||
|
||||
|
||||
def cache_paths() -> dict:
|
||||
root = Path(os.environ.get("XDG_CACHE_HOME") or "~/.cache").expanduser()
|
||||
root = root / "bandsaunter"
|
||||
return {"callsigns": root / "callsigns.json",
|
||||
"aircraft": root / "flights.json"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Entry:
|
||||
"""One thing that was looked up, flattened for showing.
|
||||
|
||||
``rows`` is every field that had a value, in the order a person would
|
||||
read them, rather than the order the register happened to send them.
|
||||
"""
|
||||
|
||||
kind: str = ""
|
||||
key: str = "" # what it is filed under
|
||||
title: str = "" # the callsign or the registration
|
||||
what: str = "" # a name, or a make and model
|
||||
where: str = "" # a town, or a route
|
||||
when: float = 0.0 # when it was looked up
|
||||
status: str = ""
|
||||
position: tuple | None = None
|
||||
rows: list = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def mappable(self) -> bool:
|
||||
return self.position is not None
|
||||
|
||||
def maps(self) -> str:
|
||||
return maps_url(self)
|
||||
|
||||
|
||||
def maps_url(entry: Entry) -> str:
|
||||
"""A link to where this is, or "" where there is nowhere to point at."""
|
||||
if entry is None or entry.position is None:
|
||||
return ""
|
||||
lat, lon = entry.position
|
||||
return MAPS.format(lat=float(lat), lon=float(lon))
|
||||
|
||||
|
||||
def _when(value) -> str:
|
||||
try:
|
||||
value = float(value or 0)
|
||||
except (TypeError, ValueError):
|
||||
return ""
|
||||
if value <= 0:
|
||||
return ""
|
||||
return datetime.fromtimestamp(value).strftime("%Y-%m-%d %H:%M")
|
||||
|
||||
|
||||
def _read(path: Path):
|
||||
try:
|
||||
body = json.loads(Path(path).read_text())
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return body if isinstance(body, dict) else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Callsigns
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Label, field, and whether it is worth a line of its own. Ordered the way
|
||||
# somebody reads a licence rather than the way the register sends one.
|
||||
_CALL_FIELDS = (
|
||||
("licensed to", "name"),
|
||||
("class", "oper_class"),
|
||||
("licence", "licence_type"),
|
||||
("street", "street"),
|
||||
("town", "location"),
|
||||
("postcode", "postcode"),
|
||||
("country", "country"),
|
||||
("district", "district"),
|
||||
("grid", "grid"),
|
||||
("expires", "expires"),
|
||||
("previously", "previous"),
|
||||
("trustee", "trustee"),
|
||||
)
|
||||
|
||||
|
||||
def load_callsigns(path: Path | None = None) -> list[Entry]:
|
||||
"""Every callsign in the cache, whether or not it resolved.
|
||||
|
||||
The ones that did not are kept on purpose. "Asked about and not in any
|
||||
register" is a fact about a station, and a list that quietly dropped
|
||||
them would make a long evening of unlisted foreign stations look like an
|
||||
evening when nothing was looked up.
|
||||
"""
|
||||
body = _read(path or cache_paths()["callsigns"])
|
||||
if not body:
|
||||
return []
|
||||
out = []
|
||||
for call, one in body.items():
|
||||
if not isinstance(one, dict):
|
||||
continue
|
||||
rows = []
|
||||
for label, field_name in _CALL_FIELDS:
|
||||
value = str(one.get(field_name) or "").strip()
|
||||
if value:
|
||||
rows.append((label, value))
|
||||
lat = _float(one.get("latitude"))
|
||||
lon = _float(one.get("longitude"))
|
||||
position = (lat, lon) if (lat or lon) else None
|
||||
if position is not None:
|
||||
how = " (from the grid square)" if one.get("from_grid") else ""
|
||||
rows.append(("position", f"{lat:.5f}, {lon:.5f}{how}"))
|
||||
rows.append(("status", _explain(str(one.get("status") or ""))))
|
||||
if one.get("source"):
|
||||
rows.append(("answered by", str(one["source"])))
|
||||
looked = _when(one.get("fetched_at"))
|
||||
if looked:
|
||||
rows.append(("looked up", looked))
|
||||
out.append(Entry(
|
||||
kind="callsigns", key=str(call), title=str(call),
|
||||
what=str(one.get("name") or ""),
|
||||
where=str(one.get("location") or one.get("country") or ""),
|
||||
when=_float(one.get("fetched_at")),
|
||||
status=str(one.get("status") or ""),
|
||||
position=position, rows=rows))
|
||||
return sorted(out, key=lambda e: e.title)
|
||||
|
||||
|
||||
def _explain(status: str) -> str:
|
||||
"""What a status means, since four of the five are not self-evident."""
|
||||
return {
|
||||
"found": "found in a register",
|
||||
"unlisted": "asked about, in no register reachable from here",
|
||||
"service": "not an amateur callsign — a business or GMRS licence",
|
||||
"offline": "could not be asked: nothing reachable",
|
||||
"pending": "the lookup is still out",
|
||||
}.get(status, status)
|
||||
|
||||
|
||||
def _float(value) -> float:
|
||||
try:
|
||||
return float(value or 0.0)
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Aircraft
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_PLANE_FIELDS = (
|
||||
("registration", "registration"),
|
||||
("type", "type_code"),
|
||||
("model", "model"),
|
||||
("made by", "manufacturer"),
|
||||
("operator", "operator"),
|
||||
("airline", "airline"),
|
||||
("callsign", "callsign"),
|
||||
("country", "country"),
|
||||
("owner's country", "owner_country"),
|
||||
)
|
||||
|
||||
|
||||
def load_aircraft(path: Path | None = None) -> list[Entry]:
|
||||
"""Every aircraft in the cache, with its route where one is known.
|
||||
|
||||
The route is filed against the flight number rather than the airframe,
|
||||
because one aeroplane flies four different routes in a day -- so the two
|
||||
halves are joined here rather than assumed to be one record.
|
||||
"""
|
||||
body = _read(path or cache_paths()["aircraft"])
|
||||
if not body:
|
||||
return []
|
||||
planes = body.get("aircraft") or {}
|
||||
routes = body.get("routes") or {}
|
||||
out = []
|
||||
for icao, one in planes.items():
|
||||
if not isinstance(one, dict):
|
||||
continue
|
||||
rows = [("ICAO address", str(icao).upper())]
|
||||
for label, field_name in _PLANE_FIELDS:
|
||||
value = str(one.get(field_name) or "").strip()
|
||||
if value:
|
||||
rows.append((label, value))
|
||||
route = routes.get(str(one.get("callsign") or "").upper()) \
|
||||
if isinstance(routes, dict) else None
|
||||
leg = _leg(one, route if isinstance(route, dict) else {})
|
||||
for label, value in leg:
|
||||
rows.append((label, value))
|
||||
rows.append(("status", _explain_plane(str(one.get("status") or ""))))
|
||||
looked = _when(one.get("fetched_at"))
|
||||
if looked:
|
||||
rows.append(("looked up", looked))
|
||||
position = _airport_of(one, route if isinstance(route, dict) else {})
|
||||
if position is not None:
|
||||
rows.append(("origin airport at",
|
||||
f"{position[0]:.4f}, {position[1]:.4f}"))
|
||||
out.append(Entry(
|
||||
kind="aircraft", key=str(icao).upper(),
|
||||
title=str(one.get("registration") or "").strip()
|
||||
or str(icao).upper(),
|
||||
what=" ".join(x for x in (one.get("manufacturer"),
|
||||
one.get("model")) if x).strip()
|
||||
or str(one.get("type_code") or ""),
|
||||
where=_where_plane(one, route if isinstance(route, dict) else {}),
|
||||
when=_float(one.get("fetched_at")),
|
||||
status=str(one.get("status") or ""),
|
||||
position=position, rows=rows))
|
||||
return sorted(out, key=lambda e: e.title)
|
||||
|
||||
|
||||
def _leg(one: dict, route: dict) -> list:
|
||||
out = []
|
||||
origin = one.get("origin") or route.get("origin") or ""
|
||||
origin_code = one.get("origin_code") or route.get("origin_code") or ""
|
||||
dest = one.get("destination") or route.get("destination") or ""
|
||||
dest_code = one.get("destination_code") or route.get("destination_code") \
|
||||
or ""
|
||||
if origin or origin_code:
|
||||
out.append(("from", f"{origin} ({origin_code})".strip()
|
||||
if origin_code else str(origin)))
|
||||
if dest or dest_code:
|
||||
out.append(("to", f"{dest} ({dest_code})".strip()
|
||||
if dest_code else str(dest)))
|
||||
stops = one.get("stops") or route.get("stops") or ()
|
||||
if len(stops) > 2:
|
||||
out.append(("all stops", " — ".join(str(s) for s in stops)))
|
||||
source = one.get("route_source") or route.get("route_source") or ""
|
||||
if source:
|
||||
out.append(("route from", str(source)))
|
||||
return out
|
||||
|
||||
|
||||
def _where_plane(one: dict, route: dict) -> str:
|
||||
a = one.get("origin_code") or route.get("origin_code") or ""
|
||||
b = one.get("destination_code") or route.get("destination_code") or ""
|
||||
if a and b:
|
||||
return f"{a} → {b}"
|
||||
return str(one.get("operator") or one.get("country") or "")
|
||||
|
||||
|
||||
def _airport_of(one: dict, route: dict):
|
||||
"""Where the flight started, which is the only place an aircraft record
|
||||
can honestly be put on a map.
|
||||
|
||||
The aircraft itself is not anywhere -- this is a register of airframes,
|
||||
not a position report -- so pointing a map at its origin airport is the
|
||||
nearest true thing. Labelled as such where it is shown.
|
||||
"""
|
||||
lat = _float(one.get("origin_lat") or route.get("origin_lat"))
|
||||
lon = _float(one.get("origin_lon") or route.get("origin_lon"))
|
||||
return (lat, lon) if (lat or lon) else None
|
||||
|
||||
|
||||
def _explain_plane(status: str) -> str:
|
||||
return {
|
||||
"found": "found in a register",
|
||||
"local": "worked out from the address and callsign alone",
|
||||
"unlisted": "asked about, in no register reachable from here",
|
||||
"offline": "could not be asked: nothing reachable",
|
||||
"pending": "the lookup is still out",
|
||||
}.get(status, status)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Browsing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def load_all(paths: dict | None = None) -> dict:
|
||||
"""Both caches, as lists of entries, keyed by kind."""
|
||||
paths = paths or cache_paths()
|
||||
return {"callsigns": load_callsigns(paths.get("callsigns")),
|
||||
"aircraft": load_aircraft(paths.get("aircraft"))}
|
||||
|
||||
|
||||
def search(entries, query: str) -> list:
|
||||
"""The entries a typed query matches, over every field shown.
|
||||
|
||||
Every field rather than the title, because the interesting question is
|
||||
usually not "which callsign" but "who was in Arizona" or "what
|
||||
Bombardiers have gone over", and both of those live in the detail.
|
||||
"""
|
||||
q = (query or "").strip().lower()
|
||||
if not q:
|
||||
return list(entries)
|
||||
out = []
|
||||
for entry in entries:
|
||||
haystack = " ".join([entry.title, entry.what, entry.where,
|
||||
entry.status]
|
||||
+ [f"{label} {value}"
|
||||
for label, value in entry.rows]).lower()
|
||||
if all(word in haystack for word in q.split()):
|
||||
out.append(entry)
|
||||
return out
|
||||
295
bandsaunter/splash.py
Normal file
295
bandsaunter/splash.py
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
"""The title screen.
|
||||
|
||||
Drawn in braille, two dots wide and four tall to a character, which is eight
|
||||
times the detail a block gives and is what makes room for capitals and
|
||||
lowercase at the same height. It also reads as something drawn rather than
|
||||
as masonry, which is the point.
|
||||
|
||||
The font is cut by hand rather than pulled in: it is twelve letters at cap
|
||||
height seven, and a figlet library to draw that would be the largest thing in
|
||||
the package's requirements. Cut small on purpose -- at seven rows there is
|
||||
only one way to draw each letter, and so no room to draw it badly -- and then
|
||||
doubled, because a stroke two dots thick reads as a line where one dot thick
|
||||
reads as a dotted line.
|
||||
|
||||
Shown only on a terminal. Everything in this program can be piped into
|
||||
something else -- the band table, the sensor list, a line per packet -- and a
|
||||
title screen in the middle of that is corruption rather than decoration, so
|
||||
anything that is not a terminal gets nothing at all. ``--no-splash`` turns
|
||||
it off on a terminal too, for anybody who would rather it did not.
|
||||
|
||||
The gradient runs deep blue through cyan to a cool white across the width.
|
||||
Not the waterfall ramp the rest of the program draws in -- that one goes on
|
||||
through green and yellow to red because it stands in for a spectrum and has
|
||||
to mean something. This means nothing, so it is allowed to be a colour
|
||||
scheme.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
__all__ = ["banner", "pixels", "to_braille", "show", "wanted",
|
||||
"FONT", "CAPS", "LOWER", "ASCENDERS", "ROWS", "HEIGHT",
|
||||
"SCANNER_NAME", "BROWSER_NAME",
|
||||
"BANDSAUNTER", "SAUNTERBROWSE"]
|
||||
|
||||
# Four rows of braille, each cell two dots wide and four tall. Braille
|
||||
# because the dots read as a drawn line rather than as masonry, and because
|
||||
# eight dots to a character is four times the vertical detail a block gives
|
||||
# -- which is what makes room for capitals and lowercase at the same time.
|
||||
ROWS = 4 # braille rows a banner occupies
|
||||
HEIGHT = 16 # pixel rows, which is ROWS * 4
|
||||
BASELINE = 14 # the row under the last one any letter puts ink on
|
||||
|
||||
# Where each of a braille cell's eight dots lives, as (row, column).
|
||||
# 1 4 0x01 0x08
|
||||
# 2 5 0x02 0x10
|
||||
# 3 6 0x04 0x20
|
||||
# 7 8 0x40 0x80
|
||||
DOTS = ((0x01, 0x08), (0x02, 0x10), (0x04, 0x20), (0x40, 0x80))
|
||||
BRAILLE = 0x2800
|
||||
BLANK = chr(BRAILLE) # a cell with no dots in it
|
||||
|
||||
# Cut at cap height seven and x-height five -- the size small bitmap fonts
|
||||
# have always been cut at, where there is only one way to draw each letter
|
||||
# and so no room to draw it badly -- and then doubled. Doubling is what
|
||||
# makes a stroke two dots thick in both directions, and a stroke two dots
|
||||
# thick reads as a line where one dot thick reads as a dotted line.
|
||||
CAPS: dict[str, tuple[str, ...]] = {
|
||||
"B": ("####.",
|
||||
"#...#",
|
||||
"#...#",
|
||||
"####.",
|
||||
"#...#",
|
||||
"#...#",
|
||||
"####."),
|
||||
"S": (".####",
|
||||
"#....",
|
||||
"#....",
|
||||
".###.",
|
||||
"....#",
|
||||
"....#",
|
||||
"####."),
|
||||
}
|
||||
|
||||
# Letters that sit on the baseline and reach the x-height, and no further.
|
||||
LOWER: dict[str, tuple[str, ...]] = {
|
||||
"a": (".###.",
|
||||
"....#",
|
||||
".####",
|
||||
"#...#",
|
||||
".####"),
|
||||
"e": (".###.",
|
||||
"#...#",
|
||||
"#####",
|
||||
"#....",
|
||||
".###."),
|
||||
"n": ("#.##.",
|
||||
"##..#",
|
||||
"#...#",
|
||||
"#...#",
|
||||
"#...#"),
|
||||
"o": (".###.",
|
||||
"#...#",
|
||||
"#...#",
|
||||
"#...#",
|
||||
".###."),
|
||||
"r": ("#.##.",
|
||||
"##..#",
|
||||
"#....",
|
||||
"#....",
|
||||
"#...."),
|
||||
"s": (".####",
|
||||
"#....",
|
||||
".###.",
|
||||
"....#",
|
||||
"####."),
|
||||
"u": ("#...#",
|
||||
"#...#",
|
||||
"#...#",
|
||||
"#..##",
|
||||
".##.#"),
|
||||
"w": ("#...#",
|
||||
"#...#",
|
||||
"#.#.#",
|
||||
"##.##",
|
||||
"#...#"),
|
||||
}
|
||||
|
||||
# Letters that reach above the x-height: a full ascender, and a t, which is
|
||||
# neither one thing nor the other and has always needed its own entry.
|
||||
ASCENDERS: dict[str, tuple[str, ...]] = {
|
||||
"d": ("....#",
|
||||
"....#",
|
||||
".###.",
|
||||
"#...#",
|
||||
"#...#",
|
||||
"#...#",
|
||||
".###."),
|
||||
"t": (".#...",
|
||||
".#...",
|
||||
"####.",
|
||||
".#...",
|
||||
".#...",
|
||||
".###."),
|
||||
}
|
||||
|
||||
FONT = {**CAPS, **LOWER, **ASCENDERS}
|
||||
|
||||
SCANNER_NAME = "BandSaunter"
|
||||
BROWSER_NAME = "SaunterBrowse"
|
||||
|
||||
# What the two names used to be called, when the font was capitals only.
|
||||
BANDSAUNTER = SCANNER_NAME
|
||||
SAUNTERBROWSE = BROWSER_NAME
|
||||
|
||||
|
||||
def _double(glyph) -> list[str]:
|
||||
"""Twice the size in both directions. See the note on stroke width."""
|
||||
out = []
|
||||
for row in glyph:
|
||||
wide = "".join(c * 2 for c in row)
|
||||
out.extend((wide, wide))
|
||||
return out
|
||||
|
||||
|
||||
def pixels(word: str) -> list[str]:
|
||||
"""One word as a bitmap, each letter on its proper line.
|
||||
|
||||
Capitals and ascenders rise from the baseline to the cap height and the
|
||||
rest only to the x-height, which is the whole point of doing this in
|
||||
braille: a block font has five rows to spend and cannot afford two
|
||||
heights.
|
||||
"""
|
||||
rows = [""] * HEIGHT
|
||||
for letter in word or "":
|
||||
if letter in CAPS:
|
||||
glyph = _double(CAPS[letter])
|
||||
elif letter in ASCENDERS:
|
||||
glyph = _double(ASCENDERS[letter])
|
||||
elif letter in LOWER:
|
||||
glyph = _double(LOWER[letter])
|
||||
else:
|
||||
continue # no glyph: shorter, rather than gappy
|
||||
top = BASELINE - len(glyph)
|
||||
wide = max(len(r) for r in glyph)
|
||||
for y in range(HEIGHT):
|
||||
rows[y] += (glyph[y - top] if top <= y < top + len(glyph)
|
||||
else " " * wide) + " "
|
||||
return rows
|
||||
|
||||
|
||||
def to_braille(rows) -> list[str]:
|
||||
"""A bitmap as braille, two dots across and four down to a character."""
|
||||
if not rows:
|
||||
return []
|
||||
wide = max(len(r) for r in rows)
|
||||
if wide % 2:
|
||||
wide += 1
|
||||
grid = [r.ljust(wide) for r in rows]
|
||||
while len(grid) % 4:
|
||||
grid.append(" " * wide)
|
||||
out = []
|
||||
for top in range(0, len(grid), 4):
|
||||
line = ""
|
||||
for left in range(0, wide, 2):
|
||||
bits = 0
|
||||
for dy in range(4):
|
||||
for dx in range(2):
|
||||
if grid[top + dy][left + dx] not in " .":
|
||||
bits |= DOTS[dy][dx]
|
||||
line += chr(BRAILLE + bits)
|
||||
out.append(line.rstrip() or " ")
|
||||
return out
|
||||
|
||||
|
||||
def banner(word: str) -> list[str]:
|
||||
"""One word, as rows of braille ready to print."""
|
||||
drawn = pixels(word)
|
||||
if not any(r.strip() for r in drawn):
|
||||
return []
|
||||
return to_braille(drawn)
|
||||
|
||||
|
||||
# Deep blue, through electric blue and azure, to cyan and a cool white at the
|
||||
# far end. Deliberately *not* the waterfall ramp the rest of this program
|
||||
# draws in: that one runs through green and yellow to red because it is
|
||||
# standing in for a spectrum and has to mean something. A title screen means
|
||||
# nothing, so it is free to be a colour scheme, and this is the one a terminal
|
||||
# has always had. Blue is never the weakest channel and red is never the
|
||||
# strongest, which is what keeps it cold all the way along.
|
||||
_RAMP = ((10, 40, 140), (0, 90, 210), (0, 160, 245),
|
||||
(0, 225, 255), (210, 250, 255))
|
||||
|
||||
|
||||
def _colour(fraction: float) -> str:
|
||||
"""A point on the ramp, as a style rich understands."""
|
||||
fraction = max(0.0, min(1.0, fraction))
|
||||
span = len(_RAMP) - 1
|
||||
at = fraction * span
|
||||
first = min(int(at), span - 1)
|
||||
mix = at - first
|
||||
a, b = _RAMP[first], _RAMP[first + 1]
|
||||
rgb = tuple(int(round(a[i] + (b[i] - a[i]) * mix)) for i in range(3))
|
||||
return f"rgb({rgb[0]},{rgb[1]},{rgb[2]})"
|
||||
|
||||
|
||||
def wanted(console=None, no_splash: bool = False) -> bool:
|
||||
"""Whether to draw one at all.
|
||||
|
||||
Three ways to say no, because a title screen that cannot be turned off
|
||||
is a title screen somebody will end up grepping out of a log:
|
||||
``--no-splash``, the environment, and not being a terminal.
|
||||
"""
|
||||
if no_splash:
|
||||
return False
|
||||
if os.environ.get("BANDSAUNTER_NO_SPLASH"):
|
||||
return False
|
||||
if console is not None:
|
||||
return bool(getattr(console, "is_terminal", False))
|
||||
return bool(sys.stdout.isatty())
|
||||
|
||||
|
||||
def show(console, word: str, lines=(), *, no_splash: bool = False,
|
||||
pause: float = 0.0, force: bool = False) -> bool:
|
||||
"""Draw the title screen. Returns whether anything was drawn.
|
||||
|
||||
``pause`` is for a program that is about to take the whole screen over:
|
||||
without it the banner is replaced in the same tenth of a second it was
|
||||
drawn in, which is a waste of everybody's terminal.
|
||||
"""
|
||||
from rich.text import Text
|
||||
|
||||
if not force and not wanted(console, no_splash):
|
||||
return False
|
||||
rows = banner(word)
|
||||
if not rows:
|
||||
return False
|
||||
|
||||
width = max(len(row) for row in rows)
|
||||
console.print()
|
||||
for row in rows:
|
||||
text = Text()
|
||||
for i, char in enumerate(row):
|
||||
# A braille blank is U+2800 rather than a space, and colouring
|
||||
# something with no dots in it spends an escape sequence to no
|
||||
# effect -- which on four rows of seventy-odd cells is most of
|
||||
# what would be written.
|
||||
if char in (" ", BLANK):
|
||||
text.append(char)
|
||||
else:
|
||||
text.append(char, style=_colour(i / max(1, width - 1)))
|
||||
console.print(text, justify="center")
|
||||
for i, line in enumerate(lines):
|
||||
# The first line under the banner is the one that gets read; the
|
||||
# rest are dimmer, in the order they were given.
|
||||
style = "bold white" if i == 0 else "grey62"
|
||||
console.print(Text(line, style=style), justify="center")
|
||||
console.print()
|
||||
if pause > 0:
|
||||
import time
|
||||
|
||||
time.sleep(pause)
|
||||
return True
|
||||
|
|
@ -1018,8 +1018,19 @@ class AprsDisplay:
|
|||
from .acurite import Measure, compass, format_measure
|
||||
from .aprs import signal_text
|
||||
|
||||
from .aprs import licensee, who_text
|
||||
|
||||
named = self.net is not None and getattr(self.net, "book", None) \
|
||||
is not None
|
||||
t = Table(box=None, header_style="bold", pad_edge=False, expand=False)
|
||||
t.add_column("station", width=10, no_wrap=True)
|
||||
# Wide terminals only. A name is the most interesting thing about a
|
||||
# callsign and the least urgent: what somebody watching a channel
|
||||
# needs is who is transmitting now, and the names are all in the
|
||||
# report afterwards.
|
||||
if named and width >= 110:
|
||||
t.add_column("licensed to", width=22, style="grey62",
|
||||
no_wrap=True)
|
||||
if width >= 96:
|
||||
t.add_column("what", width=15, style="grey62", no_wrap=True)
|
||||
t.add_column("said", overflow="fold")
|
||||
|
|
@ -1032,6 +1043,9 @@ class AprsDisplay:
|
|||
t.add_column("ago", width=5, justify="right", style="grey62")
|
||||
for station in here:
|
||||
row = [Text(station.call, style="bold")]
|
||||
if named and width >= 110:
|
||||
row.append("" if station.object_of
|
||||
else who_text(licensee(self.net, station.call)))
|
||||
if width >= 96:
|
||||
row.append(station.symbol or station.kind)
|
||||
row.append(self._said(station))
|
||||
|
|
@ -1160,11 +1174,20 @@ class Ft8Display:
|
|||
def _table(self, here, now: float):
|
||||
from .ft8 import grid_away
|
||||
|
||||
from .ft8 import licensee, who_text
|
||||
|
||||
here = sorted(here, key=lambda s: (-s.last, s.call))
|
||||
band = getattr(self.heard, "band", None)
|
||||
named = band is not None and getattr(band, "register", None) is not None
|
||||
table = Table(box=None, header_style="bold", pad_edge=False,
|
||||
title=f"heard so far — {len(here)} stations",
|
||||
title_justify="left", title_style="bold")
|
||||
table.add_column("station")
|
||||
# Wide terminals only. What somebody watching a band needs is who
|
||||
# is transmitting now; the names are all in the report afterwards.
|
||||
if named and self.console.size.width >= 118:
|
||||
table.add_column("licensed to", width=24, style="grey62",
|
||||
no_wrap=True)
|
||||
table.add_column("grid")
|
||||
if self.grid:
|
||||
table.add_column("away", justify="right")
|
||||
|
|
@ -1173,7 +1196,10 @@ class Ft8Display:
|
|||
table.add_column("hz", justify="right")
|
||||
table.add_column("last", justify="right")
|
||||
for s in here[:20]:
|
||||
row = [s.call, s.grid or "—"]
|
||||
row = [s.call]
|
||||
if named and self.console.size.width >= 118:
|
||||
row.append(who_text(licensee(band, s.call)))
|
||||
row.append(s.grid or "—")
|
||||
if self.grid:
|
||||
away = grid_away(self.grid, s.grid) if s.grid else None
|
||||
if away is None:
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
.\" Generated by packaging/make-man.py -- do not edit by hand.
|
||||
.TH BANDSAUNTER 1 "2026-09-21" "bandsaunter 2026-09-21_04" "User Commands"
|
||||
.TH BANDSAUNTER 1 "2026-09-24" "bandsaunter 2026-09-24_01" "User Commands"
|
||||
.SH NAME
|
||||
bandsaunter \- scan, record and identify radio signals with an RTL-SDR
|
||||
.SH SYNOPSIS
|
||||
|
|
@ -1566,6 +1566,17 @@ and never fetched twice, every request identifies this program in its
|
|||
User-Agent, and the attribution the tiles require is written onto the picture
|
||||
\[em] a GIF travels without the readme that would otherwise carry it.
|
||||
.PP
|
||||
The finished map is cached as well, in
|
||||
.IR ~/.cache/bandsaunter/ground .
|
||||
The tiles always were, so a second evening on the same view has never touched
|
||||
the network, but it still cost decoding forty PNGs and resampling a megapixel
|
||||
and a half into this program's own projection every time a window opened, for
|
||||
an answer that cannot have changed. On a hundred-and-fifty-mile view that is
|
||||
0.61 seconds become 0.01. Both windows and both kinds of still picture share
|
||||
it. A map with squares missing is not kept, since caching a hole would keep it
|
||||
for a month. The whole cache is pruned to four hundred megabytes whenever a
|
||||
map is written, least recently used first.
|
||||
.PP
|
||||
The zoom is chosen from how wide the picture is, not from the area alone, so a
|
||||
map asked for at 1920 pixels fetches finer tiles than the same map asked for
|
||||
at 960. Half again over the width is fetched deliberately and averaged down,
|
||||
|
|
@ -1579,6 +1590,29 @@ the window wants. A drawing is capped at a couple of hundred tiles, which at
|
|||
3840 by 2160 is reached: there the zoom has stopped climbing and the map is
|
||||
enlarged after all, and a smaller radius buys the detail back.
|
||||
.PP
|
||||
The window opens maximised \[em] this is a map, and the thing anybody wants
|
||||
more of is map. Un-maximising gives back a usable window, the restored size
|
||||
being set before it maximises rather than left to the toolkit to guess.
|
||||
.B f
|
||||
goes to true full screen and back to maximised, 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 full screen by default, because the title bar
|
||||
is where the band and the frequency are written.
|
||||
.PP
|
||||
A window made bigger fetches a sharper map. The map underneath is fetched for
|
||||
the size of the window at the time, and a map of the right piece of world goes
|
||||
on being one however far it is then stretched, so nothing else notices. A
|
||||
window opened at its default size and taken to the whole screen used to keep
|
||||
the map it started with until an aircraft wandered far enough to move the view
|
||||
out of the fetched box. It now compares map pixels per degree in hand against
|
||||
what the view wants and asks for a better one when it is being blown up by more
|
||||
than fifteen per cent \[em] per degree rather than in raw pixels, because the
|
||||
fetched box is a quarter wider than the view, so a map with as many pixels as
|
||||
the window is wide has only four fifths of them on the screen. The request is
|
||||
keyed on the window's size, so once answered nothing more is asked, which is
|
||||
what stops a window larger than the tile budget can cover from asking all
|
||||
evening.
|
||||
.PP
|
||||
Resizing the window is the demanding case: a wider picture picks a sharper
|
||||
zoom and a hundred tiles that have never been on this disk are asked for at
|
||||
once, whereupon a busy server refuses some of them. A tile that does not
|
||||
|
|
@ -2730,7 +2764,9 @@ its brightness,
|
|||
.B +
|
||||
and
|
||||
.B \-
|
||||
the range, and
|
||||
the range,
|
||||
.B f
|
||||
true full screen, and
|
||||
.B q
|
||||
to quit.
|
||||
.PP
|
||||
|
|
@ -2789,6 +2825,27 @@ is longer than the aerial most dongles ship with.
|
|||
.B \-\-packets
|
||||
shows each frame as it arrives, which is what to watch while moving an aerial
|
||||
about.
|
||||
.SS Who each station is
|
||||
An APRS callsign is issued by a government, so unlike a weather sensor it can
|
||||
be looked up: the name on the licence, the town, and the licensed position,
|
||||
which is a street address where a beacon only gives a grid square. The SSID
|
||||
comes off first \[em] W1AW\-9 is the ninth radio W1AW runs, and no register
|
||||
has heard of it \[em] and objects are not looked up at all, an object being a
|
||||
marker placed on behalf of something with no licence of its own.
|
||||
.PP
|
||||
Nothing waits: the lookup runs on its own thread and the name appears in a
|
||||
later frame, because a table that stopped for a network request would stop for
|
||||
every new station on a busy channel. A station the register cannot know still
|
||||
says where it is from, the country coming out of the callsign's own structure
|
||||
with no network at all.
|
||||
.PP
|
||||
Answers are kept in
|
||||
.I ~/.cache/bandsaunter/callsigns.json
|
||||
for a month, and that file is shared with every other part of this program
|
||||
that resolves a callsign, so the same net logged night after night is asked
|
||||
about once.
|
||||
.B \-\-no\-lookup
|
||||
turns the network off and leaves the country and district, which cost nothing.
|
||||
.SH APRS OPTIONS
|
||||
Every option the APRS side takes, in the four groups the menu shows them in.
|
||||
Each is a flag here and a line in the menu, and both come from one table in
|
||||
|
|
@ -2870,6 +2927,11 @@ Setting name \fBlocation\fR, default \fBblank\fR.
|
|||
.PP
|
||||
.SS Showing
|
||||
.TP
|
||||
.B --lookup / --no-lookup
|
||||
Look up callsigns \[em] find out who each station is licensed to, and where.
|
||||
.br
|
||||
Setting name \fBlookup\fR, default \fByes\fR.
|
||||
.TP
|
||||
.B --units
|
||||
Show readings in \[em] metric or imperial, for the display and the export.
|
||||
.br
|
||||
|
|
@ -2996,6 +3058,23 @@ writes the log again in the form every amateur logging program imports,
|
|||
marked as heard rather than worked. Nothing here transmits, so nothing here is
|
||||
a contact, and an ADIF that let a logging program treat these as worked would
|
||||
put claims into somebody's log that they cannot make.
|
||||
.SS Who each station is
|
||||
Every FT8 exchange is two callsigns and a callsign is issued by a government,
|
||||
so both are looked up \[em] the station being answered may never transmit
|
||||
within earshot and is still one this receiver knows about. The licensed
|
||||
callsign is found inside the heard one: ET3RFG/R is ET3RFG operating away from
|
||||
home, DL/G4ABC is G4ABC as a guest, and a hashed <...> is not asked about
|
||||
because there is nothing to ask. Those rules are shared with APRS rather than
|
||||
written twice, getting them wrong being silent: a register asked about W1AW\-9
|
||||
returns nothing, which looks exactly like a station that is not licensed.
|
||||
.PP
|
||||
Nothing waits on the network \[em] a slot has to be decoded in well under
|
||||
fifteen seconds or the next one is missed \[em] and answers are kept in
|
||||
.I ~/.cache/bandsaunter/callsigns.json
|
||||
for a month, in the same file every other part of this program uses. The
|
||||
databases are United States registers, so the DX that makes this mode worth
|
||||
listening to comes back unlisted, and the country beside it comes out of the
|
||||
callsign's own structure with no network at all.
|
||||
.SS How well it works
|
||||
Checked against eleven off-air recordings with published decodes, which is the
|
||||
only honest way to test a decoder: an encoder tested against its own decoder
|
||||
|
|
@ -3119,6 +3198,11 @@ Aerial at \[em] your own grid square, so distances can be worked out.
|
|||
.br
|
||||
Setting name \fBgrid\fR, default \fBnot set, so no distances\fR.
|
||||
.TP
|
||||
.B --lookup / --no-lookup
|
||||
Look up callsigns \[em] find out who each station is licensed to, and where.
|
||||
.br
|
||||
Setting name \fBlookup\fR, default \fByes\fR.
|
||||
.TP
|
||||
.B --units
|
||||
Show readings in \[em] metric or imperial, for the display and the export.
|
||||
.br
|
||||
|
|
@ -3148,6 +3232,30 @@ Also write an ADIF \[em] the log again, in the form logging programs read.
|
|||
.br
|
||||
Setting name \fBadif\fR, default \fBno\fR.
|
||||
.PP
|
||||
.SH THE TITLE SCREEN
|
||||
Drawn on startup in braille, two dots wide and four tall to a character, which
|
||||
is eight times the detail a block gives and is what makes room for capitals and
|
||||
lowercase at the same height \[em] a five-row block font has no second height
|
||||
to spend, so the name comes out shouted. Coloured in a gradient from deep blue
|
||||
through cyan to a cool white across the width \[em] deliberately not the
|
||||
waterfall ramp the rest of the program draws in, which carries on through green
|
||||
and yellow to red because it stands in for a spectrum and has to mean
|
||||
something. Under it, who conceived the program and what wrote it.
|
||||
.PP
|
||||
The font is twelve letters cut by hand at cap height seven and then doubled,
|
||||
because a stroke two dots thick reads as a line where one dot thick reads as a
|
||||
dotted line.
|
||||
.PP
|
||||
It never appears where it would be in the way. 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 at all. It is
|
||||
drawn after the arguments are parsed, so
|
||||
.B \-\-help
|
||||
and a bad argument say their piece without one over the top.
|
||||
.B \-\-no\-splash
|
||||
turns it off on a terminal too, and
|
||||
.B BANDSAUNTER_NO_SPLASH=1
|
||||
turns it off for good.
|
||||
.SH FILES
|
||||
.TP
|
||||
.I ~/.config/bandsaunter/config.yaml
|
||||
|
|
@ -3290,6 +3398,8 @@ under the MIT terms and that file carries the attribution they ask for. They
|
|||
are there because they cannot be derived: everything else about FT8 here is
|
||||
worked out from first principles, but those two tables are the code itself,
|
||||
chosen once by its designers and published. No decoding logic was taken.
|
||||
.SH HOMEPAGE
|
||||
.I https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
.SH BUGS
|
||||
The DVB-T television driver claims these dongles on sight. If the receiver
|
||||
cannot be opened, that is almost always why: the package blacklists the
|
||||
|
|
|
|||
|
|
@ -78,7 +78,8 @@ Depends: python3 (>= 3.10), python3-numpy, python3-scipy, python3-rich,
|
|||
python3-yaml, librtlsdr0
|
||||
Recommends: bandsaunter-transcribe, espeak-ng
|
||||
Suggests: rtl-sdr, python3-pyqt6, ffmpeg
|
||||
Maintainer: bandsaunter
|
||||
Maintainer: The Dust Council
|
||||
Homepage: https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
Installed-Size: $(du -ks "$pkgdir" | cut -f1)
|
||||
Description: signal scanner and recorder for RTL-SDR receivers
|
||||
Sweeps any set of frequency ranges, or presets from a built-in US band plan,
|
||||
|
|
|
|||
|
|
@ -77,7 +77,8 @@ Priority: optional
|
|||
Architecture: ${arch}
|
||||
Depends: bandsaunter (= ${version}-${revision}), python3-numpy, python3-yaml
|
||||
Recommends: bandsaunter-model-$(echo "$model" | tr '._' '--')
|
||||
Maintainer: bandsaunter
|
||||
Maintainer: The Dust Council
|
||||
Homepage: https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
Installed-Size: $(du -ks "$pkg" | cut -f1)
|
||||
Description: speech recogniser for bandsaunter
|
||||
Transcribes recorded voice transmissions to text.
|
||||
|
|
@ -131,7 +132,8 @@ Section: hamradio
|
|||
Priority: optional
|
||||
Architecture: all
|
||||
Depends: bandsaunter-transcribe
|
||||
Maintainer: bandsaunter
|
||||
Maintainer: The Dust Council
|
||||
Homepage: https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
Installed-Size: $(du -ks "$modelpkg" | cut -f1)
|
||||
Description: $model speech model for bandsaunter
|
||||
The $model recognition model, installed locally so that transcription works
|
||||
|
|
|
|||
|
|
@ -133,6 +133,12 @@ on it again. The frequency is written into your saved settings, the same list
|
|||
maintains, and takes effect on the next scan \[em] a scan already running read
|
||||
its settings when it started.
|
||||
.TP
|
||||
.B c
|
||||
Open the register: every callsign and every aircraft this installation has
|
||||
ever looked up, read back out of the two caches. See
|
||||
.B THE REGISTER
|
||||
below.
|
||||
.TP
|
||||
.B "? h"
|
||||
The list of keys, and which audio player was found.
|
||||
.TP
|
||||
|
|
@ -270,6 +276,61 @@ is written into the map: holding it and not saying so would be worse than
|
|||
either showing it or not asking for it.
|
||||
.B \-\-no\-lookup
|
||||
asks for none of it.
|
||||
.SH THE REGISTER
|
||||
.B c
|
||||
opens it. Everything this installation has ever found out about a callsign or
|
||||
an aircraft, read back out of the two caches the lookups write: the scanner's
|
||||
identification, the Morse idents, APRS, FT8 and this browser all resolve
|
||||
callsigns into one file, and the aircraft side keeps its own. Between them
|
||||
they are a record of who and what has been heard from this aerial, and until
|
||||
now the only way to read either was to open the JSON.
|
||||
.PP
|
||||
The list shows the callsign or registration, who or what it is, where, when it
|
||||
was looked up, and whether there is anywhere to point a map at. Under it,
|
||||
everything known about whichever one is highlighted, in two columns \[em] a
|
||||
licence has a dozen fields and a screen is wider than it is tall.
|
||||
.TP
|
||||
.B "\[ua] \[da]"
|
||||
Move. Page Up and Page Down go a screen at a time, Home and End to the ends.
|
||||
.TP
|
||||
.B tab
|
||||
Switch between callsigns and aircraft.
|
||||
.TP
|
||||
.B /
|
||||
Search. Every field rather than the name, because the interesting question is
|
||||
usually not "which callsign" but "who was in Arizona" or "what Bombardiers
|
||||
have gone over", and both of those live in the detail. Every word has to
|
||||
match, so a search can be narrowed.
|
||||
.TP
|
||||
.B g
|
||||
Open where this one is, in whatever browser the desktop uses. Only the
|
||||
coordinates go into the link: a map does not need to be told whose licence it
|
||||
is looking at in order to show a place, and the link is the one part of this
|
||||
that leaves the machine. Where nothing is known about the position it says so
|
||||
rather than guessing, and on a machine with no browser \[em] which is the
|
||||
normal case for a receiver \[em] it prints the coordinates instead.
|
||||
.TP
|
||||
.B r
|
||||
Read the caches again, for somebody who has just finished a scan in another
|
||||
window.
|
||||
.TP
|
||||
.B "c esc"
|
||||
Back to the recordings.
|
||||
.B q
|
||||
still quits.
|
||||
.PP
|
||||
Callsigns that no register could place are kept rather than dropped. "Asked
|
||||
about, and in no register reachable from here" is a fact about a station, and a
|
||||
list that quietly dropped them would make an evening of unlisted foreign
|
||||
stations look like an evening when nothing was looked up. An aircraft is put
|
||||
on the map at the airport its flight started from, labelled as such: this is a
|
||||
register of airframes rather than a position report, and the origin is the
|
||||
nearest true thing.
|
||||
.PP
|
||||
The addresses are licence records, public by law and already printed by
|
||||
.BR bandsaunter (1)
|
||||
in its own reports; this shows them the same way rather than more
|
||||
prominently.
|
||||
.SH THE MAP
|
||||
A licence says where its holder is, so a list of callsigns is also a map. The
|
||||
scanner writes one as it runs and
|
||||
|
|
@ -410,6 +471,30 @@ during the scan, and the
|
|||
.I _transcription.txt
|
||||
beside the recording is what a later re\-run wrote. The file wins, being the
|
||||
more recent of the two.
|
||||
.SH THE TITLE SCREEN
|
||||
Drawn on startup in braille, two dots wide and four tall to a character, which
|
||||
is eight times the detail a block gives and is what makes room for capitals and
|
||||
lowercase at the same height \[em] a five-row block font has no second height
|
||||
to spend, so the name comes out shouted. Coloured in a gradient from deep blue
|
||||
through cyan to a cool white across the width \[em] deliberately not the
|
||||
waterfall ramp the rest of the program draws in, which carries on through green
|
||||
and yellow to red because it stands in for a spectrum and has to mean
|
||||
something. Under it, who conceived the program and what wrote it.
|
||||
.PP
|
||||
The font is twelve letters cut by hand at cap height seven and then doubled,
|
||||
because a stroke two dots thick reads as a line where one dot thick reads as a
|
||||
dotted line.
|
||||
.PP
|
||||
It never appears where it would be in the way. 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 at all. It is
|
||||
drawn after the arguments are parsed, so
|
||||
.B \-\-help
|
||||
and a bad argument say their piece without one over the top.
|
||||
.B \-\-no\-splash
|
||||
turns it off on a terminal too, and
|
||||
.B BANDSAUNTER_NO_SPLASH=1
|
||||
turns it off for good.
|
||||
.SH FILES
|
||||
.TP
|
||||
.I ~/bandsaunter/
|
||||
|
|
@ -493,6 +578,8 @@ or
|
|||
.UR https://www.gnu.org/licenses/
|
||||
.UE .
|
||||
There is no warranty, to the extent permitted by law.
|
||||
.SH HOMEPAGE
|
||||
.I https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
.SH BUGS
|
||||
The list is read when the browser opens. Press
|
||||
.B r
|
||||
|
|
|
|||
|
|
@ -1024,6 +1024,17 @@ and never fetched twice, every request identifies this program in its
|
|||
User-Agent, and the attribution the tiles require is written onto the picture
|
||||
\[em] a GIF travels without the readme that would otherwise carry it.
|
||||
.PP
|
||||
The finished map is cached as well, in
|
||||
.IR ~/.cache/bandsaunter/ground .
|
||||
The tiles always were, so a second evening on the same view has never touched
|
||||
the network, but it still cost decoding forty PNGs and resampling a megapixel
|
||||
and a half into this program's own projection every time a window opened, for
|
||||
an answer that cannot have changed. On a hundred-and-fifty-mile view that is
|
||||
0.61 seconds become 0.01. Both windows and both kinds of still picture share
|
||||
it. A map with squares missing is not kept, since caching a hole would keep it
|
||||
for a month. The whole cache is pruned to four hundred megabytes whenever a
|
||||
map is written, least recently used first.
|
||||
.PP
|
||||
The zoom is chosen from how wide the picture is, not from the area alone, so a
|
||||
map asked for at 1920 pixels fetches finer tiles than the same map asked for
|
||||
at 960. Half again over the width is fetched deliberately and averaged down,
|
||||
|
|
@ -1037,6 +1048,29 @@ the window wants. A drawing is capped at a couple of hundred tiles, which at
|
|||
3840 by 2160 is reached: there the zoom has stopped climbing and the map is
|
||||
enlarged after all, and a smaller radius buys the detail back.
|
||||
.PP
|
||||
The window opens maximised \[em] this is a map, and the thing anybody wants
|
||||
more of is map. Un-maximising gives back a usable window, the restored size
|
||||
being set before it maximises rather than left to the toolkit to guess.
|
||||
.B f
|
||||
goes to true full screen and back to maximised, 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 full screen by default, because the title bar
|
||||
is where the band and the frequency are written.
|
||||
.PP
|
||||
A window made bigger fetches a sharper map. The map underneath is fetched for
|
||||
the size of the window at the time, and a map of the right piece of world goes
|
||||
on being one however far it is then stretched, so nothing else notices. A
|
||||
window opened at its default size and taken to the whole screen used to keep
|
||||
the map it started with until an aircraft wandered far enough to move the view
|
||||
out of the fetched box. It now compares map pixels per degree in hand against
|
||||
what the view wants and asks for a better one when it is being blown up by more
|
||||
than fifteen per cent \[em] per degree rather than in raw pixels, because the
|
||||
fetched box is a quarter wider than the view, so a map with as many pixels as
|
||||
the window is wide has only four fifths of them on the screen. The request is
|
||||
keyed on the window's size, so once answered nothing more is asked, which is
|
||||
what stops a window larger than the tile budget can cover from asking all
|
||||
evening.
|
||||
.PP
|
||||
Resizing the window is the demanding case: a wider picture picks a sharper
|
||||
zoom and a hundred tiles that have never been on this disk are asked for at
|
||||
once, whereupon a busy server refuses some of them. A tile that does not
|
||||
|
|
@ -1735,7 +1769,9 @@ its brightness,
|
|||
.B +
|
||||
and
|
||||
.B \-
|
||||
the range, and
|
||||
the range,
|
||||
.B f
|
||||
true full screen, and
|
||||
.B q
|
||||
to quit.
|
||||
.PP
|
||||
|
|
@ -1794,6 +1830,27 @@ is longer than the aerial most dongles ship with.
|
|||
.B \-\-packets
|
||||
shows each frame as it arrives, which is what to watch while moving an aerial
|
||||
about.
|
||||
.SS Who each station is
|
||||
An APRS callsign is issued by a government, so unlike a weather sensor it can
|
||||
be looked up: the name on the licence, the town, and the licensed position,
|
||||
which is a street address where a beacon only gives a grid square. The SSID
|
||||
comes off first \[em] W1AW\-9 is the ninth radio W1AW runs, and no register
|
||||
has heard of it \[em] and objects are not looked up at all, an object being a
|
||||
marker placed on behalf of something with no licence of its own.
|
||||
.PP
|
||||
Nothing waits: the lookup runs on its own thread and the name appears in a
|
||||
later frame, because a table that stopped for a network request would stop for
|
||||
every new station on a busy channel. A station the register cannot know still
|
||||
says where it is from, the country coming out of the callsign's own structure
|
||||
with no network at all.
|
||||
.PP
|
||||
Answers are kept in
|
||||
.I ~/.cache/bandsaunter/callsigns.json
|
||||
for a month, and that file is shared with every other part of this program
|
||||
that resolves a callsign, so the same net logged night after night is asked
|
||||
about once.
|
||||
.B \-\-no\-lookup
|
||||
turns the network off and leaves the country and district, which cost nothing.
|
||||
.SH APRS OPTIONS
|
||||
Every option the APRS side takes, in the four groups the menu shows them in.
|
||||
Each is a flag here and a line in the menu, and both come from one table in
|
||||
|
|
@ -1837,6 +1894,23 @@ writes the log again in the form every amateur logging program imports,
|
|||
marked as heard rather than worked. Nothing here transmits, so nothing here is
|
||||
a contact, and an ADIF that let a logging program treat these as worked would
|
||||
put claims into somebody's log that they cannot make.
|
||||
.SS Who each station is
|
||||
Every FT8 exchange is two callsigns and a callsign is issued by a government,
|
||||
so both are looked up \[em] the station being answered may never transmit
|
||||
within earshot and is still one this receiver knows about. The licensed
|
||||
callsign is found inside the heard one: ET3RFG/R is ET3RFG operating away from
|
||||
home, DL/G4ABC is G4ABC as a guest, and a hashed <...> is not asked about
|
||||
because there is nothing to ask. Those rules are shared with APRS rather than
|
||||
written twice, getting them wrong being silent: a register asked about W1AW\-9
|
||||
returns nothing, which looks exactly like a station that is not licensed.
|
||||
.PP
|
||||
Nothing waits on the network \[em] a slot has to be decoded in well under
|
||||
fifteen seconds or the next one is missed \[em] and answers are kept in
|
||||
.I ~/.cache/bandsaunter/callsigns.json
|
||||
for a month, in the same file every other part of this program uses. The
|
||||
databases are United States registers, so the DX that makes this mode worth
|
||||
listening to comes back unlisted, and the country beside it comes out of the
|
||||
callsign's own structure with no network at all.
|
||||
.SS How well it works
|
||||
Checked against eleven off-air recordings with published decodes, which is the
|
||||
only honest way to test a decoder: an encoder tested against its own decoder
|
||||
|
|
@ -1851,6 +1925,30 @@ Every option the FT8 side takes, in the five groups the menu shows them in.
|
|||
Each is a flag here and a line in the menu, and both come from one table in
|
||||
the program, so they cannot disagree.
|
||||
.FT8_OPTIONS_HERE
|
||||
.SH THE TITLE SCREEN
|
||||
Drawn on startup in braille, two dots wide and four tall to a character, which
|
||||
is eight times the detail a block gives and is what makes room for capitals and
|
||||
lowercase at the same height \[em] a five-row block font has no second height
|
||||
to spend, so the name comes out shouted. Coloured in a gradient from deep blue
|
||||
through cyan to a cool white across the width \[em] deliberately not the
|
||||
waterfall ramp the rest of the program draws in, which carries on through green
|
||||
and yellow to red because it stands in for a spectrum and has to mean
|
||||
something. Under it, who conceived the program and what wrote it.
|
||||
.PP
|
||||
The font is twelve letters cut by hand at cap height seven and then doubled,
|
||||
because a stroke two dots thick reads as a line where one dot thick reads as a
|
||||
dotted line.
|
||||
.PP
|
||||
It never appears where it would be in the way. 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 at all. It is
|
||||
drawn after the arguments are parsed, so
|
||||
.B \-\-help
|
||||
and a bad argument say their piece without one over the top.
|
||||
.B \-\-no\-splash
|
||||
turns it off on a terminal too, and
|
||||
.B BANDSAUNTER_NO_SPLASH=1
|
||||
turns it off for good.
|
||||
.SH FILES
|
||||
.TP
|
||||
.I ~/.config/bandsaunter/config.yaml
|
||||
|
|
@ -1993,6 +2091,8 @@ under the MIT terms and that file carries the attribution they ask for. They
|
|||
are there because they cannot be derived: everything else about FT8 here is
|
||||
worked out from first principles, but those two tables are the code itself,
|
||||
chosen once by its designers and published. No decoding logic was taken.
|
||||
.SH HOMEPAGE
|
||||
.I https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
.SH BUGS
|
||||
The DVB-T television driver claims these dongles on sight. If the receiver
|
||||
cannot be opened, that is almost always why: the package blacklists the
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
.\" Generated by packaging/make-browse-man.py -- do not edit by hand.
|
||||
.TH SAUNTERBROWSE 1 "2026-09-04" "bandsaunter 2026-09-04_08" "User Commands"
|
||||
.TH SAUNTERBROWSE 1 "2026-09-24" "bandsaunter 2026-09-24_01" "User Commands"
|
||||
.SH NAME
|
||||
saunterbrowse \- read and listen to what a bandsaunter scan collected
|
||||
.SH SYNOPSIS
|
||||
|
|
@ -107,6 +107,12 @@ on it again. The frequency is written into your saved settings, the same list
|
|||
maintains, and takes effect on the next scan \[em] a scan already running read
|
||||
its settings when it started.
|
||||
.TP
|
||||
.B c
|
||||
Open the register: every callsign and every aircraft this installation has
|
||||
ever looked up, read back out of the two caches. See
|
||||
.B THE REGISTER
|
||||
below.
|
||||
.TP
|
||||
.B "? h"
|
||||
The list of keys, and which audio player was found.
|
||||
.TP
|
||||
|
|
@ -244,6 +250,61 @@ is written into the map: holding it and not saying so would be worse than
|
|||
either showing it or not asking for it.
|
||||
.B \-\-no\-lookup
|
||||
asks for none of it.
|
||||
.SH THE REGISTER
|
||||
.B c
|
||||
opens it. Everything this installation has ever found out about a callsign or
|
||||
an aircraft, read back out of the two caches the lookups write: the scanner's
|
||||
identification, the Morse idents, APRS, FT8 and this browser all resolve
|
||||
callsigns into one file, and the aircraft side keeps its own. Between them
|
||||
they are a record of who and what has been heard from this aerial, and until
|
||||
now the only way to read either was to open the JSON.
|
||||
.PP
|
||||
The list shows the callsign or registration, who or what it is, where, when it
|
||||
was looked up, and whether there is anywhere to point a map at. Under it,
|
||||
everything known about whichever one is highlighted, in two columns \[em] a
|
||||
licence has a dozen fields and a screen is wider than it is tall.
|
||||
.TP
|
||||
.B "\[ua] \[da]"
|
||||
Move. Page Up and Page Down go a screen at a time, Home and End to the ends.
|
||||
.TP
|
||||
.B tab
|
||||
Switch between callsigns and aircraft.
|
||||
.TP
|
||||
.B /
|
||||
Search. Every field rather than the name, because the interesting question is
|
||||
usually not "which callsign" but "who was in Arizona" or "what Bombardiers
|
||||
have gone over", and both of those live in the detail. Every word has to
|
||||
match, so a search can be narrowed.
|
||||
.TP
|
||||
.B g
|
||||
Open where this one is, in whatever browser the desktop uses. Only the
|
||||
coordinates go into the link: a map does not need to be told whose licence it
|
||||
is looking at in order to show a place, and the link is the one part of this
|
||||
that leaves the machine. Where nothing is known about the position it says so
|
||||
rather than guessing, and on a machine with no browser \[em] which is the
|
||||
normal case for a receiver \[em] it prints the coordinates instead.
|
||||
.TP
|
||||
.B r
|
||||
Read the caches again, for somebody who has just finished a scan in another
|
||||
window.
|
||||
.TP
|
||||
.B "c esc"
|
||||
Back to the recordings.
|
||||
.B q
|
||||
still quits.
|
||||
.PP
|
||||
Callsigns that no register could place are kept rather than dropped. "Asked
|
||||
about, and in no register reachable from here" is a fact about a station, and a
|
||||
list that quietly dropped them would make an evening of unlisted foreign
|
||||
stations look like an evening when nothing was looked up. An aircraft is put
|
||||
on the map at the airport its flight started from, labelled as such: this is a
|
||||
register of airframes rather than a position report, and the origin is the
|
||||
nearest true thing.
|
||||
.PP
|
||||
The addresses are licence records, public by law and already printed by
|
||||
.BR bandsaunter (1)
|
||||
in its own reports; this shows them the same way rather than more
|
||||
prominently.
|
||||
.SH THE MAP
|
||||
A licence says where its holder is, so a list of callsigns is also a map. The
|
||||
scanner writes one as it runs and
|
||||
|
|
@ -398,6 +459,30 @@ during the scan, and the
|
|||
.I _transcription.txt
|
||||
beside the recording is what a later re\-run wrote. The file wins, being the
|
||||
more recent of the two.
|
||||
.SH THE TITLE SCREEN
|
||||
Drawn on startup in braille, two dots wide and four tall to a character, which
|
||||
is eight times the detail a block gives and is what makes room for capitals and
|
||||
lowercase at the same height \[em] a five-row block font has no second height
|
||||
to spend, so the name comes out shouted. Coloured in a gradient from deep blue
|
||||
through cyan to a cool white across the width \[em] deliberately not the
|
||||
waterfall ramp the rest of the program draws in, which carries on through green
|
||||
and yellow to red because it stands in for a spectrum and has to mean
|
||||
something. Under it, who conceived the program and what wrote it.
|
||||
.PP
|
||||
The font is twelve letters cut by hand at cap height seven and then doubled,
|
||||
because a stroke two dots thick reads as a line where one dot thick reads as a
|
||||
dotted line.
|
||||
.PP
|
||||
It never appears where it would be in the way. 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 at all. It is
|
||||
drawn after the arguments are parsed, so
|
||||
.B \-\-help
|
||||
and a bad argument say their piece without one over the top.
|
||||
.B \-\-no\-splash
|
||||
turns it off on a terminal too, and
|
||||
.B BANDSAUNTER_NO_SPLASH=1
|
||||
turns it off for good.
|
||||
.SH FILES
|
||||
.TP
|
||||
.I ~/bandsaunter/
|
||||
|
|
@ -481,6 +566,8 @@ or
|
|||
.UR https://www.gnu.org/licenses/
|
||||
.UE .
|
||||
There is no warranty, to the extent permitted by law.
|
||||
.SH HOMEPAGE
|
||||
.I https://frostwarning.com/git/dustcouncil/bandsaunter
|
||||
.SH BUGS
|
||||
The list is read when the browser opens. Press
|
||||
.B r
|
||||
|
|
|
|||
|
|
@ -21,6 +21,10 @@ dependencies = [
|
|||
"PyYAML>=5.4",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://frostwarning.com/git/dustcouncil/bandsaunter"
|
||||
Source = "https://frostwarning.com/git/dustcouncil/bandsaunter"
|
||||
|
||||
[project.optional-dependencies]
|
||||
# The realtime aircraft window. Optional on purpose: without it the passive
|
||||
# capture, the terminal board and the drawn maps all work unchanged.
|
||||
|
|
|
|||
|
|
@ -1222,3 +1222,194 @@ 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"
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ in through the same door the real ones come through, and the PNGs are built
|
|||
here from the specification rather than by the decoder they are testing.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import time
|
||||
import zlib
|
||||
|
|
@ -333,10 +334,14 @@ def test_a_missing_tile_is_a_gap_rather_than_the_brightest_thing_on_the_map():
|
|||
so a square that never arrived used to come out as the brightest thing
|
||||
on the picture: a glowing rectangle where the map should be."""
|
||||
zoom, hole = _hole_at()
|
||||
# remember=False throughout: these two are the same view with different
|
||||
# tiles under it, which cannot happen on the air and would otherwise be
|
||||
# answered from the first one's cache entry.
|
||||
whole, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()), pause=0,
|
||||
zoom=zoom)
|
||||
zoom=zoom, remember=False)
|
||||
holed, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy({hole}),
|
||||
pause=0, retry_pause=0, zoom=zoom)
|
||||
pause=0, retry_pause=0, zoom=zoom,
|
||||
remember=False)
|
||||
assert whole is not None and holed is not None
|
||||
gap = _hole_mask(hole, zoom)
|
||||
assert gap.sum() > 1000, "the hole is not where this test thinks it is"
|
||||
|
|
@ -358,9 +363,10 @@ def test_a_missing_tile_does_not_dim_the_rest_of_the_map():
|
|||
not there."""
|
||||
zoom, hole = _hole_at()
|
||||
whole, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()), pause=0,
|
||||
zoom=zoom)
|
||||
zoom=zoom, remember=False)
|
||||
holed, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy({hole}),
|
||||
pause=0, retry_pause=0, zoom=zoom)
|
||||
pause=0, retry_pause=0, zoom=zoom,
|
||||
remember=False)
|
||||
# Outside the gap and the averaged band along its edge, the map is the
|
||||
# map: the hole took nothing else with it.
|
||||
elsewhere = ~_hole_mask(hole, zoom, grow=2)
|
||||
|
|
@ -374,10 +380,10 @@ def test_a_map_with_squares_missing_says_it_is_not_the_whole_answer():
|
|||
again."""
|
||||
_zoom, hole = _hole_at()
|
||||
whole, settled = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()),
|
||||
pause=0)
|
||||
pause=0, remember=False)
|
||||
assert whole is not None and settled
|
||||
holed, settled = bm.ground_under(*BOX, 400, 400, fetch=_patchy({hole}),
|
||||
pause=0, retry_pause=0)
|
||||
pause=0, retry_pause=0, remember=False)
|
||||
assert holed is not None and not settled
|
||||
|
||||
|
||||
|
|
@ -394,9 +400,10 @@ def test_a_tile_that_fails_once_is_asked_for_again():
|
|||
return None
|
||||
return solid(40 if (x + y) % 3 == 0 else 230)
|
||||
|
||||
whole, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()), pause=0)
|
||||
whole, _ = bm.ground_under(*BOX, 400, 400, fetch=_patchy(()), pause=0,
|
||||
remember=False)
|
||||
healed, settled = bm.ground_under(*BOX, 400, 400, fetch=flaky, pause=0,
|
||||
retry_pause=0)
|
||||
retry_pause=0, remember=False)
|
||||
assert refused["left"] == 0, "the tile was never asked for a second time"
|
||||
assert settled, "a recovered map is the whole answer"
|
||||
assert bool((healed == whole).all())
|
||||
|
|
@ -878,3 +885,157 @@ def test_a_map_asked_for_at_more_detail_than_the_tiles_hold_still_works():
|
|||
fetch=gradient_tile, zoom=9, pause=0)
|
||||
assert levels.shape == (2000, 2000)
|
||||
assert levels[0].mean() != levels[-1].mean()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Keeping the finished map
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_a_map_already_built_is_not_built_again(monkeypatch):
|
||||
"""The tiles were always cached; the work done on them was not. Opening
|
||||
the same window twice used to decode forty PNGs and resample a
|
||||
megapixel and a half into this program's own projection, both times,
|
||||
for an answer that cannot have changed."""
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
asked = []
|
||||
|
||||
def counting(z, x, y, **kw):
|
||||
asked.append((z, x, y))
|
||||
return gradient_tile(z, x, y, **kw)
|
||||
|
||||
first, settled = bm.ground_under(*box, 300, 300, shades=32,
|
||||
fetch=counting, pause=0)
|
||||
assert settled and first is not None
|
||||
built = len(asked)
|
||||
assert built > 1
|
||||
|
||||
asked.clear()
|
||||
again, settled = bm.ground_under(*box, 300, 300, shades=32,
|
||||
fetch=counting, pause=0)
|
||||
assert settled
|
||||
assert asked == [], "it went back to the tiles for a map it already had"
|
||||
assert bool((again == first).all()), "the kept map is a different map"
|
||||
|
||||
|
||||
def test_a_map_with_squares_missing_is_not_kept():
|
||||
"""Caching a hole would keep it for a month, and the whole point of
|
||||
calling a partial map provisional is that it gets asked for again."""
|
||||
zoom, hole = _hole_at()
|
||||
holed, settled = bm.ground_under(*BOX, 400, 400, fetch=_patchy({hole}),
|
||||
pause=0, retry_pause=0, zoom=zoom)
|
||||
assert holed is not None and not settled
|
||||
assert list(bm.ground_cache_dir().glob("*.npz")) == []
|
||||
|
||||
|
||||
def test_a_different_picture_is_a_different_map():
|
||||
"""Same piece of world, bigger window: reusing the smaller one would be
|
||||
exactly the upscale this program went to some trouble to avoid."""
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
small, _ = bm.ground_under(*box, 200, 200, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
large, _ = bm.ground_under(*box, 400, 400, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
assert small.shape == (200, 200) and large.shape == (400, 400)
|
||||
elsewhere, _ = bm.ground_under(48.0, -123.0, 49.0, -122.0, 200, 200,
|
||||
shades=32, fetch=gradient_tile, pause=0)
|
||||
assert len(list(bm.ground_cache_dir().glob("*.npz"))) == 3
|
||||
|
||||
|
||||
def test_a_view_that_drifted_a_few_metres_is_the_same_view():
|
||||
"""Rounded to about a hundred metres, which is finer than a tile and
|
||||
far finer than anything visible: a map rebuilt because the middle
|
||||
moved by a pixel would defeat the point of keeping it."""
|
||||
a, _ = bm.ground_under(47.0, -123.0, 48.0, -122.0, 200, 200, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
asked = []
|
||||
|
||||
def counting(z, x, y, **kw):
|
||||
asked.append((z, x, y))
|
||||
return gradient_tile(z, x, y, **kw)
|
||||
|
||||
b, _ = bm.ground_under(47.00002, -123.00002, 48.00002, -121.99998,
|
||||
200, 200, shades=32, fetch=counting, pause=0)
|
||||
assert asked == []
|
||||
assert bool((a == b).all())
|
||||
|
||||
|
||||
def test_keeping_the_map_can_be_turned_off():
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
bm.ground_under(*box, 250, 250, shades=32, fetch=gradient_tile,
|
||||
pause=0, remember=False)
|
||||
assert list(bm.ground_cache_dir().glob("*.npz")) == []
|
||||
|
||||
|
||||
def test_a_truncated_cache_file_is_a_miss_rather_than_a_crash():
|
||||
"""Which is what a cache looks like after a power cut."""
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
bm.ground_under(*box, 220, 220, shades=32, fetch=gradient_tile, pause=0)
|
||||
kept = list(bm.ground_cache_dir().glob("*.npz"))
|
||||
assert len(kept) == 1
|
||||
kept[0].write_bytes(b"PK\x03\x04 truncated")
|
||||
levels, settled = bm.ground_under(*box, 220, 220, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
assert levels is not None and settled and levels.shape == (220, 220)
|
||||
|
||||
|
||||
def test_a_map_kept_too_long_ago_is_built_again(monkeypatch):
|
||||
box = (47.0, -123.0, 48.0, -122.0)
|
||||
bm.ground_under(*box, 210, 210, shades=32, fetch=gradient_tile, pause=0)
|
||||
later = time.time() + bm.GROUND_CACHE_DAYS * 86_400 + 1
|
||||
monkeypatch.setattr(bm.time, "time", lambda: later)
|
||||
asked = []
|
||||
|
||||
def counting(z, x, y, **kw):
|
||||
asked.append(1)
|
||||
return gradient_tile(z, x, y, **kw)
|
||||
|
||||
bm.ground_under(*box, 210, 210, shades=32, fetch=counting, pause=0)
|
||||
assert asked, "a month-old map was believed"
|
||||
|
||||
|
||||
def test_forgetting_the_maps_keeps_the_tiles():
|
||||
"""The maps are quick to rebuild from tiles and the tiles are not quick
|
||||
to fetch again, so the cheap thing goes first."""
|
||||
bm.ground_under(47.0, -123.0, 48.0, -122.0, 230, 230, shades=32,
|
||||
fetch=gradient_tile, pause=0)
|
||||
before = bm.cache_size()
|
||||
assert before["ground"]["files"] == 1
|
||||
assert bm.forget_ground() == 1
|
||||
after = bm.cache_size()
|
||||
assert after["ground"]["files"] == 0
|
||||
assert after["tiles"]["files"] == before["tiles"]["files"]
|
||||
|
||||
|
||||
def test_the_cache_says_how_big_it_is(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path))
|
||||
empty = bm.cache_size()
|
||||
assert empty["total"]["bytes"] == 0 and empty["total"]["files"] == 0
|
||||
root = tmp_path / "bandsaunter" / "tiles" / "9" / "81"
|
||||
root.mkdir(parents=True)
|
||||
(root / "178.png").write_bytes(b"x" * 1000)
|
||||
got = bm.cache_size()
|
||||
assert got["tiles"] == {"bytes": 1000, "files": 1}
|
||||
assert got["total"]["bytes"] == 1000
|
||||
|
||||
|
||||
def test_pruning_throws_away_the_least_recently_used(tmp_path, monkeypatch):
|
||||
"""Least recently *used*, not oldest: a tile fetched a year ago and
|
||||
looked at last night is the receiver's own neighbourhood, and throwing
|
||||
that away to keep last week's holiday is the wrong way round."""
|
||||
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path))
|
||||
where = tmp_path / "bandsaunter" / "tiles" / "9" / "81"
|
||||
where.mkdir(parents=True)
|
||||
now = time.time()
|
||||
for i, age in enumerate((100.0, 0.0, 50.0)): # middle one is freshest
|
||||
path = where / f"{i}.png"
|
||||
path.write_bytes(b"x" * 400_000)
|
||||
os.utime(path, (now - age * 86_400, now - age * 86_400))
|
||||
assert bm.cache_size()["tiles"]["files"] == 3
|
||||
gone = bm.prune_cache(limit_mb=0.5)
|
||||
assert gone == 2
|
||||
left = list(where.glob("*.png"))
|
||||
assert [p.name for p in left] == ["1.png"], "it kept the wrong one"
|
||||
|
||||
|
||||
def test_pruning_a_cache_that_already_fits_does_nothing():
|
||||
assert bm.prune_cache(limit_mb=10_000) == 0
|
||||
|
|
|
|||
|
|
@ -837,3 +837,235 @@ def test_nothing_claims_to_be_listening_before_there_is_a_receiver(tmp_path):
|
|||
shown = caught.get()
|
||||
assert "cannot open the receiver" in shown
|
||||
assert "listening on" not in shown
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Who each station is
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _register(tmp_path, entries=()):
|
||||
"""A licence register that knows what it is told and asks nobody."""
|
||||
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
|
||||
|
||||
|
||||
def _heard_from(band, text, calls, grid="", at=1_700_000_000.0):
|
||||
band.add(ft8wave.Decode(text=text, kind="standard", calls=calls,
|
||||
grid=grid, hertz=1200.0, offset=0.2,
|
||||
snr_db=-7.0, calling=text.startswith("CQ"),
|
||||
at=at))
|
||||
|
||||
|
||||
def test_both_callsigns_in_an_exchange_are_looked_up(tmp_path):
|
||||
"""The station being answered may never transmit within earshot, and is
|
||||
still a station this receiver knows about."""
|
||||
register = _register(tmp_path)
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
_heard_from(band, "W1AW KU0W DM42", ("W1AW", "KU0W"), "DM42")
|
||||
assert set(register._entries) == {"W1AW", "KU0W"}
|
||||
|
||||
|
||||
def test_a_station_is_asked_about_once_however_often_it_transmits(tmp_path):
|
||||
register = _register(tmp_path)
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
for i in range(6):
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31",
|
||||
at=1_700_000_000.0 + i * 15)
|
||||
assert set(register._entries) == {"W1AW"}
|
||||
|
||||
|
||||
def test_a_callsign_nobody_has_spelled_out_is_not_asked_about(tmp_path):
|
||||
"""FT8 carries a compound callsign as a hash and expects the receiver to
|
||||
have heard it in full earlier. Until it has, there is nothing to ask."""
|
||||
register = _register(tmp_path)
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
_heard_from(band, "<...> ON7EE JO10", ("<...>", "ON7EE"), "JO10")
|
||||
assert set(register._entries) == {"ON7EE"}
|
||||
|
||||
|
||||
def test_a_rover_is_looked_up_under_its_licence(tmp_path):
|
||||
"""ET3RFG/R is ET3RFG operating away from the licensed address, and no
|
||||
register has heard of the suffix."""
|
||||
register = _register(tmp_path)
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
_heard_from(band, "ET3RFG/R IN3ADG -23", ("ET3RFG/R", "IN3ADG"))
|
||||
assert set(register._entries) == {"ET3RFG", "IN3ADG"}
|
||||
|
||||
|
||||
def test_the_name_is_shown_when_it_has_arrived(tmp_path):
|
||||
register = _register(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
||||
"Newington, CT")])
|
||||
band = ft8.Band()
|
||||
band.register = register
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31")
|
||||
assert ft8.who_text(ft8.licensee(band, "W1AW")) == \
|
||||
"ARRL HQ Operators Club — Newington, CT"
|
||||
|
||||
|
||||
def test_the_dx_the_register_cannot_know_still_says_which_country():
|
||||
"""Which on this band is the point: the databases are United States
|
||||
registers and the interesting stations are all somewhere else."""
|
||||
from bandsaunter.callsign import Callsign
|
||||
|
||||
who = Callsign(call="VK4BLE", country="Australia", status="unlisted")
|
||||
assert ft8.who_text(who) == "Australia"
|
||||
|
||||
|
||||
def test_nothing_is_looked_up_without_a_register():
|
||||
band = ft8.Band()
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31")
|
||||
assert ft8.licensee(band, "W1AW") is None
|
||||
assert ft8.open_register(ft8.Ft8Options(lookup=False)).online is False
|
||||
|
||||
|
||||
def test_the_report_gives_a_column_for_who_each_station_is(tmp_path):
|
||||
from rich.console import Console
|
||||
|
||||
band = ft8.Band()
|
||||
band.register = _register(tmp_path, [("W1AW", "ARRL HQ Operators Club",
|
||||
"Newington, CT")])
|
||||
band.slots = 2
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31")
|
||||
console = Console(width=150, force_terminal=False)
|
||||
with console.capture() as caught:
|
||||
ft8.report(console, band, ft8.Ft8Options(lookup=True))
|
||||
shown = caught.get()
|
||||
assert "licensed to" in shown and "ARRL HQ Operators Club" in shown
|
||||
|
||||
|
||||
def test_the_report_leaves_the_column_out_when_lookups_are_off(tmp_path):
|
||||
from rich.console import Console
|
||||
|
||||
band = ft8.Band()
|
||||
band.slots = 2
|
||||
_heard_from(band, "CQ W1AW FN31", ("W1AW",), "FN31")
|
||||
console = Console(width=150, force_terminal=False)
|
||||
with console.capture() as caught:
|
||||
ft8.report(console, band, ft8.Ft8Options(lookup=False))
|
||||
assert "licensed to" not in caught.get()
|
||||
|
||||
|
||||
def test_what_was_learned_is_written_to_the_disk(tmp_path):
|
||||
"""Otherwise every evening asks the register about the same band again,
|
||||
which is the one thing caching it was for."""
|
||||
from bandsaunter.callsign import CallsignBook
|
||||
|
||||
where = tmp_path / "callsigns.json"
|
||||
band = ft8.Band()
|
||||
band.register = _register(tmp_path, [("W1AW", "ARRL HQ", "Newington, CT")])
|
||||
band.register._dirty = True
|
||||
ft8.keep_lookups(band)
|
||||
assert where.exists()
|
||||
assert CallsignBook(online=False, cache=where).get("W1AW").name == "ARRL HQ"
|
||||
|
||||
|
||||
def test_listening_ends_by_writing_what_it_learned(tmp_path, monkeypatch):
|
||||
"""Through the real path rather than by calling the helper directly."""
|
||||
from rich.console import Console
|
||||
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
||||
|
||||
where = tmp_path / "callsigns.json"
|
||||
monkeypatch.setattr(ft8, "open_register",
|
||||
lambda options: CallsignBook(online=False,
|
||||
cache=where))
|
||||
monkeypatch.setattr(ft8, "open_device", lambda console, options: None)
|
||||
console = Console(width=100, force_terminal=False)
|
||||
options = ft8.defaults()
|
||||
options.log = False
|
||||
heard = ft8.Heard()
|
||||
heard.band.register = CallsignBook(online=False, cache=where)
|
||||
heard.band.register._entries["KU0W"] = Callsign(
|
||||
call="KU0W", name="Rod R Gowdy", status="found",
|
||||
version=CACHE_VERSION, fetched_at=time.time())
|
||||
heard.band.register._dirty = True
|
||||
with console.capture():
|
||||
ft8.finish(console, options, str(tmp_path), heard)
|
||||
assert CallsignBook(online=False, cache=where).get("KU0W").name == \
|
||||
"Rod R Gowdy"
|
||||
|
||||
|
||||
def test_every_mode_that_hears_callsigns_looks_them_up_and_caches_them():
|
||||
"""The whole of the answer to "all possible features", as a test rather
|
||||
than as a promise.
|
||||
|
||||
Written as a register of what is known to resolve callsigns, so that a
|
||||
module which starts doing it later fails here until somebody has
|
||||
decided whether it should. Checking only that the current ones work
|
||||
would say nothing about the next one.
|
||||
|
||||
Aircraft are deliberately absent: a registration is not an amateur
|
||||
callsign and no amateur register has heard of one. They have their own
|
||||
cached book, which test_flights covers.
|
||||
"""
|
||||
import ast
|
||||
import importlib
|
||||
|
||||
from bandsaunter import aprs, browse, scanner
|
||||
from bandsaunter.callsign import CallsignBook, _cache_path
|
||||
|
||||
known = {
|
||||
"scanner": "speech transcripts and Morse idents",
|
||||
"browse": "the recording browser",
|
||||
"aprs": "APRS stations",
|
||||
"ft8": "FT8 exchanges",
|
||||
}
|
||||
found = {}
|
||||
for path in sorted(Path(aprs.__file__).parent.glob("*.py")):
|
||||
if path.stem in ("callsign", "__init__"):
|
||||
continue
|
||||
tree = ast.parse(path.read_text())
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module == "callsign":
|
||||
if any(a.name in ("CallsignBook", "find_callsigns",
|
||||
"licensed_call") for a in node.names):
|
||||
found[path.stem] = True
|
||||
assert set(found) == set(known), (
|
||||
f"modules resolving callsigns changed: {sorted(found)} "
|
||||
f"vs {sorted(known)} -- add it here and give it a lookup, or "
|
||||
f"explain why it should not have one")
|
||||
|
||||
# And every one of them resolves through the same file, so a callsign
|
||||
# heard on two bands is asked about once rather than twice.
|
||||
for book in (aprs.open_book(aprs.defaults()),
|
||||
ft8.open_register(ft8.defaults()),
|
||||
CallsignBook(online=False)):
|
||||
assert book.cache_path == _cache_path()
|
||||
assert browse is not None and scanner is not None
|
||||
|
||||
|
||||
def test_a_callsign_heard_on_two_bands_is_asked_about_once(tmp_path):
|
||||
"""The point of one shared file: APRS and FT8 hear the same operators,
|
||||
and a register asked twice for the same answer is a register being
|
||||
asked one time too many."""
|
||||
from bandsaunter import aprs
|
||||
from bandsaunter.callsign import CACHE_VERSION, Callsign, CallsignBook
|
||||
|
||||
where = tmp_path / "callsigns.json"
|
||||
asked = []
|
||||
|
||||
class Counting(CallsignBook):
|
||||
def _request(self, url, call):
|
||||
asked.append(call)
|
||||
raise AssertionError("no network in tests")
|
||||
|
||||
first = Counting(online=False, cache=where)
|
||||
first._entries["W1AW"] = Callsign(call="W1AW", name="ARRL HQ",
|
||||
status="found", version=CACHE_VERSION,
|
||||
fetched_at=time.time())
|
||||
first._dirty = True
|
||||
first.save()
|
||||
|
||||
# A different mode, a later evening, the same file.
|
||||
second = Counting(online=True, cache=where)
|
||||
assert second.get("W1AW").name == "ARRL HQ"
|
||||
assert asked == [], "it went back to the register for an answer it had"
|
||||
|
|
|
|||
|
|
@ -243,3 +243,79 @@ def test_the_flags_it_tells_you_to_use_are_real():
|
|||
for line in ("scan -b 2m --simulate", "adsb --simulate --seconds 30",
|
||||
"devices --test", "transcribe --engines"):
|
||||
parser.parse_args(line.split()) # raises SystemExit if not
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Where it lives
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
REPOSITORY = "https://frostwarning.com/git/dustcouncil/bandsaunter"
|
||||
|
||||
|
||||
def test_the_install_instructions_say_where_to_clone_from():
|
||||
"""This said "git clone <the repository>" for a long time.
|
||||
|
||||
Nothing noticed, because nothing reads the install instructions except
|
||||
somebody installing -- who then cannot. A placeholder in the one
|
||||
command a new person types first is the worst place for one, so it is
|
||||
checked here rather than hoped about.
|
||||
"""
|
||||
body = INSTALL.read_text()
|
||||
clones = re.findall(r"^git clone\s+(\S+)", body, re.MULTILINE)
|
||||
assert clones, "the install instructions do not say how to get the source"
|
||||
for where in clones:
|
||||
assert where.startswith(("http://", "https://", "git@", "ssh://")), \
|
||||
f"not a repository anybody can clone: {where!r}"
|
||||
assert "<" not in where and ">" not in where, \
|
||||
f"still a placeholder: {where!r}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["INSTALL.md", "README.md",
|
||||
"pyproject.toml"])
|
||||
def test_the_files_a_new_person_reads_have_no_placeholders_left(path):
|
||||
"""Angle brackets around a word are how a placeholder is written, and
|
||||
every one of them is a sentence somebody cannot act on."""
|
||||
body = (ROOT / path).read_text()
|
||||
# Inside a fenced block a placeholder is an instruction to substitute;
|
||||
# outside one it is prose. Both are checked, and both are wrong when the
|
||||
# thing to substitute is the repository.
|
||||
for bad in ("<the repository>", "<repository>", "<repo>", "<URL>",
|
||||
"<url>"):
|
||||
assert bad not in body, f"{path} still says {bad}"
|
||||
|
||||
|
||||
def test_the_packaging_metadata_names_the_repository():
|
||||
import tomllib
|
||||
|
||||
body = tomllib.load(open(ROOT / "pyproject.toml", "rb"))
|
||||
urls = body["project"].get("urls") or {}
|
||||
assert urls, "pyproject names no homepage at all"
|
||||
assert any(REPOSITORY in v for v in urls.values())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("page", ["bandsaunter.1", "saunterbrowse.1"])
|
||||
def test_both_manuals_say_where_the_source_is(page):
|
||||
body = (ROOT / "packaging" / page).read_text()
|
||||
assert REPOSITORY in body, f"{page} does not say where to find the source"
|
||||
|
||||
|
||||
def test_the_built_package_says_where_it_came_from():
|
||||
"""Debian policy asks for a Homepage field, and an installed package
|
||||
that cannot say where it came from is one nobody can update."""
|
||||
for script in ("build-deb.sh", "build-repo.sh"):
|
||||
body = (ROOT / "packaging" / script).read_text()
|
||||
assert f"Homepage: {REPOSITORY}" in body, script
|
||||
assert "Maintainer: bandsaunter" not in body, \
|
||||
f"{script} still names the package as its own maintainer"
|
||||
|
||||
|
||||
def test_the_tile_server_is_told_where_to_look_this_program_up():
|
||||
"""Not decoration: the usage policy of the service the default tiles
|
||||
come from asks for a User-Agent that identifies the application and
|
||||
gives somewhere to look it up, so that an operator with a question
|
||||
about the traffic has somebody to ask."""
|
||||
from bandsaunter.basemap import USER_AGENT
|
||||
|
||||
assert "bandsaunter/" in USER_AGENT
|
||||
assert REPOSITORY in USER_AGENT
|
||||
assert bandsaunter.__version__ in USER_AGENT
|
||||
|
|
|
|||
|
|
@ -2419,3 +2419,249 @@ def test_the_empty_picture_draws_the_words_it_was_given(app):
|
|||
waiting="listening on 144.39 MHz\n\nnothing placed yet — a station "
|
||||
"appears\nonce it has said where it is"))
|
||||
assert int((plane != station).any(axis=2).sum()) > 200
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Keeping up with the window
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _Quiet(_NoPainter):
|
||||
"""A painter that lets the ground be drawn, once there is any.
|
||||
|
||||
_NoPainter refuses, on purpose, so that a test of "it asked and drew
|
||||
nothing" cannot pass by drawing something. These tests are about what
|
||||
happens once there *is* a map.
|
||||
"""
|
||||
|
||||
def drawImage(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
def _grown(sky, view, painter, width, height):
|
||||
"""Resize, paint the ground, and say what was asked for."""
|
||||
view.resize(width, height)
|
||||
view._draw_ground(painter, view.projection())
|
||||
return sky.wanted_ground()
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_window_made_bigger_fetches_a_sharper_map(app):
|
||||
"""A map fetched for a smaller window is still a map of the right piece
|
||||
of world, so nothing else notices it is being stretched. Opening at the
|
||||
default size and then going to the whole screen used to keep the first
|
||||
map until an aircraft wandered far enough to move the view out of the
|
||||
fetched box -- which on a quiet band is a long time to look at a blurred
|
||||
coastline.
|
||||
"""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
|
||||
asked = _grown(sky, view, painter, 900, 650)
|
||||
assert asked is not None
|
||||
key, box, size = asked
|
||||
first = size[0]
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
|
||||
# Twice as wide: the map in hand now covers each of its pixels with two.
|
||||
asked = _grown(sky, view, painter, 1800, 1300)
|
||||
assert asked is not None, "it kept stretching the map it had"
|
||||
assert asked[2][0] > first * 1.5, asked[2]
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_window_nudged_a_few_pixels_does_not_refetch(app):
|
||||
"""Dragging an edge must not send somebody's evening to a tile server a
|
||||
hundred times."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
key, box, size = _grown(sky, view, painter, 1200, 850)
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
|
||||
for extra in (1, 4, 20, 60):
|
||||
sky._wanted = None
|
||||
view.resize(1200 + extra, 850)
|
||||
view._draw_ground(painter, view.projection())
|
||||
assert sky.wanted_ground() is None, f"refetched over {extra} pixels"
|
||||
|
||||
|
||||
@qt
|
||||
def test_it_stops_asking_once_the_sharper_map_has_arrived(app):
|
||||
"""The check is "am I being stretched", and a window larger than the
|
||||
tile budget can cover is stretched by design -- so this had better be
|
||||
answered by the request rather than by the result, or a 4K window asks
|
||||
for a map for the rest of the evening."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
key, box, size = _grown(sky, view, painter, 3840, 2160)
|
||||
# Answered with a map of the size asked for, which is what the fetching
|
||||
# does however far the zoom had to be capped to get it.
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
for _ in range(5):
|
||||
sky._wanted = None
|
||||
view._draw_ground(painter, view.projection())
|
||||
assert sky.wanted_ground() is None, "it is still asking"
|
||||
|
||||
|
||||
@qt
|
||||
def test_a_window_made_smaller_does_not_refetch(app):
|
||||
"""Shrinking leaves the map finer than it needs to be, which costs
|
||||
nothing and looks perfect."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
key, box, size = _grown(sky, view, painter, 1800, 1300)
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
sky._wanted = None
|
||||
view.resize(900, 650)
|
||||
view._draw_ground(painter, view.projection())
|
||||
assert sky.wanted_ground() is None
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_stretch_is_measured_in_map_pixels_per_degree(app):
|
||||
"""Not in window pixels: the fetched box is wider than the view, so the
|
||||
two numbers are not the same and comparing the wrong pair would either
|
||||
never refetch or always."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
view.resize(1000, 700)
|
||||
projection = view.projection()
|
||||
box = view.ground_box(projection)
|
||||
across = box[3] - box[1]
|
||||
shown = projection.east - projection.west
|
||||
assert across > shown, "the fetched box is not wider than the view"
|
||||
|
||||
# A map at exactly the density the view wants is not stretched; one at
|
||||
# half that is.
|
||||
want = projection.width / shown
|
||||
exact = np.zeros((10, int(round(want * across))), dtype=np.uint8)
|
||||
assert not SkyView._stretched(exact, box, projection)
|
||||
half = np.zeros((10, max(1, exact.shape[1] // 2)), dtype=np.uint8)
|
||||
assert SkyView._stretched(half, box, projection)
|
||||
|
||||
# The case that tells the two ways of measuring apart, and the realistic
|
||||
# one: a map with exactly as many pixels as the window is wide, spread
|
||||
# over a box a quarter wider than the view. Only four fifths of those
|
||||
# pixels land on the screen, so it *is* being stretched -- and counting
|
||||
# raw pixels against raw pixels would call it fine.
|
||||
same = np.zeros((10, projection.width), dtype=np.uint8)
|
||||
assert SkyView._stretched(same, box, projection), (
|
||||
"the stretch is being measured in window pixels rather than in map "
|
||||
"pixels per degree")
|
||||
|
||||
|
||||
@qt
|
||||
def test_nothing_is_stretched_when_there_is_nothing_to_stretch(app):
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
view.resize(900, 650)
|
||||
projection = view.projection()
|
||||
assert not SkyView._stretched(None, (0.0, 0.0, 1.0, 1.0), projection)
|
||||
assert not SkyView._stretched(np.zeros((4, 4), dtype=np.uint8), None,
|
||||
projection)
|
||||
# A box with no width at all cannot be divided by.
|
||||
assert not SkyView._stretched(np.zeros((4, 4), dtype=np.uint8),
|
||||
(1.0, 2.0, 1.0, 2.0), projection)
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_window_opens_maximised(app):
|
||||
"""This is a map, and the thing somebody wants more of is map. It used
|
||||
to open at eleven hundred by eight hundred whatever the screen was."""
|
||||
from bandsaunter.livemap import _build
|
||||
|
||||
window = _build()["Window"](a_sky(a_blip()), "test")
|
||||
assert window.isMaximized()
|
||||
assert not window.isFullScreen()
|
||||
|
||||
|
||||
@qt
|
||||
def test_un_maximising_gives_back_a_usable_window(app):
|
||||
"""Set before maximising, so that there is a size to come back to: a
|
||||
window maximised from nothing restores to whatever the toolkit guessed."""
|
||||
from bandsaunter.livemap import _build
|
||||
|
||||
window = _build()["Window"](a_sky(a_blip()), "test")
|
||||
restored = window.normalGeometry()
|
||||
assert restored.width() >= 800 and restored.height() >= 600
|
||||
|
||||
|
||||
@qt
|
||||
def test_f_goes_to_true_full_screen_and_back_to_maximised(app):
|
||||
"""Back to maximised rather than to the size it was built at: leaving
|
||||
full screen should not shrink the map to a quarter of the screen."""
|
||||
from bandsaunter.livemap import _build, _qt
|
||||
|
||||
_name, core, gui, _widgets, _signal = _qt()
|
||||
window = _build()["Window"](a_sky(a_blip()), "test")
|
||||
|
||||
def press(letter):
|
||||
window.keyPressEvent(gui.QKeyEvent(
|
||||
core.QEvent.Type.KeyPress, 0,
|
||||
core.Qt.KeyboardModifier.NoModifier, letter))
|
||||
|
||||
press("f")
|
||||
assert window.isFullScreen() and not window.isMaximized()
|
||||
press("f")
|
||||
assert window.isMaximized() and not window.isFullScreen()
|
||||
|
||||
|
||||
@qt
|
||||
def test_the_keys_along_the_top_say_how_to_go_full_screen(app):
|
||||
"""A window with no frame is one somebody has to know a key to get out
|
||||
of, so the key is on the screen rather than only in the manual."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
view.resize(1400, 700)
|
||||
said = []
|
||||
|
||||
class _Spy:
|
||||
"""Swallows everything a painter is asked to do, and keeps the text."""
|
||||
|
||||
def __getattr__(self, name):
|
||||
return lambda *a, **k: None
|
||||
|
||||
def drawText(self, *a):
|
||||
said.append(a[-1])
|
||||
|
||||
view._draw_header(_Spy(), 1)
|
||||
assert any("f full" in line for line in said), said
|
||||
|
||||
|
||||
@qt
|
||||
def test_opening_maximised_fetches_a_map_for_the_size_it_opened_at(app):
|
||||
"""The two halves of this belong together: a window that opens big is no
|
||||
use if the map it fetches is for a window that opened small."""
|
||||
from bandsaunter.livemap import SkyView
|
||||
|
||||
sky = a_sky(a_blip())
|
||||
view = SkyView(sky)
|
||||
painter = _Quiet()
|
||||
|
||||
# The small size a window used to open at, answered.
|
||||
key, box, size = _grown(sky, view, painter, 1100, 800)
|
||||
small = size[0]
|
||||
sky.set_ground(np.zeros((size[1], size[0]), dtype=np.uint8), key, box)
|
||||
|
||||
# Now the size a maximised window on an ordinary screen has.
|
||||
sky._wanted = None
|
||||
asked = _grown(sky, view, painter, 1920, 1080)
|
||||
assert asked is not None, "it opened big and kept the small map"
|
||||
assert asked[2][0] > small
|
||||
|
|
|
|||
412
tests/test_register.py
Normal file
412
tests/test_register.py
Normal file
|
|
@ -0,0 +1,412 @@
|
|||
"""The register: everything ever looked up, read back and made browsable.
|
||||
|
||||
Nothing here touches a network or a receiver. Both caches are written by
|
||||
the tests and read by the code, which is the whole reason the reading lives
|
||||
in a module of its own.
|
||||
"""
|
||||
import json
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from rich.console import Console
|
||||
|
||||
from bandsaunter import register as reg
|
||||
from bandsaunter.browse import Browser
|
||||
|
||||
|
||||
def write_callsigns(path: Path, entries) -> Path:
|
||||
body = {}
|
||||
for one in entries:
|
||||
row = {"call": one["call"], "status": one.get("status", "found"),
|
||||
"fetched_at": one.get("fetched_at", 1_700_000_000.0),
|
||||
"version": 4}
|
||||
row.update({k: v for k, v in one.items() if k != "call"})
|
||||
body[one["call"]] = row
|
||||
path.write_text(json.dumps(body))
|
||||
return path
|
||||
|
||||
|
||||
def write_aircraft(path: Path, planes, routes=None) -> Path:
|
||||
path.write_text(json.dumps({"aircraft": {p["icao"]: p for p in planes},
|
||||
"routes": routes or {},
|
||||
"airports": {}}))
|
||||
return path
|
||||
|
||||
|
||||
SOME = [
|
||||
{"call": "AB7IC", "name": "Thomas G Britton", "location": "Tucson, AZ",
|
||||
"street": "8410 E Brookwood Dr", "postcode": "85750-2468",
|
||||
"country": "United States", "district": "district 7",
|
||||
"grid": "DM42og", "oper_class": "EXTRA", "licence_type": "PERSON",
|
||||
"expires": "12/21/2033", "latitude": 32.2750431,
|
||||
"longitude": -110.8131236, "source": "callook.info"},
|
||||
{"call": "VK4BLE", "country": "Australia", "status": "unlisted"},
|
||||
{"call": "WQVF960", "country": "United States", "status": "service"},
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reading the caches
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_a_callsign_comes_back_with_everything_that_was_known(tmp_path):
|
||||
where = write_callsigns(tmp_path / "c.json", SOME)
|
||||
entries = reg.load_callsigns(where)
|
||||
got = {e.title: e for e in entries}
|
||||
one = got["AB7IC"]
|
||||
assert one.what == "Thomas G Britton"
|
||||
assert one.where == "Tucson, AZ"
|
||||
assert one.position == pytest.approx((32.2750431, -110.8131236))
|
||||
shown = dict(one.rows)
|
||||
for label in ("licensed to", "class", "licence", "street", "town",
|
||||
"postcode", "country", "district", "grid", "expires",
|
||||
"position", "status", "answered by", "looked up"):
|
||||
assert label in shown, label
|
||||
assert shown["street"] == "8410 E Brookwood Dr"
|
||||
assert shown["answered by"] == "callook.info"
|
||||
|
||||
|
||||
def test_a_callsign_nobody_could_place_is_kept_rather_than_dropped(tmp_path):
|
||||
""""Asked about and in no register" is a fact about a station. A list
|
||||
that quietly dropped them would make an evening of unlisted foreign
|
||||
stations look like an evening when nothing was looked up."""
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
assert {e.title for e in entries} == {"AB7IC", "VK4BLE", "WQVF960"}
|
||||
vk = next(e for e in entries if e.title == "VK4BLE")
|
||||
assert vk.position is None and not vk.mappable
|
||||
assert dict(vk.rows)["status"] == \
|
||||
"asked about, in no register reachable from here"
|
||||
|
||||
|
||||
def test_a_status_says_what_it_means_rather_than_what_it_is_called(tmp_path):
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
service = next(e for e in entries if e.title == "WQVF960")
|
||||
assert "not an amateur callsign" in dict(service.rows)["status"]
|
||||
|
||||
|
||||
def test_a_position_taken_from_the_grid_says_so(tmp_path):
|
||||
"""A grid square is a few kilometres across and a licensed address is a
|
||||
street, so which one a coordinate came from matters."""
|
||||
where = write_callsigns(tmp_path / "c.json", [
|
||||
{"call": "G4ABC", "grid": "IO91", "latitude": 51.5,
|
||||
"longitude": -1.0, "from_grid": True}])
|
||||
one = reg.load_callsigns(where)[0]
|
||||
assert "from the grid square" in dict(one.rows)["position"]
|
||||
|
||||
|
||||
def test_an_aircraft_comes_back_with_its_route(tmp_path):
|
||||
"""The route is filed against the flight number and the airframe against
|
||||
the address, so the two halves have to be joined."""
|
||||
where = write_aircraft(
|
||||
tmp_path / "f.json",
|
||||
[{"icao": "4CA2D3", "registration": "EI-DYM", "callsign": "RYR1234",
|
||||
"manufacturer": "Boeing", "model": "737-8AS", "type_code": "B738",
|
||||
"operator": "Ryanair", "country": "Ireland", "status": "found",
|
||||
"fetched_at": 1_700_000_000.0}],
|
||||
{"RYR1234": {"origin": "Dublin", "origin_code": "EIDW",
|
||||
"origin_lat": 53.4213, "origin_lon": -6.2701,
|
||||
"destination": "Stansted", "destination_code": "EGSS",
|
||||
"route_source": "a schedule service"}})
|
||||
one = reg.load_aircraft(where)[0]
|
||||
assert one.title == "EI-DYM"
|
||||
assert one.what == "Boeing 737-8AS"
|
||||
assert one.where == "EIDW → EGSS"
|
||||
shown = dict(one.rows)
|
||||
assert shown["from"] == "Dublin (EIDW)"
|
||||
assert shown["to"] == "Stansted (EGSS)"
|
||||
assert shown["route from"] == "a schedule service"
|
||||
assert shown["ICAO address"] == "4CA2D3"
|
||||
assert one.position == pytest.approx((53.4213, -6.2701))
|
||||
|
||||
|
||||
def test_an_aircraft_with_no_registration_is_shown_by_its_address(tmp_path):
|
||||
where = write_aircraft(tmp_path / "f.json",
|
||||
[{"icao": "ABCDEF", "status": "unlisted"}])
|
||||
assert reg.load_aircraft(where)[0].title == "ABCDEF"
|
||||
|
||||
|
||||
def test_a_cache_that_is_not_there_is_no_entries_rather_than_an_error(tmp_path):
|
||||
assert reg.load_callsigns(tmp_path / "nope.json") == []
|
||||
assert reg.load_aircraft(tmp_path / "nope.json") == []
|
||||
|
||||
|
||||
def test_a_cache_full_of_rubbish_is_no_entries_rather_than_an_error(tmp_path):
|
||||
bad = tmp_path / "c.json"
|
||||
bad.write_text("{ not json at all")
|
||||
assert reg.load_callsigns(bad) == []
|
||||
bad.write_text("[1, 2, 3]")
|
||||
assert reg.load_callsigns(bad) == []
|
||||
|
||||
|
||||
def test_the_two_caches_are_the_ones_everything_else_writes():
|
||||
from bandsaunter.callsign import _cache_path as calls
|
||||
from bandsaunter.flights import _cache_path as planes
|
||||
|
||||
where = reg.cache_paths()
|
||||
assert where["callsigns"] == calls()
|
||||
assert where["aircraft"] == planes()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Maps
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_a_map_link_points_at_the_coordinates_and_says_nothing_else(tmp_path):
|
||||
"""The one part of this that leaves the machine, so it carries as little
|
||||
as it can: a map does not need to be told whose licence it is looking
|
||||
at in order to show a place."""
|
||||
one = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))[0]
|
||||
url = one.maps()
|
||||
assert url.startswith("https://www.google.com/maps/")
|
||||
assert "32.275043" in url and "-110.813124" in url
|
||||
assert "AB7IC" not in url
|
||||
assert "Britton" not in url and "Brookwood" not in url
|
||||
|
||||
|
||||
def test_nothing_to_point_at_is_no_link_rather_than_a_wrong_one(tmp_path):
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
vk = next(e for e in entries if e.title == "VK4BLE")
|
||||
assert vk.maps() == "" and reg.maps_url(None) == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Searching
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_searching_looks_at_every_field_and_not_only_the_name(tmp_path):
|
||||
"""The interesting question is usually not "which callsign" but "who was
|
||||
in Arizona", and that lives in the detail."""
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
assert [e.title for e in reg.search(entries, "tucson")] == ["AB7IC"]
|
||||
assert [e.title for e in reg.search(entries, "brookwood")] == ["AB7IC"]
|
||||
assert [e.title for e in reg.search(entries, "australia")] == ["VK4BLE"]
|
||||
assert [e.title for e in reg.search(entries, "EXTRA")] == ["AB7IC"]
|
||||
|
||||
|
||||
def test_every_word_has_to_match_so_a_search_can_be_narrowed(tmp_path):
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
assert [e.title for e in reg.search(entries, "united states")] != []
|
||||
assert reg.search(entries, "tucson australia") == []
|
||||
|
||||
|
||||
def test_an_empty_search_is_everything(tmp_path):
|
||||
entries = reg.load_callsigns(write_callsigns(tmp_path / "c.json", SOME))
|
||||
assert len(reg.search(entries, "")) == len(entries)
|
||||
assert len(reg.search(entries, " ")) == len(entries)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Browsing it
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def browser(tmp_path, monkeypatch):
|
||||
"""A browser whose register reads caches the test wrote."""
|
||||
calls = write_callsigns(tmp_path / "callsigns.json", SOME)
|
||||
planes = write_aircraft(tmp_path / "flights.json", [
|
||||
{"icao": "4CA2D3", "registration": "EI-DYM", "manufacturer": "Boeing",
|
||||
"model": "737-8AS", "status": "found", "fetched_at": 1.7e9}])
|
||||
monkeypatch.setattr(reg, "cache_paths",
|
||||
lambda: {"callsigns": calls, "aircraft": planes})
|
||||
console = Console(width=116, height=30, force_terminal=False)
|
||||
return Browser(tmp_path, console=console)
|
||||
|
||||
|
||||
def _screen(browser) -> str:
|
||||
with browser.console.capture() as caught:
|
||||
browser.console.print(browser.render())
|
||||
return caught.get()
|
||||
|
||||
|
||||
def test_c_opens_the_register_and_closes_it_again(browser):
|
||||
assert not browser.showing_register
|
||||
browser.handle("c")
|
||||
assert browser.showing_register
|
||||
assert "62" not in browser.message # it read the test's caches
|
||||
assert "3 callsigns" in browser.message
|
||||
browser.handle("c")
|
||||
assert not browser.showing_register
|
||||
browser.handle("c")
|
||||
browser.handle("escape")
|
||||
assert not browser.showing_register
|
||||
|
||||
|
||||
def test_the_register_shows_what_is_in_it(browser):
|
||||
browser.handle("c")
|
||||
shown = _screen(browser)
|
||||
assert "the register" in shown
|
||||
assert "AB7IC" in shown and "Thomas G Britton" in shown
|
||||
assert "Tucson, AZ" in shown
|
||||
# A date, because when something was looked up is part of the record.
|
||||
assert "2023-" in shown or "2026-" in shown or "2020-" in shown
|
||||
|
||||
|
||||
def test_the_detail_shows_every_field_for_the_current_one(browser):
|
||||
browser.handle("c")
|
||||
browser.reg_index = 0
|
||||
shown = _screen(browser)
|
||||
for bit in ("8410 E Brookwood Dr", "85750-2468", "DM42og", "EXTRA",
|
||||
"12/21/2033", "callook.info"):
|
||||
assert bit in shown, bit
|
||||
|
||||
|
||||
def test_tab_switches_between_callsigns_and_aircraft(browser):
|
||||
browser.handle("c")
|
||||
assert browser.reg_kind == "callsigns"
|
||||
browser.handle("tab")
|
||||
assert browser.reg_kind == "aircraft"
|
||||
shown = _screen(browser)
|
||||
assert "EI-DYM" in shown and "Boeing 737-8AS" in shown
|
||||
browser.handle("tab")
|
||||
assert browser.reg_kind == "callsigns"
|
||||
|
||||
|
||||
def test_moving_about_stays_inside_the_list(browser):
|
||||
browser.handle("c")
|
||||
for _ in range(20):
|
||||
browser.handle("down")
|
||||
_screen(browser) # the panel clamps as it draws
|
||||
assert browser.reg_index == 2 # three entries
|
||||
for _ in range(20):
|
||||
browser.handle("up")
|
||||
assert browser.reg_index == 0
|
||||
browser.handle("end")
|
||||
_screen(browser)
|
||||
assert browser.reg_index == 2
|
||||
browser.handle("home")
|
||||
assert browser.reg_index == 0
|
||||
|
||||
|
||||
def test_searching_in_the_register_narrows_the_list(browser):
|
||||
browser.handle("c")
|
||||
browser.handle("/")
|
||||
for ch in "tucson":
|
||||
browser.handle(ch)
|
||||
assert browser.reg_query == "tucson"
|
||||
browser.handle("enter")
|
||||
shown = _screen(browser)
|
||||
assert "AB7IC" in shown and "VK4BLE" not in shown
|
||||
assert "matching" in shown
|
||||
browser.handle("/")
|
||||
browser.handle("escape")
|
||||
assert browser.reg_query == ""
|
||||
|
||||
|
||||
def test_backspace_takes_a_letter_off_a_search(browser):
|
||||
browser.handle("c")
|
||||
browser.handle("/")
|
||||
for ch in "tucsonx":
|
||||
browser.handle(ch)
|
||||
browser.handle("backspace")
|
||||
assert browser.reg_query == "tucson"
|
||||
|
||||
|
||||
def test_g_opens_the_place_in_a_browser(browser, monkeypatch):
|
||||
import webbrowser
|
||||
|
||||
asked = []
|
||||
monkeypatch.setattr(webbrowser, "open",
|
||||
lambda url: asked.append(url) or True)
|
||||
browser.handle("c")
|
||||
browser.reg_index = 0
|
||||
browser.handle("g")
|
||||
assert len(asked) == 1
|
||||
assert "32.275043" in asked[0] and "maps" in asked[0]
|
||||
assert "opened AB7IC" in browser.message
|
||||
|
||||
|
||||
def test_g_on_something_with_no_position_says_so_rather_than_guessing(
|
||||
browser, monkeypatch):
|
||||
import webbrowser
|
||||
|
||||
asked = []
|
||||
monkeypatch.setattr(webbrowser, "open",
|
||||
lambda url: asked.append(url) or True)
|
||||
browser.handle("c")
|
||||
browser.handle("/")
|
||||
for ch in "australia":
|
||||
browser.handle(ch)
|
||||
browser.handle("enter")
|
||||
browser.handle("g")
|
||||
assert asked == []
|
||||
assert "where this one is" in browser.message
|
||||
|
||||
|
||||
def test_a_machine_with_no_browser_prints_the_place_instead(browser,
|
||||
monkeypatch):
|
||||
"""A headless box is the normal case for a receiver, and the coordinates
|
||||
are still the answer somebody wanted."""
|
||||
import webbrowser
|
||||
|
||||
monkeypatch.setattr(webbrowser, "open", lambda url: False)
|
||||
browser.handle("c")
|
||||
browser.reg_index = 0
|
||||
browser.handle("g")
|
||||
assert "no browser to open" in browser.message
|
||||
assert "32.275043" in browser.message
|
||||
|
||||
|
||||
def test_a_browser_that_will_not_start_is_reported_rather_than_raising(
|
||||
browser, monkeypatch):
|
||||
import webbrowser
|
||||
|
||||
def boom(url):
|
||||
raise RuntimeError("no display")
|
||||
|
||||
monkeypatch.setattr(webbrowser, "open", boom)
|
||||
browser.handle("c")
|
||||
browser.reg_index = 0
|
||||
assert browser.handle("g") is True
|
||||
assert "could not open a browser" in browser.message
|
||||
|
||||
|
||||
def test_q_still_quits_from_the_register(browser):
|
||||
browser.handle("c")
|
||||
assert browser.handle("q") is False
|
||||
|
||||
|
||||
def test_the_register_is_read_once_rather_than_on_every_frame(browser,
|
||||
monkeypatch):
|
||||
reads = []
|
||||
real = reg.load_all
|
||||
monkeypatch.setattr(reg, "load_all",
|
||||
lambda *a, **k: reads.append(1) or real(*a, **k))
|
||||
browser.handle("c")
|
||||
for _ in range(5):
|
||||
_screen(browser)
|
||||
browser.handle("down")
|
||||
assert len(reads) == 1
|
||||
# And r asks again, for somebody who has just finished a scan.
|
||||
browser.handle("r")
|
||||
assert len(reads) == 2
|
||||
assert "read the caches again" in browser.message
|
||||
|
||||
|
||||
def test_the_keys_page_says_the_register_is_there(browser):
|
||||
browser.handle("?")
|
||||
shown = _screen(browser)
|
||||
assert "every callsign and aircraft ever looked up" in shown
|
||||
# The register's own keys are named on the register's own screen, the
|
||||
# keys page being exactly as tall as an eighty-by-twenty-four terminal.
|
||||
browser.handle("?") # close the keys page
|
||||
browser.handle("c")
|
||||
browser.message = "" # the footer shows counts first
|
||||
assert "g map" in _screen(browser)
|
||||
assert "tab switch" in _screen(browser)
|
||||
|
||||
|
||||
def test_an_empty_register_says_so_rather_than_drawing_a_blank(tmp_path,
|
||||
monkeypatch):
|
||||
monkeypatch.setattr(reg, "cache_paths",
|
||||
lambda: {"callsigns": tmp_path / "none.json",
|
||||
"aircraft": tmp_path / "none.json"})
|
||||
console = Console(width=100, height=24, force_terminal=False)
|
||||
browser = Browser(tmp_path, console=console)
|
||||
browser.handle("c")
|
||||
shown = _screen(browser)
|
||||
assert "nothing here" in shown
|
||||
assert browser.reg_current is None
|
||||
# And g on nothing at all does not fall over.
|
||||
assert browser.handle("g") is True
|
||||
239
tests/test_splash.py
Normal file
239
tests/test_splash.py
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
"""The title screen.
|
||||
|
||||
Most of what matters here is when it does *not* appear. Everything in this
|
||||
program can be piped into something else, and a banner in the middle of a
|
||||
table somebody is parsing is corruption rather than decoration.
|
||||
"""
|
||||
from rich.console import Console
|
||||
|
||||
from bandsaunter import splash
|
||||
|
||||
|
||||
def _plain(console: Console, drawing) -> str:
|
||||
with console.capture() as caught:
|
||||
drawing()
|
||||
return caught.get()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The drawing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_both_names_come_out_as_four_rows_of_braille():
|
||||
for word in (splash.SCANNER_NAME, splash.BROWSER_NAME):
|
||||
rows = splash.banner(word)
|
||||
assert len(rows) == splash.ROWS
|
||||
assert all(all(0x2800 <= ord(c) <= 0x28FF for c in row)
|
||||
for row in rows), "something in there is not braille"
|
||||
assert any(c != "\u2800" for row in rows for c in row)
|
||||
|
||||
|
||||
def test_the_names_are_written_the_way_they_are_spelled():
|
||||
"""Not shouted. Braille gives four times the vertical detail a block
|
||||
does, which is what makes room for two heights of letter at once."""
|
||||
assert splash.SCANNER_NAME == "BandSaunter"
|
||||
assert splash.BROWSER_NAME == "SaunterBrowse"
|
||||
assert set("BS") <= set(splash.CAPS)
|
||||
assert "a" in splash.LOWER and "d" in splash.ASCENDERS
|
||||
|
||||
|
||||
def test_a_capital_stands_taller_than_the_letter_beside_it():
|
||||
"""The point of the whole exercise: if both were drawn the same height
|
||||
the name would read as BANDSAUNTER, which is not its name."""
|
||||
def top_of(word):
|
||||
drawn = splash.pixels(word)
|
||||
return next(i for i, row in enumerate(drawn) if row.strip())
|
||||
|
||||
assert top_of("B") < top_of("a"), "the capital does not rise"
|
||||
assert top_of("d") == top_of("B"), "the ascender does not reach"
|
||||
assert top_of("t") < top_of("a"), "the t does not rise at all"
|
||||
assert top_of("o") == top_of("a"), "two x-height letters disagree"
|
||||
|
||||
|
||||
def test_every_letter_sits_on_the_same_baseline():
|
||||
def bottom_of(word):
|
||||
drawn = splash.pixels(word)
|
||||
return max(i for i, row in enumerate(drawn) if row.strip())
|
||||
|
||||
heights = {ch: bottom_of(ch) for ch in "BSandutersow"}
|
||||
assert len(set(heights.values())) == 1, heights
|
||||
|
||||
|
||||
def test_both_names_fit_an_eighty_column_terminal():
|
||||
"""Which is the narrowest terminal anybody still has, and the width a
|
||||
banner has to be cut to rather than wrapped at."""
|
||||
for word in (splash.SCANNER_NAME, splash.BROWSER_NAME):
|
||||
assert max(len(r) for r in splash.banner(word)) <= 78, word
|
||||
|
||||
|
||||
def test_every_letter_the_two_names_need_has_a_glyph():
|
||||
"""A missing one would silently shorten the name rather than fail."""
|
||||
for word in (splash.SCANNER_NAME, splash.BROWSER_NAME):
|
||||
for letter in word:
|
||||
assert letter in splash.FONT, letter
|
||||
|
||||
|
||||
def test_a_stroke_is_two_dots_thick_in_both_directions():
|
||||
"""One dot thick reads as a dotted line rather than a line, which is
|
||||
the one thing that makes drawing in braille difficult. Doubling the
|
||||
small font is what avoids it."""
|
||||
doubled = splash._double(("#.",))
|
||||
assert doubled == ["##..", "##.."]
|
||||
|
||||
|
||||
def test_a_letter_with_no_glyph_is_left_out_rather_than_drawn_as_a_hole():
|
||||
assert splash.banner("Band!!") == splash.banner("Band")
|
||||
assert splash.banner("!!!") == []
|
||||
assert splash.banner("") == []
|
||||
# And an uppercase name is no longer the same as a lowercase one, which
|
||||
# is the whole change: the font has two heights now.
|
||||
assert splash.banner("Band") != splash.banner("BAND")
|
||||
|
||||
|
||||
def test_the_gradient_is_cold_the_whole_way_along():
|
||||
"""Digital blues, cyans and white, and nothing warm anywhere.
|
||||
|
||||
Checked as an invariant rather than by naming the five stops: blue is
|
||||
never the weakest channel and red is never the strongest, which is what
|
||||
"blue through cyan to white" *means* and what any warm colour slipping
|
||||
back in would break. This 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.
|
||||
"""
|
||||
for step in range(0, 101):
|
||||
style = splash._colour(step / 100)
|
||||
red, green, blue = (int(v) for v in style[4:-1].split(","))
|
||||
assert blue >= green >= red, (step, style)
|
||||
assert blue >= 120, f"too dark to read at {step}: {style}"
|
||||
|
||||
|
||||
def test_the_gradient_ends_pale_and_starts_deep():
|
||||
"""A gradient that did not travel would be a colour."""
|
||||
start = [int(v) for v in splash._colour(0.0)[4:-1].split(",")]
|
||||
end = [int(v) for v in splash._colour(1.0)[4:-1].split(",")]
|
||||
assert sum(end) > sum(start) * 2, "it barely brightens"
|
||||
assert start[2] >= 120 and end[1] >= 200
|
||||
|
||||
|
||||
def test_the_gradient_runs_from_one_end_of_the_ramp_to_the_other():
|
||||
first, last = splash._colour(0.0), splash._colour(1.0)
|
||||
assert first != last
|
||||
assert first.startswith("rgb(") and last.startswith("rgb(")
|
||||
# And it is clamped rather than extrapolated off either end.
|
||||
assert splash._colour(-5.0) == first
|
||||
assert splash._colour(5.0) == last
|
||||
|
||||
|
||||
def test_the_lines_under_it_are_drawn_in_the_order_they_were_given():
|
||||
console = Console(width=100, force_terminal=False)
|
||||
shown = _plain(console, lambda: splash.show(
|
||||
console, splash.SCANNER_NAME,
|
||||
("Conceived by: The Dust Council", "100% AI Coded by Claude Code."),
|
||||
force=True))
|
||||
assert "Conceived by: The Dust Council" in shown
|
||||
assert "100% AI Coded by Claude Code." in shown
|
||||
assert shown.index("Conceived") < shown.index("100%")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# When it stays out of the way
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_nothing_is_drawn_when_the_output_is_not_a_terminal():
|
||||
"""The one that matters. A table piped into something else must come
|
||||
out as a table."""
|
||||
console = Console(width=100, force_terminal=False)
|
||||
shown = _plain(console, lambda: splash.show(console, splash.SCANNER_NAME,
|
||||
("a", "b")))
|
||||
assert shown == ""
|
||||
assert splash.wanted(console) is False
|
||||
|
||||
|
||||
def test_no_splash_turns_it_off_on_a_terminal_too():
|
||||
console = Console(width=100, force_terminal=True)
|
||||
assert splash.wanted(console) is True
|
||||
assert splash.wanted(console, no_splash=True) is False
|
||||
shown = _plain(console, lambda: splash.show(console, splash.SCANNER_NAME,
|
||||
("a",), no_splash=True))
|
||||
assert shown == ""
|
||||
|
||||
|
||||
def test_the_environment_can_turn_it_off_for_good(monkeypatch):
|
||||
"""For anybody who would rather it did not, without having to remember a
|
||||
flag on every invocation."""
|
||||
console = Console(width=100, force_terminal=True)
|
||||
monkeypatch.setenv("BANDSAUNTER_NO_SPLASH", "1")
|
||||
assert splash.wanted(console) is False
|
||||
shown = _plain(console, lambda: splash.show(console, splash.SCANNER_NAME,
|
||||
("a",)))
|
||||
assert shown == ""
|
||||
|
||||
|
||||
def test_it_says_whether_it_drew_anything():
|
||||
console = Console(width=100, force_terminal=False)
|
||||
assert splash.show(console, splash.SCANNER_NAME, ("a",)) is False
|
||||
assert splash.show(console, splash.SCANNER_NAME, ("a",), force=True) is True
|
||||
assert splash.show(console, "!!!", ("a",), force=True) is False
|
||||
|
||||
|
||||
def test_nothing_sleeps_when_nothing_is_drawn(monkeypatch):
|
||||
"""The pause is for a program about to take the screen over. Paying it
|
||||
with no banner drawn would be a tenth of a second added to every piped
|
||||
command for nothing."""
|
||||
import time
|
||||
|
||||
slept = []
|
||||
monkeypatch.setattr(time, "sleep", lambda s: slept.append(s))
|
||||
console = Console(width=100, force_terminal=False)
|
||||
splash.show(console, splash.BROWSER_NAME, ("a",), pause=5.0)
|
||||
assert slept == []
|
||||
splash.show(console, splash.BROWSER_NAME, ("a",), pause=0.25, force=True)
|
||||
assert slept == [0.25]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Where it is wired in
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_both_programs_can_be_told_not_to_draw_one():
|
||||
from bandsaunter.browse import build_parser as browse_parser
|
||||
from bandsaunter.cli import build_parser as cli_parser
|
||||
|
||||
assert cli_parser().parse_args(["--no-splash", "devices"]).no_splash
|
||||
assert not cli_parser().parse_args(["devices"]).no_splash
|
||||
assert browse_parser().parse_args(["--no-splash"]).no_splash
|
||||
assert not browse_parser().parse_args([]).no_splash
|
||||
|
||||
|
||||
def test_the_scanner_draws_its_own_name(monkeypatch):
|
||||
drawn = []
|
||||
monkeypatch.setattr(splash, "show",
|
||||
lambda console, word, lines=(), **kw:
|
||||
drawn.append((word, tuple(lines))) or False)
|
||||
from bandsaunter import cli
|
||||
|
||||
cli.main(["devices"])
|
||||
assert drawn and drawn[0][0] == splash.SCANNER_NAME
|
||||
lines = drawn[0][1]
|
||||
assert lines[0] == "Conceived by: The Dust Council"
|
||||
assert lines[1] == "100% AI Coded by Claude Code."
|
||||
|
||||
|
||||
def test_the_browser_draws_its_own_name_and_waits_a_moment(monkeypatch,
|
||||
tmp_path):
|
||||
drawn = []
|
||||
|
||||
def fake(console, word, lines=(), **kw):
|
||||
drawn.append((word, tuple(lines), kw.get("pause", 0.0)))
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(splash, "show", fake)
|
||||
from bandsaunter import browse
|
||||
|
||||
# Straight back out again: the banner is drawn before anything else.
|
||||
browse.main([str(tmp_path), "--callsigns"])
|
||||
assert drawn and drawn[0][0] == splash.BROWSER_NAME
|
||||
assert drawn[0][1][0] == "Conceived by: The Dust Council"
|
||||
assert drawn[0][1][1] == "100% AI Coded by Claude Code."
|
||||
# The browser runs on the alternate screen, so the banner needs a beat.
|
||||
assert drawn[0][2] > 0
|
||||
Loading…
Add table
Add a link
Reference in a new issue