瀏覽代碼

feat(roaming): WiFi channel utilization survey tab (Phase 14.4) (#113)

Adds read-only per-channel utilization to /roaming (Survey tab,
replaces the coming-soon placeholder).

Backend:
- GET /api/survey: per-router and per-radio view parsed from
  `iw dev wlanX survey dump`. Lists interfaces via `iw dev`, then
  survey per radio. Agent-only routers skipped.
- Types SurveyChannel/Radio/Router/Overview.
- parseIwSurvey: pure parser with noise floor + busy/active/rx/tx
  percentages. freqToChannel and freqToBand helpers cover 2.4/5/6/60.
- 503 if no router responds.

Frontend (Roaming.tsx Survey tab):
- Per-router cards with one table per radio (wlan0, wlan1, ...).
- Columns: channel, MHz, noise dBm (color-coded), busy% (green <40,
  amber <70, red >=70), rx%, tx%.
- "In use" badge highlights the channel the radio is on.
- Filter by band (all / 2.4 / 5).
- Lazy-loaded only when the tab opens.

Tests: parseIwSurvey + freqToChannel + freqToBand with a real Flint2
fixture (2 radios, 4 channels) + edge cases (empty, header-only,
channel without active time).

Closes #111

Co-authored-by: nacho <nacho@cloudless.club>
Nacho 3 月之前
父節點
當前提交
ffcda03657

+ 16 - 0
app/public/locales/en/translation.json

@@ -367,6 +367,22 @@
       "coverageHint": "Coverage = interfaces with 802.11r / total interfaces on that SSID. For smooth roaming it should be 100% on every SSID.",
       "noIfaces": "No wireless interfaces.",
       "unreachable": "Router not reachable over SSH."
+    },
+    "survey": {
+      "title": "Channel utilization",
+      "description": "Noise floor and load on each WiFi channel (iw survey dump). Congested channels are the most common cause of slow home WiFi.",
+      "empty": "No router returned survey data. Verify that `iw dev wlanX survey dump` works on your routers.",
+      "unreachable": "Router not reachable over SSH or no wireless interfaces.",
+      "colChannel": "Channel",
+      "colFreq": "MHz",
+      "colNoise": "Noise",
+      "colBusy": "Busy",
+      "colRx": "RX",
+      "colTx": "TX",
+      "inUse": "In use",
+      "legendFree": "< 40% (free)",
+      "legendBusy": "40-70% (busy)",
+      "legendCongested": "≥ 70% (congested)"
     }
   },
   "notFound": {

+ 16 - 0
app/public/locales/es/translation.json

@@ -367,6 +367,22 @@
       "coverageHint": "Cobertura = interfaces con 802.11r / total de interfaces en ese SSID. Para roaming fluido debe ser 100% en cada SSID.",
       "noIfaces": "Sin interfaces wifi.",
       "unreachable": "Router no accesible por SSH."
+    },
+    "survey": {
+      "title": "Utilización por canal",
+      "description": "Noise floor y ocupación de cada canal wifi (iw survey dump). Los canales congestionados son la causa más habitual de WiFi lento en casa.",
+      "empty": "Ningún router devolvió datos de survey. Verifica que el comando `iw dev wlanX survey dump` funciona en tus routers.",
+      "unreachable": "Router no accesible por SSH o sin interfaces wifi.",
+      "colChannel": "Canal",
+      "colFreq": "MHz",
+      "colNoise": "Noise",
+      "colBusy": "Ocupación",
+      "colRx": "RX",
+      "colTx": "TX",
+      "inUse": "En uso",
+      "legendFree": "< 40% (libre)",
+      "legendBusy": "40-70% (ocupado)",
+      "legendCongested": "≥ 70% (congestionado)"
     }
   },
   "notFound": {

+ 240 - 2
app/src/pages/Roaming.tsx

@@ -89,6 +89,35 @@ interface Dot11rOverview {
   routers: Dot11rRouter[]
 }
 
+// ---------------------------------------------------------------------------
+// Tipos del contrato GET /api/survey (server-go/internal/adapters/types.go).
+// ---------------------------------------------------------------------------
+
+interface SurveyChannel {
+  freq: number
+  channel: number
+  inUse: boolean
+  noiseDbm: number
+  busyPct: number
+  rxPct: number
+  txPct: number
+}
+interface SurveyRadio {
+  device: string
+  band: string
+  channels: SurveyChannel[]
+}
+interface SurveyRouter {
+  routerId: string
+  name: string
+  available: boolean
+  radios: SurveyRadio[]
+}
+interface SurveyOverview {
+  available: boolean
+  routers: SurveyRouter[]
+}
+
 type Band = 'all' | '2.4 GHz' | '5 GHz'
 type Tab = 'matrix' | '11r' | 'survey' | 'events'
 
@@ -110,6 +139,10 @@ export default function Roaming() {
   const [dot11r, setDot11r] = useState<Dot11rOverview | null>(null)
   const [dot11rLoading, setDot11rLoading] = useState(false)
   const [dot11rError, setDot11rError] = useState(false)
+  const [survey, setSurvey] = useState<SurveyOverview | null>(null)
+  const [surveyLoading, setSurveyLoading] = useState(false)
+  const [surveyError, setSurveyError] = useState(false)
+  const [surveyBand, setSurveyBand] = useState<'all' | '2.4 GHz' | '5 GHz'>('all')
   const [loading, setLoading] = useState(true)
   const [error, setError] = useState(false)
   const [spin, setSpin] = useState(false)
@@ -168,6 +201,28 @@ export default function Roaming() {
     }
   }, [tab, dot11r, dot11rLoading, dot11rError])
 
