Browse Source

feat(agent): report own BSSIDs and neighbor channel width (#1088)

- The agent parses its own AP interfaces from plain phy#0
	Interface wlan0
		ifindex 3
		wdev 0x1
		addr 62:e5:56:b6:94:bd
		type managed
		multicast TXQ:
			qsz-byt	qsz-pkt	flows	drops	marks	overlmt	hashcol	tx-bytes	tx-packets
			0	0	0	0	0	0	0	0		0 (iface, addr,
  ssid, type) and ships them in wireless.ownBssids. The server feeds them
  to the channel-plan own detection as exact seeds, closing the gaps where
  MAC prefixes and SSID transitivity cannot help: units with randomized
  BSSIDs and guest networks that dawn/usteer do not steer.
- ParseScan now reads the HT/VHT operation blocks of each BSS (secondary
  channel offset, channel width) into ScanResult.WidthMhz, and the server
  persists it in a new wifi_scans.width_mhz column (migrated, default 0).
  The spectrum draws each neighbor at its advertised width instead of the
  fixed 20 MHz fallback, and the heat strip and the table use it too.
- Agent version bump to 3.0.6. Both fields are additive: old agents and
  old rows keep the fallbacks.

closes #1087
Nacho 2 months ago
parent
commit
ff3c4ca132

+ 4 - 0
agent/probe/local.go

@@ -417,6 +417,10 @@ func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
 				wd.Scans = ParseScan(out)
 			}
 		}
