Просмотр исходного кода

fix(channelplan): exclude own-mesh BSSIDs and validate channel against width/DFS (#634)

Two fixes to the channel recommendation (#631):

1. Own-mesh BSSIDs no longer count as neighbors. The mesh's own access
   points (the monitored routers' radios) share the first 5 octets with
   the router MAC, so a scan row whose BSSID matches that prefix is now
   excluded from the scoring. Without this, the plan counted the mesh's own
   satellites as interference and could suggest a channel the mesh already
   occupies (self-interference), e.g. recommending ch6 while two satellites
   are already on it.

2. Candidate channels are validated against the radio width and DFS. At
   40/80/160 MHz only channels whose whole block (ch..ch+(n-1)*4) stays
   inside non-DFS channels (52-64, 100-144) and within the band are offered.
   This stops recommending a channel like 44 at 80 MHz, whose block crosses
   into the DFS band.

Tests: TestRecommendExcluyeMallaPropia (own AP on ch1 excluded -> 1 is
free and recommended) and TestRecommendAnchura80NoCruzaDfs (44 not offered
at 80 MHz; 36 wins). Full channelplan + httpapi suites pass.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
1380c1b8a0
2 измененных файлов с 166 добавлено и 8 удалено
  1. 99 8
      server-go/internal/channelplan/store.go
  2. 67 0
      server-go/internal/channelplan/store_test.go

+ 99 - 8
server-go/internal/channelplan/store.go

@@ -125,9 +125,19 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 		return nil, err
 		return nil, err
 	}
 	}
 
 
-	// Agrupar scans por banda y canal.
+	// #631: la malla propia (los APs de los routers monitorizados) NO debe
+	// contarse como "vecino": sus BSSIDs comparten los primeros 5 octetos con
+	// la MAC del router (radios = MAC base, +1, +2...). Se excluyen del
+	// scoring para que la recomendación optimice contra interferencia externa
+	// y no sugiera canales que la propia malla ya ocupa (autointerferencia).
+	ownPrefixes := s.ownMeshPrefixes()
+
+	// Agrupar scans por banda y canal (descartando la propia malla).
 	byBand := map[string]map[int][]ScanRow{}
 	byBand := map[string]map[int][]ScanRow{}
 	for _, sc := range scans {
 	for _, sc := range scans {
+		if isOwnMeshBSSID(sc.BSSID, ownPrefixes) {
+			continue
+		}
 		band := bandForFreq(sc.Freq)
 		band := bandForFreq(sc.Freq)
 		if byBand[band] == nil {
 		if byBand[band] == nil {
 			byBand[band] = map[int][]ScanRow{}
 			byBand[band] = map[int][]ScanRow{}
@@ -152,7 +162,7 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 		if rec.Iface == "" {
 		if rec.Iface == "" {
 			rec.Iface = ifaceForBand(band) // placeholder; el agente no reporta iface por radio
 			rec.Iface = ifaceForBand(band) // placeholder; el agente no reporta iface por radio
 		}
 		}
-		candidates := candidateChannels(band)
+		candidates := candidateChannels(band, r.WidthMhz)
 		bestCh, bestScore := 0, math.MaxInt
 		bestCh, bestScore := 0, math.MaxInt
 		currentScore := math.MaxInt
 		currentScore := math.MaxInt
 		for _, ch := range candidates {
 		for _, ch := range candidates {
@@ -203,17 +213,98 @@ func channelScore(scans map[int][]ScanRow, channel int) int {
 	return int(score)
 	return int(score)
 }
 }
 
 
-func candidateChannels(band string) []int {
+// candidateChannels devuelve los canales candidatos no-DFS para la banda,
+// filtrando por el ancho del radio (#631): a 40/80/160 MHz solo valen los
+// canales cuyo bloque completo (canales ch..ch+(n-1)*4, n=w/20) no entra en
+// un canal DFS (52-64, 100-144) ni se sale de la banda.
+func candidateChannels(band string, widthMhz int) []int {
+	var base []int
 	switch band {
 	switch band {
 	case "2.4 GHz":
 	case "2.4 GHz":
-		return []int{1, 6, 11}
+		base = []int{1, 6, 11}
 	case "5 GHz":
 	case "5 GHz":
-		// UNII-1/2/3 canales no-DFS preferidos para uso doméstico.
-		return []int{36, 40, 44, 48, 149, 153, 157, 161, 165}
+		// UNII-1/3 canales no-DFS preferidos para uso doméstico.
+		base = []int{36, 40, 44, 48, 149, 153, 157, 161, 165}
 	case "6 GHz":
 	case "6 GHz":
-		return []int{1, 5, 9, 13, 17, 21, 25, 29}
+		base = []int{1, 5, 9, 13, 17, 21, 25, 29}
+	default:
+		return nil
+	}
+	if widthMhz <= 20 {
+		return base
+	}
+	out := make([]int, 0, len(base))
+	for _, ch := range base {
+		if validForWidth(ch, widthMhz, band) {
+			out = append(out, ch)
+		}
+	}
+	return out
+}
+
+// validForWidth indica si un canal al ancho dado ocupa un bloque fuera de
+// canales DFS (5 GHz) y dentro de la banda.
+func validForWidth(ch, widthMhz int, band string) bool {
+	if band != "5 GHz" {
+		// 2.4 y 6 GHz no tienen canales DFS en el ámbito doméstico.
+		return true
+	}
+	n := widthMhz / 20 // 1,2,4,8 para 20/40/80/160
+	if n < 1 {
+		n = 1
+	}
+	for i := 0; i < n; i++ {
+		cc := ch + i*4
+		if cc > 165 || isDFSChannel(cc) {
+			return false
+		}
+	}
+	return true
+}
+
+// isDFSChannel: canales que en ETSI/EU requieren detección DFS (radio no
+// puede usarlos sin radar) — UNII-2A (52-64) y UNII-2C (100-144).
+func isDFSChannel(ch int) bool {
+	return (ch >= 52 && ch <= 64) || (ch >= 100 && ch <= 144)
+}
+
+// ownMeshPrefixes devuelve los primeros 5 octetos de la MAC de cada router
+// monitorizado (tabla routers). Un BSSID cuyo prefijo coincida es un AP de la
+// propia malla y no debe computarse como vecino (#631).
+func (s *Store) ownMeshPrefixes() []string {
+	var out []string
+	if s.db == nil {
+		return out
+	}
+	rows, err := s.db.Query(`SELECT mac FROM routers WHERE mac IS NOT NULL AND mac <> ''`)
+	if err != nil {
+		return out
+	}
+	defer rows.Close()
+	for rows.Next() {
+		var mac string
+		if rows.Scan(&mac) == nil {
+			mac = strings.ToUpper(strings.TrimSpace(mac))
+			if len(mac) >= 14 {
+				out = append(out, mac[:14]) // "AA:BB:CC:DD:EE"
+			}
+		}
+	}
+	return out
+}
+
+func isOwnMeshBSSID(bssid string, prefixes []string) bool {
+	b := strings.ToUpper(strings.TrimSpace(bssid))
+	if len(b) < 14 {
+		return false
+	}
+	pref := b[:14]
+	for _, p := range prefixes {
+		if p == pref {
+			return true
+		}
 	}
 	}
-	return nil
+	return false
 }
 }
 
 
 func bandForFreq(freq int) string {
 func bandForFreq(freq int) string {

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

@@ -151,6 +151,73 @@ func TestPrune(t *testing.T) {
 	}
 	}
 }
 }
 
 
+// TestRecommendExcluyeMallaPropia (#631): un AP de la propia malla (BSSID que
+// comparte los 5 primeros octetos con la MAC de un router monitorizado) no
+// debe puntuar como vecino, así el canal que ocupa queda libre para
+// recomendarlo.
+func TestRecommendExcluyeMallaPropia(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+	if _, err := d.DB.Exec(`INSERT INTO routers (id, name, host, type, mac, is_gateway, created_at)
+		VALUES ('rt2', 'RT2 AX6', '192.168.1.2', 'openwrt', '8C:DE:F9:33:71:58', 0, ?)`,
+		time.Now().UnixMilli()); err != nil {
+		t.Fatalf("insert router: %v", err)
+	}
+
+	st := channelplan.NewStore(d.DB)
+	now := time.Now().Unix()
+	// La propia malla (prefijo 8C:DE:F9:33:71) ocupa el canal 1 con señal
+	// fortísima (-30); sin la exclusión penalizaría el 1 y recomendaría 6/11.
+	scans := []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "8C:DE:F9:33:71:59", SSID: "temiscira", Channel: 1, Freq: 2412, Signal: -30},
+	}
+	if err := st.SaveScan("rt1", now, scans); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+
+	recs, err := st.Recommend("rt1", []probe.Radio{{Name: "2.4 GHz", Channel: 1, WidthMhz: 20}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	if len(recs) != 1 {
+		t.Fatalf("esperaba 1 radio, got %d", len(recs))
+	}
+	// Con el AP propio excluido, el canal 1 (ocupado solo por la malla) queda
+	// libre y es el primero de la lista no-DFS (1,6,11) con score 0.
+	if recs[0].Recommended != 1 {
+		t.Fatalf("la propia malla debería excluirse y dejar libre el 1, got %d", recs[0].Recommended)
+	}
+}
+
+// TestRecommendAnchura80NoCruzaDfs (#631): a 80 MHz el canal 44 ocupa el
+// bloque 44-56 que entra en canales DFS (52+), así que no debe ofrecerse como
+// candidato; se recomienda el 36, único bloque UNII-1 no-DFS a ese ancho.
+func TestRecommendAnchura80NoCruzaDfs(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)
+	recs, err := st.Recommend("rt1", []probe.Radio{{Name: "5 GHz", Channel: 44, WidthMhz: 80}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	if len(recs) != 1 {
+		t.Fatalf("esperaba 1 radio, got %d", len(recs))
+	}
+	if recs[0].Recommended == 44 {
+		t.Fatalf("a 80 MHz el 44 cruza a DFS y no debe recomendarse: %+v", recs[0])
+	}
+	if recs[0].Recommended != 36 {
+		t.Fatalf("a 80 MHz solo el bloque 36-48 es no-DFS: got %d", recs[0].Recommended)
+	}
+}
+
 func TestRecommendPasaSeccion(t *testing.T) {
 func TestRecommendPasaSeccion(t *testing.T) {
 	d, err := db.Open(t.TempDir())
 	d, err := db.Open(t.TempDir())
 	if err != nil {
 	if err != nil {