فهرست منبع

fix: channel plan end to end (store wiring, freq parse, dedup, router id resolution) (#479)

* fix(server): wire the channelplan store in main and prune wifi scans

The channel plan endpoint and store were complete but main never passed
the store in Deps, so the route was never registered (the page showed
not_found) and the ingest silently dropped every scan: wifi_scans stayed
empty in production. Wire it like the other stores and run Store.Prune
on a ticker (48h retention, sweep every 6h) so the table does not grow
unbounded now that scans actually persist.

Closes #475

* chore: drop the bare 'netpulse' gitignore rule that hid cmd/netpulse

* fix(agent): parse iw scan freq as float instead of integer

Real iw output prints "freq: 5260.0"; Atoi failed silently, Freq stayed 0
and the flush discarded every BSS, so pushes always carried scans: []
and the channel plan had no data to work with. Test now covers the
float format captured from a real router.

Closes #475 (with the server-side wiring)

* fix(channelplan): dedup neighbors by BSSID and null-safe radios/scans in the UI

Every agent push reinserted the same neighbors, so RecentScans returned
one row per push: the score summed each AP hundreds of times until the
int overflowed (MaxInt64 recommendations) and the neighbors table was
noise. Group by BSSID keeping the most recent observation. The page also
crashed with a TypeError when the endpoint returned null radios/scans
(routers without a fresh wireless payload, switches included).

Closes #475

* fix(channelplan): resolve the overview router id to the agent slug

The page sends the overview id of the router (hostname or friendly
name, flint2/rt2) while scans and the fresh payload live under the
agent slug (gateway/redmi-ax6), so every lookup came back empty. Match
slug directly, then board hostname from the last payload, then the
routers table via resolveAgentRouter.

Closes #475

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 ماه پیش
والد
کامیت
73ea1f4d0b

+ 3 - 3
.gitignore

@@ -15,9 +15,9 @@ legacy/server-node/.env
 .DS_Store
 
 # Binarios compilados
-# (solo el binario local de `go build` en el módulo agent; el patrón `netpulse-agent*`
-# coincidía con el directorio fuente agent/cmd/netpulse-agent/ e ignoraba su código)
-netpulse
+# (ancla los patrones a su ruta: el patrón libre `netpulse` ignoraba el
+# directorio FUENTE server-go/cmd/netpulse/ y bloqueaba `git add` de main.go,
+# igual que `netpulse-agent*` hizo con agent/cmd/netpulse-agent/)
 # anclado a la raíz: el patrón libre `netpulse-agent` también ignoraba el
 # directorio deploy/openwrt/netpulse-agent/ (ficheros del paquete)
 /netpulse-agent

+ 6 - 2
agent/probe/probe.go

@@ -1137,8 +1137,12 @@ func ParseScan(out string) []ScanResult {
 			continue
 		}
 		if strings.HasPrefix(line, "freq:") {
-			v, _ := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, "freq:")))
-			current.Freq = v
+			// iw imprime la frecuencia como float ("freq: 5260.0"): Atoi
+			// fallaba en silencio, Freq quedaba 0 y el flush descartaba TODOS
+			// los BSS (scans siempre vacíos, #475).
+			if f, err := strconv.ParseFloat(strings.TrimSpace(strings.TrimPrefix(line, "freq:")), 64); err == nil {
+				current.Freq = int(f)
+			}
 			continue
 		}
 		if strings.HasPrefix(line, "signal:") {

+ 27 - 0
agent/probe/probe_test.go

@@ -873,6 +873,33 @@ BSS 11:22:33:44:55:66(on wlan1)
 	}
 }
 
