| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717 |
- // Package channelplan — almacenamiento y recomendación de canales WiFi
- // a partir de scans pasivos del agente (Fase 18, #452).
- package channelplan
- import (
- "database/sql"
- "math"
- "strings"
- "time"
- "github.com/gnacho/netpulse/agent/probe"
- )
- // Store persiste scans y calcula recomendaciones de canal.
- type Store struct {
- db *sql.DB
- // ownSeeds devuelve BSSIDs exactos reportados como propios por los
- // agentes (dawn/usteer local=true, #1082); opcional, se cablea en main.
- ownSeeds func() []string
- }
- // NewStore crea el store sobre una conexión SQLite ya abierta.
- func NewStore(db *sql.DB) *Store { return &Store{db: db} }
- // SetOwnSeeds fija el proveedor de BSSIDs propios exactos (p. ej.
- // AgentRegistry.LocalBssids). Se combinan con el prefijo MAC de routers.mac
- // y la transitividad por SSID.
- func (s *Store) SetOwnSeeds(f func() []string) { s.ownSeeds = f }
- // SaveScan guarda los resultados de un scan pasivo recibido en un push.
- func (s *Store) SaveScan(routerID string, ts int64, scans []probe.ScanResult) error {
- if len(scans) == 0 {
- return nil
- }
- tx, err := s.db.Begin()
- if err != nil {
- return err
- }
- defer tx.Rollback()
- stmt, err := tx.Prepare(`
- INSERT INTO wifi_scans (router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, ts)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
- `)
- if err != nil {
- return err
- }
- 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, sc.WidthMhz, ts); err != nil {
- return err
- }
- }
- return tx.Commit()
- }
- // ScanOutcomeRow es el ultimo resultado del scan de una interfaz (#1848).
- // Error vacio con BSS 0 significa "escaneo y no habia nada"; Error con el
- // texto del driver significa que el scan se rechazo.
- type ScanOutcomeRow struct {
- Iface string `json:"iface"`
- Phy int `json:"phy"`
- BSS int `json:"bss"`
- Error string `json:"error,omitempty"`
- Ts int64 `json:"ts"`
- }
- // SaveScanOutcomes guarda el resultado del ultimo scan por interfaz. Se llama
- // en cada push que escanea, haya o no vecinos: un rechazo del driver tambien
- // es informacion (#1848). El payload lo manda el agente desde 3.0.34.
- func (s *Store) SaveScanOutcomes(routerID string, ts int64, outcomes []probe.ScanOutcome) error {
- if len(outcomes) == 0 {
- return nil
- }
- tx, err := s.db.Begin()
- if err != nil {
- return err
- }
- defer tx.Rollback()
- stmt, err := tx.Prepare(`
- INSERT INTO wifi_scan_outcomes (router_id, iface, phy, bss, err, ts)
- VALUES (?, ?, ?, ?, ?, ?)
- ON CONFLICT(router_id, iface) DO UPDATE SET
- phy = excluded.phy, bss = excluded.bss, err = excluded.err, ts = excluded.ts
- `)
- if err != nil {
- return err
- }
- defer stmt.Close()
- for _, oc := range outcomes {
- if oc.Iface == "" {
- continue
- }
- if _, err := stmt.Exec(routerID, oc.Iface, oc.Phy, oc.BSS, oc.Error, ts); err != nil {
- return err
- }
- }
- return tx.Commit()
- }
- // ScanOutcomes devuelve el ultimo resultado por interfaz, el mas reciente
- // primero. Un agente anterior a 3.0.34 no manda el campo y esto sale vacio.
- func (s *Store) ScanOutcomes(routerID string) ([]ScanOutcomeRow, error) {
- rows, err := s.db.Query(`
- SELECT iface, phy, bss, err, ts FROM wifi_scan_outcomes
- WHERE router_id = ? ORDER BY ts DESC, iface`, routerID)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- out := []ScanOutcomeRow{}
- for rows.Next() {
- var oc ScanOutcomeRow
- if err := rows.Scan(&oc.Iface, &oc.Phy, &oc.BSS, &oc.Error, &oc.Ts); err != nil {
- return nil, err
- }
- out = append(out, oc)
- }
- return out, rows.Err()
- }
- // ScanRow es un vecino persistido (forma plana para la UI/API).
- type ScanRow struct {
- Iface string `json:"iface"`
- BSSID string `json:"bssid"`
- SSID string `json:"ssid"`
- 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
- // primeros octetos con la MAC de un router monitorizado. La UI los
- // destaca (cascada y tabla) en vez de pintarlos como vecinos ajenos.
- Own bool `json:"own"`
- }
- // 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()
- // Semillas exactas de los agentes (dawn/usteer local=true, #1082).
- exactOwn := map[string]bool{}
- if s.ownSeeds != nil {
- for _, mac := range s.ownSeeds() {
- if mac = strings.ToUpper(strings.TrimSpace(mac)); mac != "" {
- exactOwn[mac] = true
- }
- }
- }
- // Los prefijos de la malla propia se leen ANTES de la query principal:
- // el pool de SQLite va con MaxOpenConns(1) (internal/db) y
- // ownMeshPrefixes hace su propia Query; con las dos vivas a la vez el
- // segundo db.Query se queda esperando conexión para siempre (deadlock
- // detectado con -timeout: 90 s colgado en db.conn).
- prefixes := s.ownMeshPrefixes()
- var rows *sql.Rows
- var err error
- if routerID != "" {
- rows, err = s.db.Query(`
- 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
- ORDER BY signal_dbm ASC, bssid
- `, routerID, cutoff)
- } else {
- rows, err = s.db.Query(`
- SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, MAX(ts)
- FROM wifi_scans
- WHERE ts >= ?
- GROUP BY router_id, bssid
- ORDER BY signal_dbm ASC, bssid
- `, cutoff)
- }
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- 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.WidthMhz, &r.Ts); err != nil {
- return nil, err
- }
- if exactOwn[strings.ToUpper(strings.TrimSpace(r.BSSID))] {
- r.Own = true
- } else {
- r.Own = isOwnMeshBSSID(r.BSSID, prefixes)
- }
- out = append(out, r)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- // #1076: transitividad por SSID. Los BSSIDs de una misma unidad pueden
- // no compartir prefijo con routers.mac (p. ej. el guest de un GL.iNet);
- // si CUALQUIER BSSID de un SSID es propio por prefijo, todo ese SSID se
- // considera de la malla. Riesgo de falso positivo: un vecino con el
- // mismo ESSID (raro en SSIDs personalizados; aceptable en uso doméstico).
- ownSSIDs := map[string]bool{}
- for _, r := range out {
- if r.Own && r.SSID != "" {
- ownSSIDs[r.SSID] = true
- }
- }
- if len(ownSSIDs) > 0 {
- for i := range out {
- if !out[i].Own && out[i].SSID != "" && ownSSIDs[out[i].SSID] {
- out[i].Own = true
- }
- }
- }
- return out, nil
- }
- // Radio es un resumen de una radio propia con su canal actual y recomendación.
- type Radio struct {
- Iface string `json:"iface"`
- Name string `json:"name"` // "2.4 GHz" | "5 GHz" | "6 GHz"
- Channel int `json:"channel"` // canal actual
- WidthMhz int `json:"widthMhz"`
- Recommended int `json:"recommended"` // canal recomendado; 0 = sin datos
- // ScanError (#1848) lleva el motivo del ultimo intento cuando el driver
- // rechazo el scan. Vacio con medidas o cuando la banda estaba vacia.
- ScanError string `json:"scanError,omitempty"`
- CurrentScore int `json:"currentScore"`
- BestScore int `json:"bestScore"`
- // Scores puntúa TODOS los canales/bloques de la banda (no solo los
- // recomendables), para el panel de puntuación del informe (#1070/#1076):
- // 2.4 GHz canal a canal; 5 GHz bloque a bloque a su ancho, DFS incluidos
- // (informativos, no recomendables).
- Scores []ChannelScore `json:"scores,omitempty"`
- // Section es la sección UCI de la radio ("radio0") reportada por el
- // agente (#500); vacía con agentes antiguos (la UI deshabilita apply).
- Section string `json:"section,omitempty"`
- }
- // ChannelScore puntúa un canal (2.4 GHz) o bloque a su ancho (5 GHz) de la
- // banda del radio. Score es el weighted neighbor score; menor = más limpio.
- // DFS marca bloques que en ETSI requieren detección de radar (usables, pero
- // no los recomienda el motor). Recommendable = no-DFS y apto para sugerir.
- type ChannelScore struct {
- Channel int `json:"channel"`
- Score int `json:"score"`
- Neighbors int `json:"neighbors"`
- Strongest int `json:"strongest"` // dBm de la vecina más fuerte considerada
- DFS bool `json:"dfs"`
- Recommendable bool `json:"recommendable"`
- }
- // bandBlocks devuelve TODOS los canales/bloques puntuables de la banda a su
- // ancho (#1076): 2.4 GHz canal a canal (20 MHz); 5 GHz primarios cuyo bloque
- // completo cabe en la banda (DFS incluidos); 6 GHz impares 1-233 sin DFS.
- func bandBlocks(band string, widthMhz int) []ChannelScore {
- mk := func(ch int, dfs bool) ChannelScore {
- return ChannelScore{Channel: ch, DFS: dfs, Recommendable: !dfs}
- }
- switch band {
- case "2.4 GHz":
- // Se puntúan los 13 canales, pero el motor solo SUGIERE los no
- // solapados 1/6/11 (#631): el resto se muestra en la tira (informa
- // de la congestión real) sin ser recomendables.
- out := make([]ChannelScore, 0, 13)
- for ch := 1; ch <= 13; ch++ {
- orthodox := ch == 1 || ch == 6 || ch == 11
- c := mk(ch, false)
- c.Recommendable = orthodox
- out = append(out, c)
- }
- return out
- case "5 GHz":
- n := widthMhz / 20
- if n < 1 {
- n = 1
- }
- // Bloques NO solapados: el salto es el ancho del bloque (n canales
- // de 20 MHz), alineados a los dos rangos de canales (36-144 y
- // 149-165). Con salto fijo de 4 los bloques de 40/80 MHz se
- // solapaban entre sí y la tira de puntuación duplicaba el mismo
- // espectro (#1076).
- stride := n * 4
- out := make([]ChannelScore, 0, 12)
- for _, base := range [2]int{36, 149} {
- for ch := base; ch <= 165; ch += stride {
- if base == 36 && ch > 144 {
- break
- }
- if ch+(n-1)*4 > 165 {
- continue
- }
- dfs := false
- for i := 0; i < n; i++ {
- if isDFSChannel(ch + i*4) {
- dfs = true
- }
- }
- // Recomendables solo UNII-1 (36-48) y UNII-3 (149-161): el
- // rango 68-92 (5350-5470 MHz) no está asignado a RLAN en
- // ETSI, aunque no sea DFS (#1076).
- c := mk(ch, dfs)
- c.Recommendable = !dfs && (ch <= 48 || ch >= 149)
- out = append(out, c)
- }
- }
- return out
- case "6 GHz":
- // #1742: sin tabla propia, 6 GHz caía en candidateChannels y el motor
- // sugería canales de 2.4 GHz (1, 5, 9...) que nadie había medido. La
- // banda no tiene DFS en el ámbito doméstico y sus canales son los
- // impares 1-233 (paso de 5 MHz, igual que 5 GHz: 4 números por 20 MHz).
- // Los bloques se alinean desde el 1 con salto n*4 para no solaparse.
- n := widthMhz / 20
- if n < 1 {
- n = 1
- }
- stride := n * 4
- out := make([]ChannelScore, 0, 60)
- for ch := 1; ch <= 233; ch += stride {
- if ch+(n-1)*4 > 233 {
- break
- }
- // A 20 MHz solo se sugieren los PSC (5, 21, 37...): son los que
- // un cliente escanea para descubrir la red. El resto se puntúa
- // igual, para informar de la congestión real.
- c := mk(ch, false)
- c.Recommendable = n > 1 || isPSC6(ch)
- out = append(out, c)
- }
- return out
- default:
- out := make([]ChannelScore, 0, len(candidateChannels(band, widthMhz)))
- for _, ch := range candidateChannels(band, widthMhz) {
- out = append(out, mk(ch, false))
- }
- return out
- }
- }
- // Recommend recibe el estado wireless del router (radios propias) y devuelve
- // una recomendación de canal por radio, ponderando por intensidad de señal.
- func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Duration) ([]Radio, error) {
- scans, err := s.RecentScans(routerID, within)
- if err != nil {
- return nil, err
- }
- // #631 + #1080: la malla propia NO congestiona. La exclusion usa el flag
- // Own de los propios ScanRow: prefijo MAC de routers.mac + transitividad
- // por SSID (#1076), asi el guest de una unidad con MAC ajena tampoco
- // penaliza. Fuente unica con lo que la UI pinta como "Tu red".
- // Agrupar scans por banda y canal (descartando la propia malla).
- byBand := map[string]map[int][]ScanRow{}
- for _, sc := range scans {
- if sc.Own {
- continue
- }
- band := bandForFreq(sc.Freq)
- if byBand[band] == nil {
- byBand[band] = map[int][]ScanRow{}
- }
- byBand[band][sc.Channel] = append(byBand[band][sc.Channel], sc)
- }
- out := make([]Radio, 0, len(radios))
- for _, r := range radios {
- band := bandForName(r.Name)
- freq := channelToFreq(r.Channel) // best-effort para casar con scans
- if freq == 0 {
- freq = bandCenter(band, r.Channel)
- }
- rec := Radio{
- Iface: r.Section, // sección real si el agente la reporta (#500)
- Name: r.Name,
- Channel: r.Channel,
- WidthMhz: r.WidthMhz,
- Section: r.Section,
- }
- if rec.Iface == "" {
- rec.Iface = ifaceForBand(band) // placeholder; el agente no reporta iface por radio
- }
- blocks := bandBlocks(band, r.WidthMhz)
- // #1844: el bloque actual se identifica por COBERTURA, no por igualdad.
- // A 80 MHz el bloque que cubre 36-48 se llama 36, asi que un radio en
- // 48 no coincidia con ninguno y acababa en la rama de DFS, que mueve el
- // canal sin mirar vecinas y encima dentro del mismo bloque.
- blockSpan := 0
- if band != "2.4 GHz" {
- blockSpan = r.WidthMhz/20 - 1
- if blockSpan < 0 {
- blockSpan = 0
- }
- }
- bestCh, bestScore := 0, math.MaxInt
- currentScore := math.MaxInt
- currentRecommendable := false
- currentBlockCh := 0
- scores := make([]ChannelScore, 0, len(blocks))
- for _, b := range blocks {
- b.Score, b.Neighbors, b.Strongest = channelScoreDetailed(byBand[band], b.Channel)
- if r.Channel >= b.Channel && r.Channel <= b.Channel+blockSpan*4 {
- currentScore = b.Score
- currentRecommendable = b.Recommendable
- currentBlockCh = b.Channel
- }
- // El motor recomienda solo el mejor bloque no-DFS (#518/#631).
- if b.Recommendable && b.Score < bestScore {
- bestScore = b.Score
- bestCh = b.Channel
- }
- scores = append(scores, b)
- }
- if len(scores) > 0 {
- rec.Scores = scores
- }
- // #518: el canal ACTUAL puede ser DFS (52/100/112/116...) y no estar en
- // candidateChannels (solo no-DFS para recomendar). Su score es
- // informativo ("cuánto ruido tengo ahora") y debe calcularse igual,
- // no quedarse en MaxInt y pintar 9223372036854775807 en la UI.
- if currentScore == math.MaxInt {
- currentScore = channelScore(byBand[band], r.Channel)
- }
- rec.CurrentScore = currentScore
- rec.BestScore = bestScore
- // #1214: sugerencias conservadoras. (1) Sin vecinas en la banda no
- // hay dato con el que opinar. (2) Con dato, el cambio solo se
- // sugiere si el mejor bloque recomendable es apreciablemente mejor
- // (>=30% menos ruido ponderado) que el canal actual: cambiar de
- // canal es disruptivo y el empate técnico no lo justifica. En ambos
- // casos Recommended = canal ACTUAL ("mantén"); la UI distingue
- // mantener de "sin datos" con las vecinas de los scores.
- // EXCEPCIÓN: si el bloque ACTUAL cruza DFS o no es recomendable, se
- // sugiere el mejor recomendable aunque no haya vecinos (el radar
- // desaloja el canal igualmente; no es una sugerencia frívola).
- bandNeighbors := 0
- for _, m := range byBand[band] {
- bandNeighbors += len(m)
- }
- // #1742: un canal que no existe en su banda (el fallback wl de Broadcom
- // devuelve índices hardware: 323, 195...) no se puede comparar con
- // nada, así que no se sugiere cambio. Dentro de la banda se mantiene
- // el criterio legacy: si no es primario de ningún bloque puntuable se
- // asume que hay que moverlo.
- currentKnown := channelInBand(band, r.Channel)
- switch {
- case !currentKnown:
- // 0 es el centinela de "sin datos" que la UI ya distingue de
- // "mantén el actual".
- rec.Recommended = 0
- case !currentRecommendable && bestCh != 0 && bestCh != currentBlockCh:
- // Bloque actual DFS (o solapado en 2.4): se sugiere salir aunque no
- // haya vecinas. #1844: nunca el primario del bloque en el que ya
- // esta, que a 40/80 MHz es el mismo canal de radio.
- rec.Recommended = bestCh
- case bestCh != 0 && bandNeighbors > 0 && bestScore < currentScore && bestScore*100 <= currentScore*70:
- rec.Recommended = bestCh
- default:
- rec.Recommended = r.Channel
- }
- out = append(out, rec)
- }
- return out, nil
- }
- // channelScoreDetailed pondera APs vecinos por canal: señales más fuertes
- // (menos negativas) pesan más y se penalizan APs en canales adyacentes
- // (sobre todo en 2.4 GHz). Además cuenta cuántas vecinas participan y la
- // más fuerte entre ellas, para el panel de puntuación del informe (#1070).
- func channelScoreDetailed(scans map[int][]ScanRow, channel int) (score int, neighbors int, strongest int) {
- total := 0.0
- strongest = math.MinInt
- for ch, list := range scans {
- for _, ap := range list {
- diff := abs(ch - channel)
- weighted := false
- if diff == 0 {
- // Mismo canal: peso completo, en dominio de potencia (#1080):
- // w = 10^((s+60)/10); una vecina a -50 pesa ~3000x una a -85.
- total += math.Pow(10, float64(ap.Signal+60)/10)
- weighted = true
- } else if diff <= 2 {
- // Canal adyacente (+-2): un cuarto (-6 dB), sobre todo en 2.4.
- total += math.Pow(10, float64(ap.Signal+60)/10) / 4
- weighted = true
- }
- if !weighted {
- continue
- }
- neighbors++
- if strongest == math.MinInt || ap.Signal > strongest {
- strongest = ap.Signal
- }
- }
- }
- if neighbors == 0 {
- // Sin vecinas no hay "más fuerte": 0 en vez de MinInt, que en JSON
- // sale como -9223372036854775808 y rompe la tabla.
- strongest = 0
- }
- // x1000 para conservar resolucion al pasar a int (w(-90 dBm) ~= 0.001).
- return int(total * 1000), neighbors, strongest
- }
- // channelScore es la puntuación ponderada pura (menor = canal más limpio).
- func channelScore(scans map[int][]ScanRow, channel int) int {
- score, _, _ := channelScoreDetailed(scans, channel)
- return score
- }
- // 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. 6 GHz tiene su propia
- // tabla de bloques en bandBlocks (#1742).
- func candidateChannels(band string, widthMhz int) []int {
- var base []int
- switch band {
- case "2.4 GHz":
- base = []int{1, 6, 11}
- case "5 GHz":
- // UNII-1/3 canales no-DFS preferidos para uso doméstico.
- base = []int{36, 40, 44, 48, 149, 153, 157, 161, 165}
- 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
- }
- // channelInBand indica si el canal que reporta el radio existe en su banda.
- // El fallback wl de Broadcom devuelve índices hardware (323, 195) que no son
- // canales de 6 GHz (#1742).
- func channelInBand(band string, ch int) bool {
- switch band {
- case "2.4 GHz":
- return ch >= 1 && ch <= 14
- case "5 GHz":
- return ch >= 36 && ch <= 165 && (ch-4)%4 == 0
- case "6 GHz":
- return ch >= 1 && ch <= 233 && (ch-1)%4 == 0
- default:
- // Banda desconocida: no se juzga el canal, se deja el criterio previo.
- return true
- }
- }
- // isPSC6 marca los Preferred Scanning Channels de 6 GHz (5, 21, 37 ... 229):
- // los que un cliente escanea para descubrir la red.
- func isPSC6(ch int) bool {
- return ch >= 5 && ch <= 229 && (ch-5)%16 == 0
- }
- // 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 false
- }
- func bandForFreq(freq int) string {
- switch {
- case freq >= 2412 && freq <= 2484:
- return "2.4 GHz"
- case freq >= 5180 && freq <= 5885:
- return "5 GHz"
- case freq >= 5955:
- return "6 GHz"
- }
- return ""
- }
- func bandForName(name string) string {
- if strings.Contains(name, "2.4") {
- return "2.4 GHz"
- }
- if strings.Contains(name, "5") {
- return "5 GHz"
- }
- if strings.Contains(name, "6") {
- return "6 GHz"
- }
- return ""
- }
- func ifaceForBand(band string) string {
- switch band {
- case "2.4 GHz":
- return "wlan0"
- case "5 GHz":
- return "wlan1"
- }
- return ""
- }
- // channelToFreq best-effort para 2.4 y 5 GHz; se usa como fallback si no
- // tenemos freq directa.
- func channelToFreq(ch int) int {
- if ch >= 1 && ch <= 14 {
- if ch == 14 {
- return 2484
- }
- return 2407 + ch*5
- }
- if ch >= 36 && ch <= 165 {
- return 5000 + ch*5
- }
- return 0
- }
- func bandCenter(band string, ch int) int {
- if f := channelToFreq(ch); f > 0 {
- return f
- }
- switch band {
- case "2.4 GHz":
- return 2437
- case "5 GHz":
- return 5180
- case "6 GHz":
- return 5955
- }
- return 0
- }
- func abs(n int) int {
- if n < 0 {
- return -n
- }
- return n
- }
- // Prune elimina scans más antiguos que `retention`.
- func (s *Store) Prune(retention time.Duration) error {
- cutoff := time.Now().Add(-retention).Unix()
- _, err := s.db.Exec(`DELETE FROM wifi_scans WHERE ts < ?`, cutoff)
- return err
- }
|