Files
meshcore-analyzer/cmd/server/planner_config_test.go
11eb72f578 feat(planner): Coverage tab, reach of a candidate repeater site (#2406)
The repeater planner (#2391) gets a fourth tab, **Coverage**: put a
marker where you are thinking of placing a repeater, set its antenna
height, and see on the map who would hear it. It answers the siting
question "what does a repeater reach if we put it here", with two
layers: handheld users and other repeaters.

## What it shows

- **Users layer:** the chance that a handheld at 1.5 m hears the site,
in 4 bands (10-25%, 25-50%, 50-75%, 75% and up; below 10% is not
painted). The chance comes from a distance curve `P(d) = 1 / (1 +
exp((ln d - ln d50) / slope))`, fitted on drive-test receptions of 41
Belgian repeaters (d50 2.7 km, slope 0.30). Terrain only lowers a cell
by 2 bands where a 1.5 m receiver sits deeper than 1 first-Fresnel
radius under the terrain (`cmd/server/planner_viewshed.go:19-21`).
Antenna height does not change the curve: in the drive tests, handheld
reach barely changed between 1, 7 and 15 m. The panel says so in one
line.
- **Repeaters layer:** first-Fresnel clearance from the site to every
cell, for a receiver at "Repeaters at" height (default
`planner.existingAntennaM`). 3 classes: line of sight (clearance 0% or
more), slightly blocked (-20% to 0%), blocked (not painted). Every known
repeater within range gets its link computed with the existing planner
link code, a dot in its class colour, a line for line of sight and
slightly blocked, and an entry in a list.
- **Compute button:** changing site, height or range moves the marker
and updates the URL hash right away, and dims an existing result with an
"Outdated" note. Only "Compute coverage" starts a job. A shared link
that carries a site computes once on open. The planner has 1 heavy-job
slot shared with Area and allows 6 jobs per minute per IP, so
recomputing on every change would burn both.

State is in the hash:
`#/tools/planner?mode=coverage&site=51.06,4.41&h=10&rx=5&range=30&layer=repeaters`.

This builds on the repeater planner @zfouts wrote in #2391: the terrain
tiles, the first-Fresnel analysis, the link code, the job protocol and
the Area module pattern are all reused here. Thanks for that work, it
made this tab a small addition instead of a new subsystem.

## Why the Repeaters classes are not the route LOS verdicts

The route verdicts (clear 100%+, clear60 60%+, marginal 0%+, blocked)
almost never show on Shuttle Radar Topography Mission (SRTM) terrain at
mast heights. At 10 m / 5 m, 30 km around Mechelen, 109 of 70,980 cells
reach clear60 or clear. SRTM includes trees and roofs, so the line
between 2 masts rarely clears 60% of the Fresnel zone.

I checked the clearance against one Belgian repeater (28 m, receivers at
5 m) and the repeaters live data shows it actually hears:

| Distance | Heard, clearance >= 0 | Heard, clearance < 0 |
|---|---|---|
| 0-10 km | 9 of 11 | none in range |
| 10-20 km | 3 of 4 | 1 of 8 |
| 20-30 km | 0 of 6 | 3 of 35 |
| 30-60 km | 1 of 2 | 0 of 84 |

Every link heard within 16 km had a clearance between 2% and 54%, so
"marginal" is where working links live. The map classes follow that
(`repeaterClass`, `cmd/server/planner_viewshed.go:75-89`). Chain, Relay
and Area keep the shared verdicts; `losVerdict` is unchanged. This rests
on 17 heard links from 1 repeater, which is why the -20% band is narrow
and the panel says line of sight stops being enough beyond about 20 km.

## Server

- `GET /api/planner/viewshed?site=&h=&rx=&range=`
(`cmd/server/planner_api.go:603`, route `cmd/server/routes.go:393`).
Same job protocol, result cache, rate limits and opt-in as the other
planner endpoints: 404 while `planner.enabled` is false.
- One byte per cell: low nibble Users class 1-5, high nibble Repeaters
class 1-3, 0 for no data. The grid is about 300 x 300 at every range:
0.2 km cells up to 30 km, `range/150` above (`planner_viewshed.go:47`).
- Links skip rooms, stale repeaters and a repeater within 100 m of the
site (that is the site itself). They carry no `elev_m` profile.
- `truncated` is true only when the 300-node cap may have dropped a
repeater within range (`viewshedTruncated`, `planner_api.go:694`).
- Tile cap: `Viewshed` in the planner tile limits, sized from the
largest offered range (60 km).
- New config: `planner.userReach.{d50Km,slope}` with a `_comment` in
`config.example.json`. Bounds 0.2-50 km and 0.05-2.
- No writes, no new `map[string]interface{}`; response types
`PlannerViewshedResponse/Params/Link` in `planner_types.go`.

## Frontend

- `public/planner-coverage.js` + `.css`, mounted like `planner-area.js`.
`planner.js` gets a `MODULES` table (`public/planner.js:31`) so Area and
Coverage share one enter/leave path.
- Canvas raster in an `L.imageOverlay`; the layer switch repaints
locally without a new request. Requests go through `fetchJob` / `CSApi`.
- Colours are CSS variables `--pl-cov-user-2..5` and `--pl-cov-rep-1..3`
in `:root` and both dark blocks of `style.css`; the Repeaters ones point
at `--status-*`, so a theme that changes those changes the map.

## Performance

The job is opt-in and runs in the existing planner job slot, never in a
hot path. Measured on real SRTM tiles, local build, 304 Belgian
repeaters:

| Site | Range | Mast | Job time |
|---|---|---|---|
| Maasvallei (hilly) | 30 km | 10 m | 2.07 s |
| Maasvallei | 30 km | 30 m | 2.57 s |
| Maasvallei | 60 km | 10 m | 3.98 s |
| Mechelen (flat) | 30 km | 10 m | 2.61 s |

On a staging instance (ARM64, cold tile cache) a 30 km job took 6.8 s
including the tile downloads. Response size at 60 km with 115 links:
239,942 bytes with link elevation profiles, 149,984 without (what this
PR ships). `BenchmarkViewshedMaxLeg` covers the 60 km worst case on a
synthetic terrain view.

## Verification

- Go: 26 viewshed tests and benchmarks in `planner_viewshed_test.go`,
`planner_api_test.go`, `planner_config_test.go` and
`planner_tiles_test.go`, among them: flat terrain equals the plain curve
and `analyzeLOS`, a ridge shadows only its far side, missing terrain is
"no data", the `truncated` rule (proven to fail on the old rule), links
without `elev_m`, the repeater at the site left out. `go test ./...` in
`cmd/server` passes.
- Frontend: `tests/unit/test-planner-coverage.js` (23 tests, in
`test-all.sh`): grid decode, class-to-colour mapping, unpainted classes,
hash round trip, no fetch on parameter change, 1 fetch per click,
deep-link autorun once, stale responses ignored, link classes at the
boundaries, escaped repeater names.
- E2E: 5 Coverage cases in `tests/e2e/test-planner-e2e.js` (stubbed
viewshed): click and compute, layer switch without a request, outdated
then recompute, deep link, leaving the tab removes the overlay. Planner
E2E 25/25 locally.
- eslint 0 errors. Browser: light and dark theme, Users and Repeaters on
flat, hilly and coastal sites, deep links, no console errors; also on a
staging instance with live data.

## Not in this PR

- The `--pl-cov-*` colours are not in the customizer's `THEME_CSS_MAP`
yet. They follow `--status-*` for the Repeaters layer; the Users colours
need their own entries (AGENTS.md rule 8, later milestone).
- In Flanders the Users layer is close to a circle: 0.3% of cells differ
from the plain curve around Mechelen, 42% in the Maasvallei, 64% in the
Ardennes. The terrain correction is untested in hilly areas, the drive
tests had no repeater there.
- The Repeaters calibration uses 1 repeater. Other operators with drive
tests or neighbour data can tighten it.
- A link's class comes from `clearance_pct`, rounded to 0.1%, while the
grid uses the raw clearance: within 0.05% of a bound a link can land 1
class off the cell under it. List, line and dot always agree with each
other.
- An OS dark-mode switch without the theme toggle does not repaint the
overlay until the next compute, the same as the planner's tile layer.

---------

Co-authored-by: zfouts <zachary.fouts@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:19:49 +01:00

263 lines
11 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"bytes"
"encoding/json"
"log"
"math"
"net/http"
"slices"
"strings"
"testing"
)
func TestPlannerConfigSizes(t *testing.T) {
// Unset: the defaults, no warning.
for _, c := range []*PlannerConfig{nil, {}, {Enabled: true}} {
r, warns := c.resolved()
if r.MaxAreaKm != 100 || r.NodeMarginKm != 30 || r.MaxLegKm != 100 || len(warns) != 0 {
t.Fatalf("%+v: resolved %+v, warnings %q", c, r, warns)
}
}
// Each end of each range is kept.
for _, c := range []PlannerConfig{
{MaxAreaKm: 20, NodeMarginKm: 10, MaxLegKm: 10, DefaultRangeKm: 10},
{MaxAreaKm: 250, NodeMarginKm: 60, MaxLegKm: 200},
{MaxAreaKm: 137.5, NodeMarginKm: 12.5, MaxLegKm: 64},
} {
r, warns := c.resolved()
if r.MaxAreaKm != c.MaxAreaKm || r.NodeMarginKm != c.NodeMarginKm || r.MaxLegKm != c.MaxLegKm || len(warns) != 0 {
t.Fatalf("%+v: resolved %+v, warnings %q", c, r, warns)
}
}
// Out of range (NaN included): the default and one warning each.
for _, c := range []struct {
cfg PlannerConfig
warn string
}{
{PlannerConfig{MaxAreaKm: 19.9}, "planner.maxAreaKm must be within 20-250; using the default"},
{PlannerConfig{MaxAreaKm: 251}, "planner.maxAreaKm must be within 20-250; using the default"},
{PlannerConfig{MaxAreaKm: -100}, "planner.maxAreaKm must be within 20-250; using the default"},
{PlannerConfig{MaxAreaKm: math.NaN()}, "planner.maxAreaKm must be within 20-250; using the default"},
{PlannerConfig{NodeMarginKm: 9.5}, "planner.nodeMarginKm must be within 10-60; using the default"},
{PlannerConfig{NodeMarginKm: 61}, "planner.nodeMarginKm must be within 10-60; using the default"},
{PlannerConfig{MaxLegKm: 9}, "planner.maxLegKm must be within 10-200; using the default"},
{PlannerConfig{MaxLegKm: 200.5}, "planner.maxLegKm must be within 10-200; using the default"},
{PlannerConfig{MaxLegKm: math.Inf(1)}, "planner.maxLegKm must be within 10-200; using the default"},
} {
r, warns := c.cfg.resolved()
if r.MaxAreaKm != 100 || r.NodeMarginKm != 30 || r.MaxLegKm != 100 || !slices.Equal(warns, []string{c.warn}) {
t.Errorf("%+v: resolved %+v, warnings %q", c.cfg, r, warns)
}
}
}
func TestPlannerConfigRangesFollowMaxLeg(t *testing.T) {
for _, c := range []struct {
maxLeg float64
want []float64
}{
{100, []float64{10, 15, 20, 30, 40, 50, 60}},
{60, []float64{10, 15, 20, 30, 40, 50, 60}},
{45, []float64{10, 15, 20, 30, 40}},
{10, []float64{10}},
} {
r, _ := (&PlannerConfig{MaxLegKm: c.maxLeg}).resolved()
if got := r.rangesKm(); !slices.Equal(got, c.want) {
t.Errorf("maxLegKm %v: ranges %v, want %v", c.maxLeg, got, c.want)
}
}
// The returned slice cannot grow into the shared list.
r, _ := (&PlannerConfig{MaxLegKm: 25}).resolved()
_ = append(r.rangesKm(), 999)
if plannerRangesKm[3] != 30 {
t.Fatal("append through rangesKm overwrote plannerRangesKm")
}
// A default range over maxLegKm becomes the largest allowed one.
for _, c := range []struct {
cfg PlannerConfig
wantRange float64
warn string
}{
{PlannerConfig{MaxLegKm: 25}, 20, "planner.defaultRangeKm 30 is over planner.maxLegKm 25; using 20"},
{PlannerConfig{MaxLegKm: 10, DefaultRangeKm: 60}, 10, "planner.defaultRangeKm 60 is over planner.maxLegKm 10; using 10"},
} {
r, warns := c.cfg.resolved()
if r.DefaultRangeKm != c.wantRange || !slices.Equal(warns, []string{c.warn}) {
t.Errorf("%+v: range %v, warnings %q", c.cfg, r.DefaultRangeKm, warns)
}
// Resolving again is stable and quiet.
r2, warns := r.resolved()
same := *r2.UserReach == *r.UserReach // pointers differ, values must not
r2.UserReach, r.UserReach = nil, nil
if r2 != r || !same || len(warns) != 0 {
t.Errorf("%+v: re-resolved %+v, warnings %q", c.cfg, r2, warns)
}
}
if r, warns := (&PlannerConfig{MaxLegKm: 40, DefaultRangeKm: 40}).resolved(); r.DefaultRangeKm != 40 || len(warns) != 0 {
t.Errorf("range equal to maxLegKm: %v, %q", r.DefaultRangeKm, warns)
}
}
func TestPlannerConfigJSONAndClient(t *testing.T) {
var cfg Config
raw := `{"planner":{"enabled":true,"maxAreaKm":180,"nodeMarginKm":45,"maxLegKm":35}}`
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
t.Fatal(err)
}
if p := cfg.Planner; p.MaxAreaKm != 180 || p.NodeMarginKm != 45 || p.MaxLegKm != 35 {
t.Fatalf("decoded %+v", p)
}
cc := cfg.Planner.clientConfig(nil)
if cc.MaxAreaKm != 180 || cc.NodeMarginKm != 45 || cc.MaxLegKm != 35 || cc.DefaultRangeKm != 30 ||
!slices.Equal(cc.RangesKm, []float64{10, 15, 20, 30}) {
t.Fatalf("client config %+v", cc)
}
b, _ := json.Marshal(cc)
for _, k := range []string{`"maxAreaKm":180`, `"nodeMarginKm":45`, `"maxLegKm":35`, `"rangesKm":[10,15,20,30]`} {
if !strings.Contains(string(b), k) {
t.Fatalf("client JSON %s lacks %s", b, k)
}
}
// Defaults.
cc = (&PlannerConfig{Enabled: true}).clientConfig(nil)
if cc.MaxAreaKm != 100 || cc.NodeMarginKm != 30 || cc.MaxLegKm != 100 || len(cc.RangesKm) != len(plannerRangesKm) {
t.Fatalf("default client config %+v", cc)
}
}
func TestPlannerConfigLogSizes(t *testing.T) {
var buf bytes.Buffer
prev, flags := log.Writer(), log.Flags()
log.SetOutput(&buf)
t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) })
logPlannerConfig(&PlannerConfig{Enabled: true, MaxAreaKm: 200, NodeMarginKm: 50, MaxLegKm: 150})
out := buf.String()
for _, want := range []string{
"maxArea=200 km, nodeMargin=50 km, maxLeg=150 km",
"terrain tiles per request: coverage 28, relay 24, profile 24",
"one view takes up to 81 MB (2.9 MB a tile)",
} {
if !strings.Contains(out, want) {
t.Errorf("log lacks %q:\n%s", want, out)
}
}
}
// The handlers apply the operator's sizes: the box limit, the node margin
// (view, fingerprint and node selection), the leg limit and its ranges.
func TestPlannerAPIConfiguredSizes(t *testing.T) {
const ip = "198.51.100.210"
// About 145 × 144 km around the test cluster.
const big = "/api/planner/coverage?bbox=29.5,-97.8,30.8,-96.3"
h := newPlannerHarness(t)
if w := h.get(big, ip); w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrAreaTooLarge) {
t.Fatalf("default size: %d %s", w.Code, w.Body.String())
}
h = newPlannerHarnessWith(t, PlannerConfig{Enabled: true, MaxAreaKm: 200, NodeMarginKm: 50})
// A repeater 40 km north of the box: inside a 50 km margin, not a 30 km one.
h.data.setNodes(append(plannerTestNodes(), nodeInfo{PublicKey: "aa09", Name: "Ridge", Role: "repeater",
Lat: 30.8 + 40/plannerKmPerDeg, Lon: -97.0, HasGPS: true, LastSeen: plannerTestStart}))
if w := h.get(big, ip); w.Code != http.StatusAccepted && w.Code != http.StatusOK {
t.Fatalf("maxAreaKm 200: %d %s", w.Code, w.Body.String())
}
h.waitEntered(t)
area := geoBBox{S: 29.5, W: -97.8, N: 30.8, E: -96.3}
if v := h.src.lastBBox(); v != plannerExpandBBox(area, 50) {
t.Fatalf("view %+v, want the box plus 50 km", v)
}
h.stubs.mu.Lock()
plan := h.stubs.lastPlan
h.stubs.mu.Unlock()
if !slices.ContainsFunc(plan.Nodes, func(n plannerNode) bool { return n.PubKey == "aa09" && !n.InArea }) {
t.Fatalf("plan nodes %+v lack the margin repeater", plan.Nodes)
}
// maxLegKm: a 120 km leg is too long by default and allowed at 150.
const relay120 = "/api/planner/relay?a=30.1,-97.1&b=31.18,-97.1"
const prof120 = "/api/planner/profile?pts=30.1,-97.1,31.18,-97.1"
h = newPlannerHarness(t)
if w := h.get(relay120, ip); w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrTooLong) {
t.Fatalf("default relay 120 km: %d %s", w.Code, w.Body.String())
}
if w := h.get(prof120, ip); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), plannerErrTooLong) {
t.Fatalf("default profile 120 km: %d %s", w.Code, w.Body.String())
}
h = newPlannerHarnessWith(t, PlannerConfig{Enabled: true, MaxLegKm: 150})
h.p.fastWait = plannerFastWait
if w := h.get(relay120, ip); w.Code != http.StatusOK {
t.Fatalf("maxLegKm 150 relay: %d %s", w.Code, w.Body.String())
}
w := h.get(prof120, ip)
var prof PlannerProfileResponse
if err := json.Unmarshal(w.Body.Bytes(), &prof); err != nil || w.Code != http.StatusOK ||
len(prof.Legs) != 1 || prof.Legs[0].Error != "" || len(prof.Legs[0].ElevM) == 0 {
t.Fatalf("maxLegKm 150 profile: %d %s", w.Code, w.Body.String())
}
if v, want := h.src.lastBBox(), plannerProfileView(geoBBox{30.1, -97.1, 31.18, -97.1}, plannerProfilePad(150)); v != want {
t.Fatalf("profile view %+v, want %+v", v, want)
}
// Ranges above maxLegKm are refused, and the default follows them.
h = newPlannerHarnessWith(t, PlannerConfig{Enabled: true, MaxLegKm: 25})
h.p.fastWait = plannerFastWait
for _, path := range []string{plannerRelayPath + "&range=30", plannerCovPath + "&range=30"} {
if w := h.get(path, ip); w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "range must be one of 10,15,20\"") {
t.Fatalf("%s: %d %s", path, w.Code, w.Body.String())
}
}
if w := h.get(plannerRelayPath+"&range=20", ip); w.Code != http.StatusOK {
t.Fatalf("range 20: %d %s", w.Code, w.Body.String())
}
if w := h.get(plannerRelayPath, ip); w.Code != http.StatusOK {
t.Fatalf("default range: %d %s", w.Code, w.Body.String())
}
h.stubs.mu.Lock()
rangeKm := h.stubs.lastRelay.RangeKm
h.stubs.mu.Unlock()
if rangeKm != 20 {
t.Fatalf("default range %v, want 20", rangeKm)
}
}
func TestPlannerUserReachDefaults(t *testing.T) {
for _, c := range []*PlannerConfig{nil, {}, {Enabled: true}} {
r, warns := c.resolved()
if r.UserReach == nil || *r.UserReach != (PlannerUserReach{D50Km: 2.7, Slope: 0.30}) || len(warns) != 0 {
t.Fatalf("%+v: resolved %+v, warnings %q", c, r.UserReach, warns)
}
}
r, warns := (&PlannerConfig{Enabled: true, UserReach: &PlannerUserReach{D50Km: 0.2, Slope: 2}}).resolved()
if *r.UserReach != (PlannerUserReach{D50Km: 0.2, Slope: 2}) || len(warns) != 0 {
t.Fatalf("range ends: resolved %+v, warnings %q", r.UserReach, warns)
}
}
func TestPlannerUserReachOutOfRange(t *testing.T) {
for _, c := range []struct {
in PlannerUserReach
want PlannerUserReach
warn string
}{
{PlannerUserReach{D50Km: 0.1, Slope: 0.4}, PlannerUserReach{D50Km: 2.7, Slope: 0.4}, "planner.userReach.d50Km"},
{PlannerUserReach{D50Km: 3, Slope: 5}, PlannerUserReach{D50Km: 3, Slope: 0.30}, "planner.userReach.slope"},
} {
r, warns := (&PlannerConfig{Enabled: true, UserReach: &c.in}).resolved()
if *r.UserReach != c.want || len(warns) != 1 || !strings.Contains(warns[0], c.warn) {
t.Errorf("%+v: resolved %+v, warnings %q", c.in, r.UserReach, warns)
}
}
}
func TestPlannerClientConfigUserReach(t *testing.T) {
cc := (&PlannerConfig{Enabled: true, UserReach: &PlannerUserReach{D50Km: 4, Slope: 0.5}}).clientConfig(nil)
if cc.UserReach != (PlannerUserReach{D50Km: 4, Slope: 0.5}) {
t.Fatalf("client config %+v", cc.UserReach)
}
if cc := (&PlannerConfig{Enabled: true}).clientConfig(nil); cc.UserReach != (PlannerUserReach{D50Km: 2.7, Slope: 0.30}) {
t.Fatalf("default client config %+v", cc.UserReach)
}
}