+// TestParseScanFreqFloat (#475): iw real imprime "freq: 5260.0"; con Atoi el
+// error se tragaba, Freq quedaba 0 y el flush descartaba todos los BSS.
+func TestParseScanFreqFloat(t *testing.T) {
+	out := `==IFACE==wlan1
+BSS 9c:9d:7e:1b:ea:b3(on wlan1)
+	last seen: 945720.058s [boottime]
+	TSF: 419753678847 usec (4d, 20:35:53)
+	freq: 5260.0
+	signal: -61.00 dBm
+	SSID: vecino-dfs
+BSS 8c:de:f9:33:71:59(on wlan1)
+	freq: 5180.0
+	signal: -72.00 dBm
+	SSID: 
+`
+	got := ParseScan(out)
+	if len(got) != 2 {
+		t.Fatalf("esperaba 2 resultados, got %d: %+v", len(got), got)
+	}
+	if got[0].Freq != 5260 || got[0].Channel != 52 || got[0].Signal != -61 {
+		t.Errorf("primer scan incorrecto: %+v", got[0])
+	}
+	if got[1].Freq != 5180 || got[1].Channel != 36 || got[1].SSID != "" {
+		t.Errorf("segundo scan incorrecto: %+v", got[1])
+	}
+}
+
 func TestParseScanVacio(t *testing.T) {
 	if got := ParseScan(""); len(got) != 0 {
 		t.Fatalf("esperaba [] vacío, got %d", len(got))

+ 1 - 1
app/src/pages/ChannelPlan.tsx

@@ -64,7 +64,7 @@ export default function ChannelPlan() {
         if (!res.ok) throw new Error(await res.text())
         return res.json()
       })
-      .then((d) => setData(d))
+      .then((d) => setData({ ...d, radios: d.radios ?? [], scans: d.scans ?? [] }))
       .catch((e) => setError(String(e)))
       .finally(() => setLoading(false))
   }, [routerId])

+ 26 - 0
server-go/cmd/netpulse/main.go