+		// BSSIDs propios (#1087): `iw dev` sin scan, barato y estable.
+		if out := p.runBest(ctx, CmdIwDev, 5*time.Second); out != "" {
+			wd.OwnBssids = ParseIwDev(out)
+		}
 	} else {
 		p.radiosMu.Lock()
 		cached := p.radiosCache

+ 16 - 0
agent/probe/payload.go

@@ -113,6 +113,18 @@ type WirelessData struct {
 	// Scans: redes vecinas vistas por cada interfaz WiFi (Fase 18/#452).
 	// nil/ausente = el scan no se pudo realizar en este push.
 	Scans []ScanResult `json:"scans,omitempty"`
+	// OwnBssids: BSSIDs de las interfaces AP de ESTE equipo (#1087), de
+	// `iw dev`. El server los usa de semilla exacta para no contar las
+	// propias redes como vecinas (casos con MAC aleatorizada o guest cuya
+	// MAC no casa con routers.mac). nil con agentes antiguos.
+	OwnBssids []OwnBSSID `json:"ownBssids,omitempty"`
+}
+
+// OwnBSSID: una interfaz AP local con su BSSID y SSID (#1087).
+type OwnBSSID struct {
+	Iface  string `json:"iface"`
+	BSSID  string `json:"bssid"` // MAC en mayúsculas
+	SSID   string `json:"ssid"`  // puede estar vacío
 }
 
 // ScanResult es un AP vecino detectado por un scan pasivo.
@@ -123,6 +135,10 @@ type ScanResult struct {
 	Channel int    `json:"channel"` // canal numérico
 	Freq    int    `json:"freq"`    // frecuencia en MHz
 	Signal  int    `json:"signal"`  // dBm (negativo)
+	// WidthMhz: ancho de canal anunciado (HT/VHT operation del scan, #1087).
+	// 0 con agentes antiguos o BSS sin esos bloques: la UI usa 20 MHz de
+	// fallback en ese caso.
+	WidthMhz int `json:"widthMhz,omitempty"`
 }
 
 // DHCPData: leases ipv4 (mac en mayúsculas) + clientes GL.iNet.

+ 86 - 0
agent/probe/probe.go

@@ -84,6 +84,10 @@ const (
 	// emite "==IFACE==<iface>" antes de cada scan y parsea BSS/freq/signal/SSID.
 	// Si `iw` no está disponible, la sección Scans queda vacía (best-effort).
 	CmdScan = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" scan 2>/dev/null; done`
+	// CmdIwDev (#1087): `iw dev` a secas, sin scan. Lista las interfaces con
+	// su MAC y SSID: fuente de los BSSIDs propios para el análisis de
+	// canales. Barato (no saca la radio del canal).
+	CmdIwDev = "iw dev 2>/dev/null"
 	// CmdRadioSections (#500): secciones wifi-device de UCI con su banda, para
 	// resolver "2.4 GHz" → radio0 (la relación iface→sección no sale de iwinfo).
 	CmdRadioSections = `uci -q show wireless 2>/dev/null | grep -E "=wifi-device$|\.band=|\.hwmode="`
@@ -1492,10 +1496,21 @@ func ParseScan(out string) []ScanResult {
 	var res []ScanResult
 	iface := ""
 	var current *ScanResult
+	// Estado del bloque HT/VHT en curso para el ancho de canal (#1087).
+	section := ""
+	ht40, vhtWidth := false, 0
 	flush := func() {
 		if current != nil && current.BSSID != "" && current.Freq > 0 {
 			current.Channel = FreqToChannel(current.Freq)
 			if current.Channel > 0 {
+				switch {
+				case vhtWidth > 0:
+					current.WidthMhz = vhtWidth
+				case ht40:
+					current.WidthMhz = 40
+				default:
+					current.WidthMhz = 20
+				}
 				res = append(res, *current)
 			}
 		}
@@ -1516,11 +1531,43 @@ func ParseScan(out string) []ScanResult {
 			}
 			bssid := strings.ToUpper(strings.Split(fields[1], "(")[0])
 			current = &ScanResult{Iface: iface, BSSID: bssid}
+			section, ht40, vhtWidth = "", false, 0
 			continue
 		}
 		if current == nil {
 			continue
 		}
+		// Ancho de canal anunciado por el vecino (#1087): HT operation da
+		// el salto de 40 MHz; VHT operation el de 80/160.
+		switch {
+		case strings.HasPrefix(line, "HT operation:"):
+			section = "ht"
+			continue
+		case strings.HasPrefix(line, "VHT operation:"):
+			section = "vht"
+			continue
+		case strings.HasPrefix(line, "HE operation:") || strings.HasPrefix(line, "EHT operation:"):
+			section = ""
+			continue
+		}
+		if section == "ht" && strings.Contains(line, "secondary channel offset:") {
+			ht40 = !strings.Contains(line, "no secondary")
+			continue
+		}
+		if section == "vht" && strings.Contains(line, "channel width:") {
+			// "* channel width: 1 (80 MHz)": 1 = 80 MHz, 2 = 160 MHz.
+			re := vhtWidthRe.FindStringSubmatch(line)
+			if re != nil {
+				n, _ := strconv.Atoi(re[1])
+				switch n {
+				case 1:
+					vhtWidth = 80
+				case 2:
+					vhtWidth = 160
+				}
+			}
+			continue
+		}
 		if strings.HasPrefix(line, "freq:") {
 			// iw imprime la frecuencia como float ("freq: 5260.0"): Atoi
 			// fallaba en silencio, Freq quedaba 0 y el flush descartaba TODOS
@@ -1544,6 +1591,45 @@ func ParseScan(out string) []ScanResult {
 	return res
 }
 
+var vhtWidthRe = regexp.MustCompile(`channel width:\s*(\d)\s*\(`)
+
+// ParseIwDev parsea la salida de CmdIwDev (`iw dev`) y devuelve las
+// interfaces AP de ESTE equipo con su BSSID y SSID (#1087). Los bloques
+// "Interface <name>" traen addr, ssid y type; solo type AP interesa (los
+// STA/clientes managed no son red propia).
+func ParseIwDev(out string) []OwnBSSID {
+	var res []OwnBSSID
+	iface, addr, ssid, ifType := "", "", "", ""
+	flush := func() {
+		if iface != "" && addr != "" && ifType == "AP" {
+			res = append(res, OwnBSSID{Iface: iface, BSSID: strings.ToUpper(addr), SSID: ssid})
+		}
+	}
+	for _, raw := range strings.Split(out, "\n") {
+		line := strings.TrimSpace(raw)
+		fields := strings.Fields(line)
+		if len(fields) >= 2 && fields[0] == "Interface" {
+			flush()
+			iface, addr, ssid, ifType = fields[1], "", "", ""
+			continue
+		}
+		if len(fields) >= 2 && fields[0] == "addr" {
+			addr = fields[1]
+			continue
+		}
+		if len(fields) >= 2 && fields[0] == "ssid" {
+			ssid = strings.TrimSpace(strings.TrimPrefix(line, "ssid"))
+			continue
+		}
+		if len(fields) >= 2 && fields[0] == "type" {
+			ifType = fields[1]
+			continue
+		}
+	}
+	flush()
+	return res
+}
+
 // FreqToChannel convierte frecuencia (MHz) a número de canal 802.11.
 func FreqToChannel(freq int) int {
 	switch {

+ 88 - 0
agent/probe/probe_test.go

@@ -936,6 +936,94 @@ func TestParseUsteer(t *testing.T) {
 }
 
 // TestParseScanExtraeVecinos (#452): parsea la salida de `iw dev` scan.
+func TestParseScanWidthMhz(t *testing.T) {
+	// Bloques HT/VHT reales de `iw dev wlan0 scan` (OpenWrt).
+	out := `==IFACE==wlan0
+BSS 11:22:33:44:55:66(on wlan0)
+	freq: 2437
+	signal: -55.00 dBm
+	SSID: ochenta
+	HT operation:
+		 * primary channel: 6
+		 * secondary channel offset: below
+	VHT operation:
+		 * channel width: 1 (80 MHz)
+BSS aa:bb:cc:dd:ee:ff(on wlan0)
+	freq: 2462
+	signal: -70.00 dBm
+	SSID: cuarenta
+	HT operation:
+		 * primary channel: 11
+		 * secondary channel offset: above
+BSS 22:33:44:55:66:77(on wlan0)
+	freq: 2412
+	signal: -80.00 dBm
+	SSID: veinte
+	HT operation:
+		 * primary channel: 1
+		 * secondary channel offset: no secondary
+BSS 33:44:55:66:77:88(on wlan0)
+	freq: 5500
+	signal: -60.00 dBm
+	SSID: ciento60
+	HT operation:
+		 * primary channel: 100
+		 * secondary channel offset: below
+	VHT operation:
+		 * channel width: 2 (160 MHz)
+`
+	got := ParseScan(out)
+	widths := map[string]int{}
+	for _, s := range got {
+		widths[s.SSID] = s.WidthMhz
+	}
+	if widths["ochenta"] != 80 || widths["cuarenta"] != 40 || widths["veinte"] != 20 || widths["ciento60"] != 160 {
+		t.Fatalf("anchos inesperados: %+v de %+v", widths, got)
+	}
+}
+
+func TestParseIwDev(t *testing.T) {
+	out := `phy#0
+	Interface wlan0
+		ifindex 12
+		wdev 0x200000000
+		addr 62:e5:56:b6:94:bd
+		ssid temiscira
+		type AP
+		channel 6 (2437 MHz), width: 80 MHz, center1: 2437 MHz
+		txpower 20.00 dBm
+	Interface wlan0-1
+		ifindex 13
+		wdev 0x200000001
+		addr 6a:e5:56:b6:94:bd
+		ssid temiscira-guest
+		type AP
+		channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz
+	Interface wlan1
+		ifindex 14
+		wdev 0x200000002
+		addr 62:e5:56:b6:94:be
+		ssid temiscira
+		type AP
+		channel 36 (5180 MHz), width: 80 MHz, center1: 5210 MHz
+phy#1
+	Interface uap0
+		ifindex 20
+		addr 62:e5:56:b6:94:bf
+		type managed
+`
+	got := ParseIwDev(out)
+	if len(got) != 3 {
+		t.Fatalf("esperaba 3 APs (uap0 managed fuera): %+v", got)
+	}
+	if got[0].BSSID != "62:E5:56:B6:94:BD" || got[0].SSID != "temiscira" || got[0].Iface != "wlan0" {
+		t.Fatalf("bloque 0 mal parseado: %+v", got[0])
+	}
+	if got[1].SSID != "temiscira-guest" {
+		t.Fatalf("guest sin capturar: %+v", got[1])
+	}
+}
+
 func TestParseScanExtraeVecinos(t *testing.T) {
 	out := `==IFACE==wlan0
 BSS 00:11:22:33:44:55(on wlan0)

+ 2 - 1
app/public/locales/en/translation.json

@@ -2043,7 +2043,8 @@
     "onlyMine": "Only mine",
     "legendDfs": "DFS range (radar)",
     "legendSuggested": "Suggested block",
-    "legendCurrent": "Your channel"
+    "legendCurrent": "Your channel",
+    "heatNoteKnown": "real widths from each neighbor HT/VHT advertisements"
   },
   "firmwareUpgrades": {
     "title": "Firmware upgrades",

+ 2 - 1
app/public/locales/es/translation.json

@@ -2043,7 +2043,8 @@
     "onlyMine": "Solo mías",
     "legendDfs": "Zona DFS (radar)",
     "legendSuggested": "Bloque sugerido",
-    "legendCurrent": "Tu canal"
+    "legendCurrent": "Tu canal",
+    "heatNoteKnown": "anchos reales de los anuncios HT/VHT de cada vecina"
   },
   "firmwareUpgrades": {
     "title": "Actualizaciones de firmware",

+ 17 - 4
app/src/pages/ChannelPlan.tsx

@@ -29,6 +29,7 @@ interface Scan {
   channel: number
   freq: number
   signal: number
+  widthMhz?: number
   routerId: string
   ts?: number
   own?: boolean
@@ -246,7 +247,9 @@ export default function ChannelPlan() {
       channel: s.channel,
       freq: s.freq,
       signal: s.signal,
-      widthMhz: 20,
+      // Ancho real del anuncio HT/VHT del vecino (#1087); 20 MHz de
+      // fallback cuando el agente viejo/no lo trae.
+      widthMhz: s.widthMhz && s.widthMhz > 0 ? s.widthMhz : 20,
       own: s.own ?? false,
       color: s.own ? themeColor('--accent') : ssidColor(s.ssid || s.bssid),
     }))
@@ -651,7 +654,9 @@ export default function ChannelPlan() {
                     <div className="mb-1.5 flex items-center gap-2">
                       <span className="text-label uppercase text-text-muted">{t('channelPlan.heatTitle')}</span>
                       <span className="ml-auto text-caption font-normal normal-case tracking-normal text-text-muted">
-                        {t('channelPlan.heatNote')}
+                        {bandScans.some((s) => !s.own && !(s.widthMhz && s.widthMhz > 0))
+                          ? t('channelPlan.heatNote')
+                          : t('channelPlan.heatNoteKnown')}
                       </span>
                     </div>
                     <div className="flex justify-between text-[10.5px] text-text-muted">
@@ -856,9 +861,17 @@ export default function ChannelPlan() {
                               </td>
                               <td className="px-3 py-2.5 font-mono font-bold text-text-primary">{s.channel}</td>
                               <td className="px-3 py-2.5">
-                                {s.own && active.widthMhz > 0 ? (
+                                {s.own ? (
+                                  active.widthMhz > 0 ? (
+                                    <span className="rounded-md bg-elevated px-2 py-0.5 text-[11px] font-bold text-text-secondary">
+                                      {active.widthMhz} MHz
+                                    </span>
+                                  ) : (
+                                    <span className="text-text-muted">—</span>
+                                  )
+                                ) : s.widthMhz && s.widthMhz > 0 ? (
                                   <span className="rounded-md bg-elevated px-2 py-0.5 text-[11px] font-bold text-text-secondary">
-                                    {active.widthMhz} MHz
+                                    {s.widthMhz} MHz
                                   </span>
                                 ) : (
                                   <span className="text-text-muted">—</span>

+ 7 - 0
server-go/internal/adapters/agent.go

@@ -172,6 +172,13 @@ func (r *AgentRegistry) LocalBssids() []string {
 		if st.Payload == nil {
 			continue
 		}
+		// BSSIDs propios reportados por el agente (#1087): exactos, cubren
+		// MACs aleatorizadas y guests fuera de dawn/usteer.
+		if w := st.Payload.Data.Wireless; w != nil {
+			for _, ob := range w.OwnBssids {
+				add(ob.BSSID)
+			}
+		}
 		if st.Payload.Data.Dawn != nil {
 			for _, ssid := range st.Payload.Data.Dawn.SSIDs {
 				for _, ap := range ssid.APs {

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

@@ -39,8 +39,8 @@ func (s *Store) SaveScan(routerID string, ts int64, scans []probe.ScanResult) er
 	defer tx.Rollback()
 
 	stmt, err := tx.Prepare(`
-		INSERT INTO wifi_scans (router_id, iface, bssid, ssid, channel, freq, signal_dbm, ts)
-		VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+		INSERT INTO wifi_scans (router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, ts)
+		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
 	`)
 	if err != nil {
 		return err
@@ -48,7 +48,7 @@ func (s *Store) SaveScan(routerID string, ts int64, scans []probe.ScanResult) er
 	defer stmt.Close()
 
 	for _, sc := range scans {
-		if _, err := stmt.Exec(routerID, sc.Iface, strings.ToUpper(sc.BSSID), sc.SSID, sc.Channel, sc.Freq, sc.Signal, ts); err != nil {
+		if _, err := stmt.Exec(routerID, sc.Iface, strings.ToUpper(sc.BSSID), sc.SSID, sc.Channel, sc.Freq, sc.Signal, sc.WidthMhz, ts); err != nil {
 			return err
 		}
 	}
@@ -63,6 +63,9 @@ type ScanRow struct {
 	Channel  int    `json:"channel"`
 	Freq     int    `json:"freq"`
 	Signal   int    `json:"signal"`
+	// WidthMhz: ancho anunciado por el vecino (#1087); 0 = desconocido
+	// (agente viejo o BSS sin HT/VHT): la UI dibuja 20 MHz de fallback.
+	WidthMhz int    `json:"widthMhz"`
 	Ts       int64  `json:"ts"`
 	RouterID string `json:"routerId"`
 	// Own marca los BSSIDs de la propia malla (#1070): comparten los 5
@@ -99,7 +102,7 @@ func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, e
 	var err error
 	if routerID != "" {
 		rows, err = s.db.Query(`
-			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, MAX(ts)
+			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, MAX(ts)
 			FROM wifi_scans
 			WHERE router_id = ? AND ts >= ?
 			GROUP BY bssid
@@ -107,7 +110,7 @@ func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, e
 		`, routerID, cutoff)
 	} else {
 		rows, err = s.db.Query(`
-			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, MAX(ts)
+			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, MAX(ts)
 			FROM wifi_scans
 			WHERE ts >= ?
 			GROUP BY router_id, bssid
@@ -122,7 +125,7 @@ func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, e
 	out := make([]ScanRow, 0)
 	for rows.Next() {
 		var r ScanRow
-		if err := rows.Scan(&r.RouterID, &r.Iface, &r.BSSID, &r.SSID, &r.Channel, &r.Freq, &r.Signal, &r.Ts); err != nil {
+		if err := rows.Scan(&r.RouterID, &r.Iface, &r.BSSID, &r.SSID, &r.Channel, &r.Freq, &r.Signal, &r.WidthMhz, &r.Ts); err != nil {
 			return nil, err
 		}
 		if exactOwn[strings.ToUpper(strings.TrimSpace(r.BSSID))] {

+ 3 - 0
server-go/internal/db/db.go

@@ -341,6 +341,7 @@ CREATE TABLE IF NOT EXISTS wifi_scans (
   channel     INTEGER NOT NULL,
   freq        INTEGER NOT NULL,
   signal_dbm  INTEGER NOT NULL,
+  width_mhz   INTEGER NOT NULL DEFAULT 0,
   ts          INTEGER NOT NULL
 );
 CREATE INDEX IF NOT EXISTS idx_wifi_scans_router_ts ON wifi_scans(router_id, ts DESC);
@@ -503,6 +504,8 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	migrate(sqldb, "routers", "agent_only", "ALTER TABLE routers ADD COLUMN agent_only INTEGER NOT NULL DEFAULT 0")
 	// issue #196: bridgeMAC persistido del router (exclusión de "desconocido").
 	migrate(sqldb, "routers", "mac", "ALTER TABLE routers ADD COLUMN mac TEXT")
+	// Ancho de canal de los vecinos (#1087), con el agente nuevo; 0 = viejo.
+	migrate(sqldb, "wifi_scans", "width_mhz", "ALTER TABLE wifi_scans ADD COLUMN width_mhz INTEGER NOT NULL DEFAULT 0")
 	// issue #241: target de firmware por router (string libre; NULL/"" = sin comprobar).
 	migrate(sqldb, "routers", "firmware_target", "ALTER TABLE routers ADD COLUMN firmware_target TEXT")
 	// issue #309: SNMP polling for managed switches.