+  // Carga perezosa de /api/survey: igual que dot11r, un SSH por router con wifi.
+  async function loadSurvey() {
+    setSurveyLoading(true)
+    setSurveyError(false)
+    try {
+      const res = await fetch('/api/survey')
+      if (!res.ok) throw new Error(`status ${res.status}`)
+      setSurvey((await res.json()) as SurveyOverview)
+    } catch {
+      setSurveyError(true)
+      setSurvey(null)
+    } finally {
+      setSurveyLoading(false)
+    }
+  }
+
+  useEffect(() => {
+    if (tab === 'survey' && survey === null && !surveyLoading && !surveyError) {
+      void loadSurvey()
+    }
+  }, [tab, survey, surveyLoading, surveyError])
+
   // APs visibles según el filtro de banda.
   const aps = useMemo(() => {
     if (!dawn) return []
@@ -208,7 +263,7 @@ export default function Roaming() {
   const tabs: { id: Tab; label: string; soon: boolean }[] = [
     { id: 'matrix', label: t('roaming.tabMatrix'), soon: false },
     { id: '11r', label: t('roaming.tab11r'), soon: false },
-    { id: 'survey', label: t('roaming.tabSurvey'), soon: true },
+    { id: 'survey', label: t('roaming.tabSurvey'), soon: false },
     { id: 'events', label: t('roaming.tabEvents'), soon: true },
   ]
 
@@ -245,6 +300,7 @@ export default function Roaming() {
             onClick={() => {
               void load()
               if (tab === '11r') void loadDot11r()
+              if (tab === 'survey') void loadSurvey()
               if (reduce) return
               setSpin(true)
               window.setTimeout(() => setSpin(false), 650)
@@ -276,7 +332,7 @@ export default function Roaming() {
       </div>
 
       {/* ③ Contenido */}
-      {tab !== 'matrix' && tab !== '11r' && (
+      {tab !== 'matrix' && tab !== '11r' && tab !== 'survey' && (
         <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
           {t('roaming.comingSoon')}
         </div>
@@ -284,6 +340,8 @@ export default function Roaming() {
 
       {tab === '11r' && <Dot11rPanel overview={dot11r} loading={dot11rLoading} error={dot11rError} />}
 
+      {tab === 'survey' && <SurveyPanel overview={survey} loading={surveyLoading} error={surveyError} band={surveyBand} setBand={setSurveyBand} />}
+
       {tab === 'matrix' && (
         <>
           {loading && (!dawn || aps.length === 0) && (
@@ -682,3 +740,183 @@ function Flag({ on, label }: { on: boolean; label?: string }) {
     </span>
   )
 }
+
+// ---------------------------------------------------------------------------
+// Pestaña Survey (Fase 14.4) — utilización por canal, por router y radio
+// ---------------------------------------------------------------------------
+
+type SurveyBand = 'all' | '2.4 GHz' | '5 GHz'
+
+function busyClass(p: number): string {
+  if (p >= 70) return 'bg-danger/15 text-danger ring-danger/30'
+  if (p >= 40) return 'bg-warn/15 text-warn ring-warn/30'
+  return 'bg-ok/15 text-ok ring-ok/30'
+}
+
+function noiseClass(dbm: number): string {
+  // Más cercano a 0 = peor. -90 óptimo, -70 malo.
+  if (dbm >= -75) return 'text-danger'
+  if (dbm >= -85) return 'text-warn'
+  return 'text-ok'
+}
+
+function SurveyPanel({
+  overview,
+  loading,
+  error,
+  band,
+  setBand,
+}: {
+  overview: SurveyOverview | null
+  loading: boolean
+  error: boolean
+  band: SurveyBand
+  setBand: (b: SurveyBand) => void
+}) {
+  const { t } = useTranslation()
+  const reduce = useReducedMotion()
+  const initial = reduce ? false : { opacity: 0, y: 12 }
+
+  if (loading && !overview) {
+    return (
+      <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+        {t('roaming.loading')}
+      </div>
+    )
+  }
+  if (error) {
+    return (
+      <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+        {t('roaming.error')}
+      </div>
+    )
+  }
+  if (!overview || !overview.available || overview.routers.length === 0) {
+    return (
+      <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+        {t('roaming.survey.empty')}
+      </div>
+    )
+  }
+
+  const bandOptions: SurveyBand[] = ['all', '2.4 GHz', '5 GHz']
+
+  return (
+    <motion.section
+      initial={initial}
+      animate={{ opacity: 1, y: 0 }}
+      transition={{ duration: 0.25, ease: 'easeOut', delay: 0.08 }}
+      className="space-y-4"
+    >
+      {/* Header + filtro banda */}
+      <div className="rounded-2xl border border-border bg-surface p-5 md:p-6">
+        <div className="flex flex-wrap items-start justify-between gap-3">
+          <div className="flex items-start gap-2">
+            <Wifi className="mt-0.5 h-4 w-4 shrink-0 text-accent" strokeWidth={1.75} />
+            <div>
+              <h2 className="font-display text-h2 text-text-primary">{t('roaming.survey.title')}</h2>
+              <p className="mt-0.5 max-w-2xl text-caption text-text-muted">{t('roaming.survey.description')}</p>
+            </div>
+          </div>
+          <div className="inline-flex items-center gap-1 rounded-lg border border-border bg-elevated p-1" role="group" aria-label={t('roaming.matrix.filterBand')}>
+            {bandOptions.map((b) => (
+              <button
+                key={b}
+                onClick={() => setBand(b)}
+                className={cn(
+                  'rounded-md px-2.5 py-1 text-caption font-medium transition-colors',
+                  band === b ? 'bg-accent/15 text-accent' : 'text-text-muted hover:text-text-secondary',
+                )}
+              >
+                {b === 'all' ? t('roaming.matrix.allBands') : b}
+              </button>
+            ))}
+          </div>
+        </div>
+      </div>
+
+      {/* Tabla por router */}
+      {overview.routers.map((r) => {
+        const radios = r.radios.filter((rd) => band === 'all' || rd.band === band)
+        if (!r.available || radios.length === 0) {
+          return (
+            <div key={r.routerId} className="rounded-2xl border border-border bg-surface p-5">
+              <h3 className="font-display text-h3 text-text-primary">{r.name}</h3>
+              <p className="mt-2 text-caption text-text-muted">{t('roaming.survey.unreachable')}</p>
+            </div>
+          )
+        }
+        return (
+          <div key={r.routerId} className="rounded-2xl border border-border bg-surface p-5 md:p-6">
+            <h3 className="mb-3 font-display text-h3 text-text-primary">{r.name}</h3>
+            {radios.map((radio) => (
+              <div key={radio.device} className="mb-4 last:mb-0">
+                <div className="mb-2 flex items-center gap-2">
+                  <span className="rounded-md bg-elevated px-2 py-0.5 font-mono text-caption text-text-secondary">{radio.device}</span>
+                  <span className="text-caption text-text-muted">{radio.band}</span>
+                </div>
+                <div className="overflow-x-auto">
+                  <table className="w-full border-separate border-spacing-0 text-left text-sm">
+                    <thead>
+                      <tr className="text-label uppercase text-text-muted">
+                        <th className="pb-2 pr-3 font-medium">{t('roaming.survey.colChannel')}</th>
+                        <th className="pb-2 pr-3 font-medium">{t('roaming.survey.colFreq')}</th>
+                        <th className="pb-2 pr-3 font-medium">{t('roaming.survey.colNoise')}</th>
+                        <th className="pb-2 pr-3 font-medium">{t('roaming.survey.colBusy')}</th>
+                        <th className="pb-2 pr-3 font-medium">{t('roaming.survey.colRx')}</th>
+                        <th className="pb-2 pr-3 font-medium">{t('roaming.survey.colTx')}</th>
+                      </tr>
+                    </thead>
+                    <tbody>
+                      {radio.channels.map((c) => (
+                        <tr key={c.freq} className={cn(c.inUse && 'bg-accent/5')}>
+                          <td className="border-b border-border/60 py-2 pr-3">
+                            <span className="font-mono text-text-primary">
+                              {c.channel || '—'}
+                              {c.inUse && (
+                                <span className="ml-1.5 rounded bg-accent-soft px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-accent">
+                                  {t('roaming.survey.inUse')}
+                                </span>
+                              )}
+                            </span>
+                          </td>
+                          <td className="border-b border-border/60 py-2 pr-3 font-mono text-caption text-text-muted">{c.freq}</td>
+                          <td className={cn('border-b border-border/60 py-2 pr-3 font-mono text-mono-sm', noiseClass(c.noiseDbm))}>
+                            {c.noiseDbm} dBm
+                          </td>
+                          <td className="border-b border-border/60 py-2 pr-3">
+                            <span className={cn('inline-block min-w-[3.5rem] rounded-md px-2 py-0.5 text-center font-mono text-mono-sm ring-1 ring-inset', busyClass(c.busyPct))}>
+                              {c.busyPct.toFixed(1)}%
+                            </span>
+                          </td>
+                          <td className="border-b border-border/60 py-2 pr-3 font-mono text-caption text-text-secondary">{c.rxPct.toFixed(1)}%</td>
+                          <td className="border-b border-border/60 py-2 pr-3 font-mono text-caption text-text-secondary">{c.txPct.toFixed(1)}%</td>
+                        </tr>
+                      ))}
+                    </tbody>
+                  </table>
+                </div>
+              </div>
+            ))}
+          </div>
+        )
+      })}
+
+      {/* Leyenda */}
+      <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-caption text-text-muted">
+        <span className="inline-flex items-center gap-1.5">
+          <span className="inline-block h-2.5 w-2.5 rounded-sm bg-ok/40 ring-1 ring-inset ring-ok/40" />
+          {t('roaming.survey.legendFree')}
+        </span>
+        <span className="inline-flex items-center gap-1.5">
+          <span className="inline-block h-2.5 w-2.5 rounded-sm bg-warn/40 ring-1 ring-inset ring-warn/40" />
+          {t('roaming.survey.legendBusy')}
+        </span>
+        <span className="inline-flex items-center gap-1.5">
+          <span className="inline-block h-2.5 w-2.5 rounded-sm bg-danger/40 ring-1 ring-inset ring-danger/40" />
+          {t('roaming.survey.legendCongested')}
+        </span>
+      </div>
+    </motion.section>
+  )
+}

+ 2 - 0
server-go/internal/adapters/demo.go

@@ -189,6 +189,8 @@ func (d *Demo) GetDawn(context.Context) (*Dawn, error) { return nil, nil }
 
 func (d *Demo) GetDot11r(context.Context) (*Dot11rOverview, error) { return nil, nil }
 
+func (d *Demo) GetSurvey(context.Context) (*SurveyOverview, error) { return nil, nil }
+
 func (d *Demo) GetAdguardClients(context.Context) ([]AdguardClient, error) { return nil, nil }
 
 // GetOverview: overview completo (ts en SEGUNDOS). Paridad demo.js:132-146.

+ 214 - 0
server-go/internal/adapters/live.go

@@ -2074,3 +2074,217 @@ func (l *Live) GetDot11r(ctx context.Context) (*Dot11rOverview, error) {
 	}
 	return &out, nil
 }
+
+// ---------------------------------------------------------------------------
+// WiFi Survey (canal utilization) — Fase 14.4
+// ---------------------------------------------------------------------------
+
+// freqToChannel mapea frecuencia MHz → número de canal IEEE 802.11.
+// 2.4 GHz: 2412-2472 → 1-13; 2484 → 14. 5 GHz: 5000+5*N → N (5180=36, ...).
+// 60 GHz: 56160+2160*N → N+1.
+func freqToChannel(freq int) int {
+	switch {
+	case freq >= 2412 && freq <= 2472:
+		return (freq-2412)/5 + 1
+	case freq == 2484:
+		return 14
+	case freq >= 5160 && freq <= 5885:
+		// Canales UNII: 5160=ch32 ... 5885=ch177. Fórmula general (freq-5000)/5.
+		return (freq - 5000) / 5
+	case freq >= 5940 && freq <= 7115:
+		// 6 GHz (Wi-Fi 6E): 5950=ch1 ... 7115=ch233. Mismo (freq-5000)/5, con offset.
+		return (freq - 5950) / 5 + 1
+	case freq == 56160:
+		return 1
+	case freq >= 56160:
+		return (freq-56160)/2160 + 1
+	}
+	return 0
+}
+
+// freqToBand devuelve "2.4 GHz"|"5 GHz"|"6 GHz"|"60 GHz"|"" según la frecuencia.
+func freqToBand(freq int) string {
+	switch {
+	case freq >= 2412 && freq <= 2484:
+		return "2.4 GHz"
+	case freq >= 5160 && freq <= 5885:
+		return "5 GHz"
+	case freq >= 5945 && freq <= 7115:
+		return "6 GHz"
+	case freq >= 56160:
+		return "60 GHz"
+	}
+	return ""
+}
+
+// parseIwSurvey parsea la salida de `iw dev wlanX survey dump` y devuelve
+// un map device → lista de SurveyChannel (uno por frecuencia). Función pura
+// para testear con fixtures reales sin SSH.
+//
+// Formato (ejemplo Flint2):
+//
+//	Survey data from wlan0
+//		frequency:			2412 MHz [in use]
+//		noise:				-90 dBm
+//		channel active time:		3632796925 ms
+//		channel busy time:		878259766 ms
+//		channel receive time:		440957725 ms
+//		channel transmit time:		340995043 ms
+//	Survey data from wlan0
+//		frequency:			2417 MHz
+//		noise:				-92 dBm
+//		channel active time:		72 ms
+//		channel busy time:		20 ms
+//		...
+//
+// Cada bloque empieza con "Survey data from <dev>". Los valores están
+// tabulados y separados por ":". El "[in use]" marca el canal operativo.
+func parseIwSurvey(out string) map[string][]SurveyChannel {
+	type rawChannel struct {
+		freq     int
+		inUse    bool
+		noise    int
+		activeMs float64
+		busyMs   float64
+		rxMs     float64
+		txMs     float64
+	}
+	result := map[string][]SurveyChannel{}
+	var currentDev string
+	var current *rawChannel
+
+	flush := func() {
+		if currentDev == "" || current == nil {
+			return
+		}
+		ch := SurveyChannel{
+			Freq:     current.freq,
+			Channel:  freqToChannel(current.freq),
+			InUse:    current.inUse,
+			NoiseDbm: current.noise,
+		}
+		if current.activeMs > 0 {
+			ch.BusyPct = current.busyMs / current.activeMs * 100
+			ch.RxPct = current.rxMs / current.activeMs * 100
+			ch.TxPct = current.txMs / current.activeMs * 100
+		}
+		result[currentDev] = append(result[currentDev], ch)
+		current = nil
+	}
+
+	for _, line := range strings.Split(out, "\n") {
+		line = strings.TrimRight(line, "\r")
+		trimmed := strings.TrimSpace(line)
+
+		if strings.HasPrefix(trimmed, "Survey data from ") {
+			flush()
+			currentDev = strings.TrimPrefix(trimmed, "Survey data from ")
+			continue
+		}
+		if currentDev == "" {
+			continue
+		}
+		parts := strings.SplitN(trimmed, ":", 2)
+		if len(parts) != 2 {
+			continue
+		}
+		// Solo inicializamos el canal si la línea tiene un campo válido.
+		// Evita crear un canal vacío al final de cada bloque (línea "" final).
+		if current == nil {
+			current = &rawChannel{}
+		}
+		key := strings.TrimSpace(parts[0])
+		val := strings.TrimSpace(parts[1])
+
+		switch key {
+		case "frequency":
+			fmt.Sscanf(val, "%d MHz", &current.freq)
+			if strings.Contains(val, "[in use]") {
+				current.inUse = true
+			}
+		case "noise":
+			fmt.Sscanf(val, "%d dBm", &current.noise)
+		case "channel active time":
+			fmt.Sscanf(val, "%f ms", &current.activeMs)
+		case "channel busy time":
+			fmt.Sscanf(val, "%f ms", &current.busyMs)
+		case "channel receive time":
+			fmt.Sscanf(val, "%f ms", &current.rxMs)
+		case "channel transmit time":
+			fmt.Sscanf(val, "%f ms", &current.txMs)
+		}
+	}
+	flush()
+	return result
+}
+
+// GetSurvey: utilización por canal wifi (iw survey dump) por router y radio.
+// Recorre los routers (saltando agent-only, que no tienen wifi) y hace SSH
+// `iw dev` para listar interfaces, luego `iw dev wlanX survey dump` por cada
+// una. Devuelve (nil, nil) si ningún router responde → el handler 503.
+func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
+	l.mu.Lock()
+	routers := append([]RouterConfig(nil), l.routers...)
+	l.mu.Unlock()
+
+	out := SurveyOverview{Routers: []SurveyRouter{}}
+	any := false
+	for _, cfg := range routers {
+		name := cfg.Name
+		if name == "" {
+			name = cfg.ID
+		}
+		r := SurveyRouter{RouterID: cfg.ID, Name: name, Radios: []SurveyRadio{}}
+		if cfg.AgentOnly {
+			out.Routers = append(out.Routers, r)
+			continue
+		}
+		// Lista de interfaces wifi (wlanX).
+		devsOut, err := l.pool.Run(cfg.Host, "iw dev 2>/dev/null | awk '/Interface/ {print $2}'", 0)
+		if err != nil {
+			out.Routers = append(out.Routers, r)
+			continue
+		}
+		devs := []string{}
+		for _, line := range strings.Split(devsOut, "\n") {
+			d := strings.TrimSpace(line)
+			if d != "" && strings.HasPrefix(d, "wlan") {
+				devs = append(devs, d)
+			}
+		}
+		if len(devs) == 0 {
+			out.Routers = append(out.Routers, r)
+			continue
+		}
+		r.Available = true
+		any = true
+		for _, dev := range devs {
+			surveyOut, err := l.pool.Run(cfg.Host, "iw dev "+dev+" survey dump 2>/dev/null", 0)
+			if err != nil {
+				continue
+			}
+			channels := parseIwSurvey(surveyOut)[dev]
+			if len(channels) == 0 {
+				continue
+			}
+			band := ""
+			// El canal in use define la banda del radio.
+			for _, c := range channels {
+				if c.InUse {
+					band = freqToBand(c.Freq)
+					break
+				}
+			}
+			if band == "" {
+				band = freqToBand(channels[0].Freq)
+			}
+			r.Radios = append(r.Radios, SurveyRadio{Device: dev, Band: band, Channels: channels})
+		}
+		out.Routers = append(out.Routers, r)
+	}
+	if !any {
+		return nil, nil
+	}
+	out.Available = true
+	return &out, nil
+}

+ 165 - 0
server-go/internal/adapters/survey_test.go

@@ -0,0 +1,165 @@
+package adapters
+
+import (
+	"math"
+	"testing"
+)
+
+// TestFreqToChannel cubre la conversión freq MHz → número de canal.
+func TestFreqToChannel(t *testing.T) {
+	cases := map[int]int{
+		2412: 1,  // 2.4 GHz ch1
+		2417: 2,  // ch2
+		2437: 6,  // ch6
+		2462: 11, // ch11
+		2472: 13, // ch13
+		2484: 14, // ch14 (Japón)
+		5180: 36, // 5 GHz UNII-1 ch36
+		5200: 40,
+		5240: 48,
+		5745: 149, // UNII-3
+		5825: 165,
+	}
+	for freq, want := range cases {
+		got := freqToChannel(freq)
+		if got != want {
+			t.Errorf("freqToChannel(%d) = %d, want %d", freq, got, want)
+		}
+	}
+}
+
+func TestFreqToBand(t *testing.T) {
+	cases := map[int]string{
+		2412: "2.4 GHz",
+		2484: "2.4 GHz",
+		5180: "5 GHz",
+		5825: "5 GHz",
+		6135: "6 GHz",
+		9999: "",
+	}
+	for freq, want := range cases {
+		got := freqToBand(freq)
+		if got != want {
+			t.Errorf("freqToBand(%d) = %q, want %q", freq, got, want)
+		}
+	}
+}
+
+// TestParseIwSurveyFlint2 usa la salida real de `iw dev wlan0 survey dump`
+// y `iw dev wlan1 survey dump` del Flint2 como fixture.
+func TestParseIwSurveyFlint2(t *testing.T) {
+	out := `Survey data from wlan0
+	frequency:			2412 MHz [in use]
+	noise:				-90 dBm
+	channel active time:		3632796925 ms
+	channel busy time:		878259766 ms
+	channel receive time:		440957725 ms
+	channel BSS receive time:	173056055 ms
+	channel transmit time:		340995043 ms
+Survey data from wlan0
+	frequency:			2417 MHz
+	noise:				-92 dBm
+	channel active time:		72 ms
+	channel busy time:		20 ms
+	channel receive time:		10 ms
+	channel transmit time:		0 ms
+Survey data from wlan1
+	frequency:			5180 MHz [in use]
+	noise:				-92 dBm
+	channel active time:		3632802379 ms
+	channel busy time:		146150367 ms
+	channel receive time:		67413467 ms
+	channel transmit time:		76785952 ms
+Survey data from wlan1
+	frequency:			5200 MHz
+	noise:				-92 dBm
+	channel active time:		191 ms
+	channel busy time:		0 ms
+	channel receive time:		0 ms
+	channel transmit time:		0 ms
+`
+	result := parseIwSurvey(out)
+
+	if len(result) != 2 {
+		t.Fatalf("expected 2 devices, got %d: %v", len(result), result)
+	}
+	if len(result["wlan0"]) != 2 {
+		t.Errorf("wlan0 channels: %d, want 2", len(result["wlan0"]))
+	}
+	if len(result["wlan1"]) != 2 {
+		t.Errorf("wlan1 channels: %d, want 2", len(result["wlan1"]))
+	}
+
+	// Canal in-use wlan0: 2412 MHz = ch1, noise -90.
+	ch := result["wlan0"][0]
+	if ch.Freq != 2412 || ch.Channel != 1 || !ch.InUse || ch.NoiseDbm != -90 {
+		t.Errorf("wlan0[0] wrong: %+v", ch)
+	}
+	// busyPct = 878259766 / 3632796925 * 100 ≈ 24.18%
+	expectedBusy := 878259766.0 / 3632796925.0 * 100
+	if math.Abs(ch.BusyPct-expectedBusy) > 0.01 {
+		t.Errorf("wlan0[0] BusyPct = %.4f, want %.4f", ch.BusyPct, expectedBusy)
+	}
+
+	// Canal NO in-use wlan0: 2417 = ch2, noise -92.
+	ch = result["wlan0"][1]
+	if ch.Freq != 2417 || ch.Channel != 2 || ch.InUse || ch.NoiseDbm != -92 {
+		t.Errorf("wlan0[1] wrong: %+v", ch)
+	}
+	// busyPct = 20 / 72 * 100 ≈ 27.78%
+	expectedBusy = 20.0 / 72.0 * 100
+	if math.Abs(ch.BusyPct-expectedBusy) > 0.01 {
+		t.Errorf("wlan0[1] BusyPct = %.4f, want %.4f", ch.BusyPct, expectedBusy)
+	}
+
+	// Canal in-use wlan1: 5180 MHz = ch36.
+	ch = result["wlan1"][0]
+	if ch.Freq != 5180 || ch.Channel != 36 || !ch.InUse {
+		t.Errorf("wlan1[0] wrong: %+v", ch)
+	}
+}
+
+// TestParseIwSurveyEdge cubre entradas degeneradas.
+func TestParseIwSurveyEdge(t *testing.T) {
+	cases := map[string]string{
+		"empty":       "",
+		"no-survey":   "unrelated line\nanother\n",
+		"only-header": "Survey data from wlan0\n",
+	}
+	for name, in := range cases {
+		t.Run(name, func(t *testing.T) {
+			got := parseIwSurvey(in)
+			if name == "only-header" {
+				// 1 device con 0 channels (no se hace flush sin campos).
+				if len(got["wlan0"]) != 0 {
+					t.Fatalf("wlan0 channels: %d, want 0", len(got["wlan0"]))
+				}
+				return
+			}
+			if len(got) != 0 {
+				t.Fatalf("expected empty map for %q, got %v", name, got)
+			}
+		})
+	}
+}
+
+// TestParseIwSurveyChannelNoActive cubre un canal sin "channel active time"
+// (no debe panicar, busyPct=0).
+func TestParseIwSurveyChannelNoActive(t *testing.T) {
+	out := `Survey data from wlan0
+	frequency:			2412 MHz
+	noise:				-85 dBm
+`
+	result := parseIwSurvey(out)
+	if len(result["wlan0"]) != 1 {
+		t.Fatalf("expected 1 channel, got %d", len(result["wlan0"]))
+	}
+	ch := result["wlan0"][0]
+	if ch.BusyPct != 0 || ch.RxPct != 0 || ch.TxPct != 0 {
+		t.Errorf("busyPct should be 0 without active time, got busy=%.2f rx=%.2f tx=%.2f",
+			ch.BusyPct, ch.RxPct, ch.TxPct)
+	}
+	if ch.NoiseDbm != -85 {
+		t.Errorf("noise = %d, want -85", ch.NoiseDbm)
+	}
+}

+ 45 - 1
server-go/internal/adapters/types.go

@@ -490,6 +490,46 @@ type Dot11rOverview struct {
 	Routers   []Dot11rRouter `json:"routers"`
 }
 
+// ---------------------------------------------------------------------------
+// WiFi Survey (canal utilization) — Fase 14.4
+// ---------------------------------------------------------------------------
+
+// SurveyChannel es un canal visto por `iw dev wlanX survey dump`: noise floor
+// + contadores busy/active/rx/tx. BusyPct = busy/active (uso del canal),
+// RxPct/TxPct desglosan parte de ese uso.
+type SurveyChannel struct {
+	Freq     int     `json:"freq"`     // MHz (2412, 5180, ...)
+	Channel  int     `json:"channel"`  // 1, 6, 11, 36, ... (computado desde freq)
+	InUse    bool    `json:"inUse"`    // true si la radio está operando en este canal
+	NoiseDbm int     `json:"noiseDbm"` // -90, -76, ... (más cercano a 0 = peor)
+	BusyPct  float64 `json:"busyPct"`  // busy_time / active_time * 100
+	RxPct    float64 `json:"rxPct"`
+	TxPct    float64 `json:"txPct"`
+}
+
+// SurveyRadio agrupa los canales survey de un device wifi (wlan0, wlan1).
+type SurveyRadio struct {
+	Device   string           `json:"device"` // wlan0, wlan1
+	Band     string           `json:"band"`   // "2.4 GHz"|"5 GHz" (inferido del primer canal)
+	Channels []SurveyChannel  `json:"channels"`
+}
+
+// SurveyRouter es el survey de un router: lista de radios wifi-iface.
+// Available=false si SSH falló.
+type SurveyRouter struct {
+	RouterID  string         `json:"routerId"`
+	Name      string         `json:"name"`
+	Available bool           `json:"available"`
+	Radios    []SurveyRadio  `json:"radios"`
+}
+
+// SurveyOverview es la respuesta de GET /api/survey. Available=false si
+// ningún router responde → el handler devuelve 503.
+type SurveyOverview struct {
+	Available bool            `json:"available"`
+	Routers   []SurveyRouter  `json:"routers"`
+}
+
 // AdguardClient es un cliente configurado en AdGuard GL.iNet (§2.13).
 type AdguardClient struct {
 	Name              string `json:"name"`
@@ -532,13 +572,14 @@ type RouterConfig struct {
 
 // Snapshotter es el contrato del adapter de datos (paridad con la interfaz JS
 // de SPEC §7: mode/tick/setRouters/getOverview/getRouters/getRouterDetail/
-// getDevices/getAlerts/getMetricsRows/getDawn/getDot11r/getAdguardClients/close;
+// getDevices/getAlerts/getMetricsRows/getDawn/getDot11r/getSurvey/getAdguardClients/close;
 // getAdguardRow() está muerto en Node y NO se porta).
 //
 // Convenciones de retorno (consumidas por internal/httpapi):
 //   - GetRouterDetail: (nil, nil) → 404 {"error":"not_found"}.
 //   - GetDawn: (nil, nil) → 503 {"error":"unavailable"}.
 //   - GetDot11r: (nil, nil) → 503 {"error":"unavailable"}.
+//   - GetSurvey: (nil, nil) → 503 {"error":"unavailable"}.
 //   - GetAdguardClients: (nil, nil) → 404 {"error":"not_configured"};
 //     (x, err) → 502 {"error":"adguard_error","message":err}.
 //   - GetOverview nunca devuelve nil sin error; el handler lo serializa tal
@@ -574,6 +615,9 @@ type Snapshotter interface {
 	// GetDot11r devuelve el estado 802.11r (FT) por router y SSID, o
 	// (nil, nil) si ningún router lo soporta → el handler responde 503.
 	GetDot11r(ctx context.Context) (*Dot11rOverview, error)
+	// GetSurvey devuelve la utilización por canal wifi (iw survey dump)
+	// por router y radio, o (nil, nil) si ningún router responde → 503.
+	GetSurvey(ctx context.Context) (*SurveyOverview, error)
 	// GetAdguardClients devuelve los clientes AdGuard, (nil, nil) si no hay
 	// cliente configurado o no soporta queryClients, o error → 502.
 	GetAdguardClients(ctx context.Context) ([]AdguardClient, error)

+ 14 - 0
server-go/internal/httpapi/data.go

@@ -317,6 +317,20 @@ func (s *server) handleDot11r(w http.ResponseWriter, r *http.Request) {
 	writeJSON(w, http.StatusOK, dot11r)
 }
 
+// handleSurvey: 503 {error:'unavailable'} si ningún router responde.
+func (s *server) handleSurvey(w http.ResponseWriter, r *http.Request) {
+	survey, err := s.adapter.GetSurvey(r.Context())
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	if survey == nil {
+		writeError(w, http.StatusServiceUnavailable, "unavailable")
+		return
+	}
+	writeJSON(w, http.StatusOK, survey)
+}
+
 // handleAdguardClients: 404 not_configured · 502 adguard_error.
 func (s *server) handleAdguardClients(w http.ResponseWriter, r *http.Request) {
 	clients, err := s.adapter.GetAdguardClients(r.Context())

+ 1 - 0
server-go/internal/httpapi/server.go

@@ -161,6 +161,7 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("GET /api/topology", s.handleTopology)
 	mux.HandleFunc("GET /api/dawn", s.handleDawn)
 	mux.HandleFunc("GET /api/dot11r", s.handleDot11r)
+	mux.HandleFunc("GET /api/survey", s.handleSurvey)
 	mux.HandleFunc("GET /api/adguard/clients", s.handleAdguardClients)
 	mux.HandleFunc("GET /api/system/info", s.handleSystemInfo)
 	mux.HandleFunc("GET /api/reports/weekly", s.handleWeeklyReport)