@@ -33,6 +33,7 @@ import (
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/agentbin"
+	"github.com/gnacho/netpulse/server-go/internal/channelplan"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/apitoken"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
@@ -224,6 +225,14 @@ func run() error {
 	}
 	fwStore := firmware.NewStore(dbHandle.DB)
 
+	// Channel plan (#452/#475): la tabla wifi_scans la crea db.Open; el store
+	// la envuelve. Sin esto la ruta /api/wifi/channel-plan nunca se registra
+	// (not_found en la UI) y la ingesta descarta los scans en silencio.
+	chPlan := channelplan.NewStore(dbHandle.DB)
+	// Los scans llegan con cada push de cada agente y las consultas miran
+	// 24h: sin purga la tabla crecería sin límite. Retención 48h, barrido 6h.
+	go pruneWifiScans(chPlan)
+
 	// Clave SSH propia para sondear routers (se genera la primera vez)
 	if err := sshkey.EnsureKeypair(cfg.SSHKeyPath); err != nil {
 		log.Printf("[netpulse] aviso: no se pudo generar la clave SSH: %v", err)
@@ -461,6 +470,7 @@ func run() error {
 		PathAnalysis:    pathStore,
 		ConfigBackup:    cfgBackup,
 		Firmware:        fwStore,
+		ChannelPlan:     chPlan,
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},
@@ -616,3 +626,19 @@ func (a *mainKVAdapter) Set(key, value string) error {
 		key, value)
 	return err
 }
+
+// pruneWifiScans purga los scans de vecinos más allá de la retención (#475).
+// Corre en su propia goroutine: un barrido al arrancar y luego cada 6h.
+func pruneWifiScans(store *channelplan.Store) {
+	const retention = 48 * time.Hour
+	if err := store.Prune(retention); err != nil {
+		log.Printf("[netpulse] aviso: purge inicial de wifi_scans: %v", err)
+	}
+	ticker := time.NewTicker(6 * time.Hour)
+	defer ticker.Stop()
+	for range ticker.C {
+		if err := store.Prune(retention); err != nil {
+			log.Printf("[netpulse] aviso: purge de wifi_scans: %v", err)
+		}
+	}
+}

+ 13 - 6
server-go/internal/channelplan/store.go

@@ -59,25 +59,32 @@ type ScanRow struct {
 	RouterID string `json:"routerId"`
 }
 
-// RecentScans devuelve los scans recientes de todos los routers (opcionalmente
-// filtrado por routerID) dentro de la ventana de frescura.
+// RecentScans devuelve los vecinos vistos recientemente (opcionalmente
+// filtrado por routerID) dentro de la ventana de fresividad, DEDUPLICADOS por
+// BSSID: cada push del agente reinserta los mismos vecinos, y sin dedup el
+// mismo AP contaba una vez por push (decenas de miles de filas al día),
+// reventaba el score (overflow) y la tabla de vecinos era puro ruido.
+// SQLite: con un único agregado MAX(ts), las columnas "bare" salen de la
+// fila del máximo (https://sqlite.org/lang_select.html#bareagg).
 func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, error) {
 	cutoff := time.Now().Add(-within).Unix()
 	var rows *sql.Rows
 	var err error
 	if routerID != "" {
 		rows, err = s.db.Query(`
-			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, ts
+			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, MAX(ts)
 			FROM wifi_scans
 			WHERE router_id = ? AND ts >= ?
-			ORDER BY ts DESC, signal_dbm ASC
+			GROUP BY bssid
+			ORDER BY signal_dbm ASC, bssid
 		`, routerID, cutoff)
 	} else {
 		rows, err = s.db.Query(`
-			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, ts
+			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, MAX(ts)
 			FROM wifi_scans
 			WHERE ts >= ?
-			ORDER BY ts DESC, signal_dbm ASC
+			GROUP BY router_id, bssid
+			ORDER BY signal_dbm ASC, bssid
 		`, cutoff)
 	}
 	if err != nil {

+ 40 - 0
server-go/internal/channelplan/store_test.go

@@ -36,6 +36,46 @@ func TestSaveAndRecentScans(t *testing.T) {
 	}
 }
 
+// TestRecentScansDedupBSSID (#475): cada push reinserta los vecinos; la
+// lectura debe devolver UNA fila por BSSID (la observación más reciente).
+func TestRecentScansDedupBSSID(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	now := time.Now().Unix()
+	// Push 1: vecino A (-70) y vecino B (-50).
+	if err := st.SaveScan("rt1", now-60, []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "AA:AA:AA:AA:AA:01", SSID: "a", Channel: 1, Freq: 2412, Signal: -70},
+		{Iface: "wlan0", BSSID: "BB:BB:BB:BB:BB:02", SSID: "b", Channel: 6, Freq: 2437, Signal: -50},
+	}); err != nil {
+		t.Fatalf("save1: %v", err)
+	}
+	// Push 2 (30 s después): el vecino A ahora se oye más fuerte (-55).
+	if err := st.SaveScan("rt1", now-30, []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "AA:AA:AA:AA:AA:01", SSID: "a", Channel: 1, Freq: 2412, Signal: -55},
+		{Iface: "wlan0", BSSID: "BB:BB:BB:BB:BB:02", SSID: "b", Channel: 6, Freq: 2437, Signal: -50},
+	}); err != nil {
+		t.Fatalf("save2: %v", err)
+	}
+
+	got, err := st.RecentScans("rt1", time.Hour)
+	if err != nil {
+		t.Fatalf("recent: %v", err)
+	}
+	if len(got) != 2 {
+		t.Fatalf("esperaba 2 vecinos dedup, got %d: %+v", len(got), got)
+	}
+	for _, r := range got {
+		if r.BSSID == "AA:AA:AA:AA:AA:01" && r.Signal != -55 {
+			t.Errorf("el vecino A debe reportar la señal MÁS RECIENTE (-55), got %d", r.Signal)
+		}
+	}
+}
+
 func TestRecommendPrefiereCanalLibre(t *testing.T) {
 	d, err := db.Open(t.TempDir())
 	if err != nil {

+ 60 - 3
server-go/internal/httpapi/wifi_channelplan.go

@@ -2,6 +2,7 @@ package httpapi
 
 import (
 	"net/http"
+	"strings"
 	"time"
 
 	"github.com/gnacho/netpulse/agent/probe"
@@ -14,26 +15,82 @@ func (s *server) registerChannelPlanRoutes(mux *http.ServeMux) {
 		return
 	}
 
+	// agentSlugForRouter resuelve la clave que usa la UI (el id del router
+	// en el overview: hostname o nombre amigable) al slug del agente bajo el
+	// que viven Fresh() y wifi_scans (#475): la flota manda flint2/rt2 y los
+	// agentes se llaman gateway/redmi-ax6. Tres capas: slug directo,
+	// hostname del board del último payload, e id/nombre de la tabla routers
+	// resuelto con resolveAgentRouter.
+	agentSlugForRouter := func(routerID string) string {
+		norm := func(v string) string { return strings.ToLower(strings.TrimSpace(v)) }
+		routerByID := map[string]routerIdentity{}
+		slugs := []string{}
+		if s.db != nil {
+			if rows, err := s.db.Query("SELECT id, type, name, host, COALESCE(mac,'') FROM routers"); err == nil {
+				for rows.Next() {
+					var id, typ, name, host, mac string
+					if rows.Scan(&id, &typ, &name, &host, &mac) == nil {
+						routerByID[id] = routerIdentity{ID: id, Type: typ, Name: name, Host: host, Mac: mac}
+					}
+				}
+				rows.Close()
+			}
+			if rows, err := s.db.Query("SELECT key FROM kv WHERE key LIKE ?", agentTokenKeyPrefix+"%"); err == nil {
+				for rows.Next() {
+					var key string
+					if rows.Scan(&key) == nil {
+						slugs = append(slugs, strings.TrimPrefix(key, agentTokenKeyPrefix))
+					}
+				}
+				rows.Close()
+			}
+		}
+		want := norm(routerID)
+		for _, slug := range slugs {
+			if slug == routerID {
+				return slug
+			}
+			var payload *probe.Payload
+			if s.agents != nil {
+				if st := s.agents.Snapshot(slug); st != nil {
+					payload = st.Payload
+				}
+			}
+			if payload != nil && payload.Data.System != nil && payload.Data.System.Board != nil {
+				if norm(payload.Data.System.Board.Hostname) == want {
+					return slug
+				}
+			}
+			if id := resolveAgentRouter(slug, payload, routerByID); id != "" {
+				if id == routerID || norm(routerByID[id].Name) == want || norm(routerByID[id].Host) == want {
+					return slug
+				}
+			}
+		}
+		return routerID
+	}
+
 	mux.Handle("GET /api/wifi/channel-plan", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		routerID := r.URL.Query().Get("routerId")
 		if routerID == "" {
 			writeError(w, http.StatusBadRequest, "invalid_body", "routerId requerido")
 			return
 		}
+		slug := agentSlugForRouter(routerID)
 
 		var radios []probe.Radio
 		if s.agents != nil {
-			if payload, ok := s.agents.Fresh(routerID); ok && payload.Data.Wireless != nil {
+			if payload, ok := s.agents.Fresh(slug); ok && payload.Data.Wireless != nil {
 				radios = payload.Data.Wireless.Radios
 			}
 		}
 
-		recommendations, err := s.channelPlan.Recommend(routerID, radios, 24*time.Hour)
+		recommendations, err := s.channelPlan.Recommend(slug, radios, 24*time.Hour)
 		if err != nil {
 			writeError(w, http.StatusInternalServerError, "channel_plan_error")
 			return
 		}
-		scans, err := s.channelPlan.RecentScans(routerID, 24*time.Hour)
+		scans, err := s.channelPlan.RecentScans(slug, 24*time.Hour)
 		if err != nil {
 			writeError(w, http.StatusInternalServerError, "channel_plan_error")
 			return