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

feat(roaming): /roaming page with clients×APs signal matrix (Phase 14.2b) (#100)

* feat(roaming): parse DAWN hearing map (clients x APs signal) server-side (#99)

Amplia GetDawn para parsear los clientes anidados del mismo
'ubus call dawn get_network' que ya ejecuta via SSH, sin tocar
routers ni agentes. Cada DawnAP lleva ahora la lista de clientes
vistos (MAC, signal -dBm, HT/VHT) del hearing map distribuido de
DAWN. Funcion pura dawnAPsFromNetwork extraida para test sin SSH.

- types.go: DawnClient + Clients []DawnClient en DawnAP; ClientCount (num_sta)
- live.go: GetDawn reescrito con json.RawMessage; dawnAPsFromNetwork pura
- dawn_test.go: hearing map (cliente bajo 2 APs), orden, vacio

* feat(roaming): /roaming page with clients x APs signal matrix (#99)

Pagina /roaming (nav entre Topologia y Alertas, icono Wifi) con la
pestana Matriz: heatmap clientes x APs con la señal -dBm del hearing
map distribuido de DAWN (verde <= -65, ambar -80, rojo >= -85).
Resuelve MAC a nombre desde el overview; ordena por mejor senal vista
ascendente (clientes en zona limite arriba). Filtros de banda y
'solo señal debil'. Pestañas 802.11r/Survey/Eventos como proximas.

- App.tsx: ruta /roaming
- Layout.tsx: NAV_ITEMS + icono Wifi
- Roaming.tsx: fetch GET /api/dawn, matriz con sticky col/header, leyenda
- locales: nav.roaming + seccion roaming.* (es+en); anyade nav.reports faltante en EN

* fix(roaming): init DawnAP.Clients so it serializes [] not null (#99)

Un slice nil en Go serializa como JSON null; el frontend itera ap.clients
sin guardarse de null -> TypeError. Inicializar []DawnClient{} vacio.

* fix(roaming): map /roaming and /orchestration in PAGE_TITLE_KEYS (#99)

El h1 global del topbar caia a 'Resumen' para rutas no mapeadas. /roaming
y /orchestration faltaban en PAGE_TITLE_KEYS.

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
bb81cf449a

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

@@ -298,6 +298,8 @@
     "more": "More",
     "more": "More",
     "moreOptions": "More options",
     "moreOptions": "More options",
     "overview": "Overview",
     "overview": "Overview",
+    "reports": "Reports",
+    "roaming": "WiFi roaming",
     "routerDetail": "Router detail",
     "routerDetail": "Router detail",
     "routers": "Routers",
     "routers": "Routers",
     "settings": "Settings",
     "settings": "Settings",
@@ -309,6 +311,32 @@
     "expand": "Expand menu",
     "expand": "Expand menu",
     "orchestration": "Orchestration"
     "orchestration": "Orchestration"
   },
   },
+  "roaming": {
+    "subtitle": "Roaming and WiFi mesh status",
+    "loading": "Loading DAWN data…",
+    "error": "Could not load DAWN status. Check that the service runs on your routers.",
+    "empty": "No router has DAWN enabled. Install it on OpenWrt to see the roaming mesh.",
+    "tabMatrix": "Matrix",
+    "tab11r": "802.11r",
+    "tabSurvey": "Survey",
+    "tabEvents": "Events",
+    "comingSoon": "Coming soon",
+    "matrix": {
+      "title": "Signal matrix",
+      "description": "Signal of each client as seen by each AP (DAWN hearing map). Clients in the marginal zone are roaming candidates.",
+      "colClient": "Client",
+      "colAp": "Access point",
+      "filterBand": "Band",
+      "allBands": "All",
+      "filterWeak": "Weak signal only (< -70 dBm)",
+      "noClients": "No clients associated with these APs.",
+      "clients": "{{count}} clients",
+      "aps": "{{count}} APs",
+      "legendGood": "≤ -65 dBm (optimal)",
+      "legendFair": "-70 to -80 dBm (fair)",
+      "legendWeak": "≥ -85 dBm (marginal)"
+    }
+  },
   "notFound": {
   "notFound": {
     "construction": "This page is under construction. The mockup will complete it in the next iteration."
     "construction": "This page is under construction. The mockup will complete it in the next iteration."
   },
   },

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

@@ -299,6 +299,7 @@
     "moreOptions": "Más opciones",
     "moreOptions": "Más opciones",
     "overview": "Resumen",
     "overview": "Resumen",
     "reports": "Informes",
     "reports": "Informes",
+    "roaming": "Roaming WiFi",
     "routerDetail": "Detalle de router",
     "routerDetail": "Detalle de router",
     "routers": "Routers",
     "routers": "Routers",
     "settings": "Ajustes",
     "settings": "Ajustes",
@@ -310,6 +311,32 @@
     "expand": "Desplegar menú",
     "expand": "Desplegar menú",
     "orchestration": "Orquestación"
     "orchestration": "Orquestación"
   },
   },
+  "roaming": {
+    "subtitle": "Estado del roaming y la malla WiFi",
+    "loading": "Cargando datos de DAWN…",
+    "error": "No se pudo cargar el estado de DAWN. Comprueba que el servicio corre en tus routers.",
+    "empty": "Ningún router tiene DAWN activo. Instálalo en OpenWrt para ver la malla de roaming.",
+    "tabMatrix": "Matriz",
+    "tab11r": "802.11r",
+    "tabSurvey": "Survey",
+    "tabEvents": "Eventos",
+    "comingSoon": "Próximamente",
+    "matrix": {
+      "title": "Matriz de señal",
+      "description": "Señal de cada cliente vista por cada AP (hearing map de DAWN). Los clientes en zona límite son candidatos a roaming.",
+      "colClient": "Cliente",
+      "colAp": "Punto de acceso",
+      "filterBand": "Banda",
+      "allBands": "Todas",
+      "filterWeak": "Solo señal débil (< -70 dBm)",
+      "noClients": "Sin clientes asociados a estos APs.",
+      "clients": "{{count}} clientes",
+      "aps": "{{count}} APs",
+      "legendGood": "≤ -65 dBm (óptimo)",
+      "legendFair": "-70 a -80 dBm (aceptable)",
+      "legendWeak": "≥ -85 dBm (límite)"
+    }
+  },
   "notFound": {
   "notFound": {
     "construction": "Esta página está en construcción. El mockup la completará en la siguiente iteración."
     "construction": "Esta página está en construcción. El mockup la completará en la siguiente iteración."
   },
   },

+ 2 - 0
app/src/App.tsx

@@ -9,6 +9,7 @@ import RouterDetail from '@/pages/RouterDetail'
 import Devices from '@/pages/Devices'
 import Devices from '@/pages/Devices'
 import Topology from '@/pages/Topology'
 import Topology from '@/pages/Topology'
 import Alerts from '@/pages/Alerts'
 import Alerts from '@/pages/Alerts'
+import Roaming from '@/pages/Roaming'
 import Reports from '@/pages/Reports'
 import Reports from '@/pages/Reports'
 import Orchestration from '@/pages/Orchestration'
 import Orchestration from '@/pages/Orchestration'
 import Settings from '@/pages/Settings'
 import Settings from '@/pages/Settings'
@@ -38,6 +39,7 @@ export default function App() {
         <Route path="devices" element={<Devices />} />
         <Route path="devices" element={<Devices />} />
         <Route path="topology" element={<Topology />} />
         <Route path="topology" element={<Topology />} />
         <Route path="alerts" element={<Alerts />} />
         <Route path="alerts" element={<Alerts />} />
+        <Route path="roaming" element={<Roaming />} />
         <Route path="reports" element={<Reports />} />
         <Route path="reports" element={<Reports />} />
         <Route path="orchestration" element={<Orchestration />} />
         <Route path="orchestration" element={<Orchestration />} />
         <Route path="settings" element={<Settings />} />
         <Route path="settings" element={<Settings />} />

+ 4 - 0
app/src/components/Layout.tsx

@@ -15,6 +15,7 @@ import {
   Router as RouterIcon,
   Router as RouterIcon,
   Settings,
   Settings,
   Waypoints,
   Waypoints,
+  Wifi,
   Wrench,
   Wrench,
 } from 'lucide-react'
 } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
@@ -44,6 +45,7 @@ const NAV_ITEMS: NavItem[] = [
   { to: '/routers', labelKey: 'nav.routers', icon: RouterIcon },
   { to: '/routers', labelKey: 'nav.routers', icon: RouterIcon },
   { to: '/devices', labelKey: 'nav.devices', icon: MonitorSmartphone },
   { to: '/devices', labelKey: 'nav.devices', icon: MonitorSmartphone },
   { to: '/topology', labelKey: 'nav.topology', icon: Waypoints },
   { to: '/topology', labelKey: 'nav.topology', icon: Waypoints },
+  { to: '/roaming', labelKey: 'nav.roaming', icon: Wifi },
   { to: '/alerts', labelKey: 'nav.alerts', icon: Bell },
   { to: '/alerts', labelKey: 'nav.alerts', icon: Bell },
   { to: '/reports', labelKey: 'nav.reports', icon: BarChart3 },
   { to: '/reports', labelKey: 'nav.reports', icon: BarChart3 },
   { to: '/orchestration', labelKey: 'nav.orchestration', icon: Wrench, adminOnly: true },
   { to: '/orchestration', labelKey: 'nav.orchestration', icon: Wrench, adminOnly: true },
@@ -62,8 +64,10 @@ const PAGE_TITLE_KEYS: [RegExp, string][] = [
   [/^\/routers/, 'nav.routers'],
   [/^\/routers/, 'nav.routers'],
   [/^\/devices/, 'nav.devices'],
   [/^\/devices/, 'nav.devices'],
   [/^\/topology/, 'nav.topology'],
   [/^\/topology/, 'nav.topology'],
+  [/^\/roaming/, 'nav.roaming'],
   [/^\/alerts/, 'nav.alerts'],
   [/^\/alerts/, 'nav.alerts'],
   [/^\/reports/, 'nav.reports'],
   [/^\/reports/, 'nav.reports'],
+  [/^\/orchestration/, 'nav.orchestration'],
   [/^\/settings/, 'nav.settings'],
   [/^\/settings/, 'nav.settings'],
 ]
 ]
 
 

+ 355 - 0
app/src/pages/Roaming.tsx

@@ -0,0 +1,355 @@
+import { useEffect, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link } from 'react-router'
+import { motion, useReducedMotion } from 'framer-motion'
+import { RefreshCw, Wifi } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import { useNetPulse } from '@/data/DataProvider'
+
+// ---------------------------------------------------------------------------
+// Tipos del contrato GET /api/dawn (server-go/internal/adapters/types.go).
+// Los clientes vienen del hearing map distribuido de DAWN: cada AP reporta
+// los clientes que ve con su señal, así que un mismo cliente puede aparecer
+// bajo varios BSSIDs (lo que pinta varias celdas en la matriz).
+// ---------------------------------------------------------------------------
+
+interface DawnClient {
+  mac: string
+  signal: number // -dBm
+  ht: boolean
+  vht: boolean
+}
+interface DawnAP {
+  ssid: string
+  bssid: string
+  hostname: string
+  band: string
+  channel: number
+  utilizationPct: number
+  clientCount: number
+  clients: DawnClient[]
+  local: boolean
+  iface: string
+}
+interface DawnMesh {
+  routerId: string
+  name: string
+  dawn: boolean
+  apsSeen: number
+}
+interface Dawn {
+  aps: DawnAP[]
+  mesh: DawnMesh[]
+}
+
+type Band = 'all' | '2.4 GHz' | '5 GHz'
+type Tab = 'matrix' | '11r' | 'survey' | 'events'
+
+/** Clase de color por señal (-dBm): verde óptimo, ámbar aceptable, rojo límite. */
+function signalClass(s: number): string {
+  if (s >= -65) return 'bg-ok/15 text-ok ring-ok/30'
+  if (s >= -80) return 'bg-warn/15 text-warn ring-warn/30'
+  return 'bg-danger/15 text-danger ring-danger/30'
+}
+
+export default function Roaming() {
+  const { t } = useTranslation()
+  const reduce = useReducedMotion()
+  const { devices } = useNetPulse()
+  const [tab, setTab] = useState<Tab>('matrix')
+  const [band, setBand] = useState<Band>('all')
+  const [weakOnly, setWeakOnly] = useState(false)
+  const [dawn, setDawn] = useState<Dawn | null>(null)
+  const [loading, setLoading] = useState(true)
+  const [error, setError] = useState(false)
+  const [spin, setSpin] = useState(false)
+
+  // MAC → nombre (resuelto desde la lista de dispositivos del overview).
+  const nameByMac = useMemo(() => {
+    const m = new Map<string, string>()
+    for (const d of devices) {
+      if (d.mac) m.set(d.mac.toUpperCase(), d.name)
+    }
+    return m
+  }, [devices])
+
+  async function load() {
+    setLoading(true)
+    setError(false)
+    try {
+      const res = await fetch('/api/dawn')
+      if (!res.ok) throw new Error(`status ${res.status}`)
+      setDawn((await res.json()) as Dawn)
+    } catch {
+      setError(true)
+      setDawn(null)
+    } finally {
+      setLoading(false)
+    }
+  }
+
+  useEffect(() => {
+    void load()
+  }, [])
+
+  // APs visibles según el filtro de banda.
+  const aps = useMemo(() => {
+    if (!dawn) return []
+    return dawn.aps.filter((a) => band === 'all' || a.band === band)
+  }, [dawn, band])
+
+  // Filas = un cliente por MAC, con su señal vista desde cada AP (BSSID).
+  const rows = useMemo(() => {
+    const byMac = new Map<string, { mac: string; signals: Map<string, number> }>()
+    for (const ap of aps) {
+      for (const c of ap.clients) {
+        let r = byMac.get(c.mac)
+        if (!r) {
+          r = { mac: c.mac, signals: new Map() }
+          byMac.set(c.mac, r)
+        }
+        // DAWN puede reportar la misma MAC varias veces bajo un BSSID; nos
+        // quedamos con la señal más fuerte (la medición más reciente/sana).
+        const prev = r.signals.get(ap.bssid)
+        if (prev === undefined || c.signal > prev) r.signals.set(ap.bssid, c.signal)
+      }
+    }
+    let arr = [...byMac.values()]
+    if (weakOnly) {
+      arr = arr.filter((r) => [...r.signals.values()].every((s) => s < -70))
+    }
+    // Orden: mejor señal vista ascendente (los clientes peor vistos arriba).
+    arr.sort((a, b) => {
+      const am = Math.max(...a.signals.values())
+      const bm = Math.max(...b.signals.values())
+      if (am !== bm) return am - bm
+      return (nameByMac.get(a.mac) ?? a.mac).localeCompare(nameByMac.get(b.mac) ?? b.mac)
+    })
+    return arr
+  }, [aps, weakOnly, nameByMac])
+
+  const bandOptions: Band[] = ['all', '2.4 GHz', '5 GHz']
+  const tabs: { id: Tab; label: string; soon: boolean }[] = [
+    { id: 'matrix', label: t('roaming.tabMatrix'), soon: false },
+    { id: '11r', label: t('roaming.tab11r'), soon: true },
+    { id: 'survey', label: t('roaming.tabSurvey'), soon: true },
+    { id: 'events', label: t('roaming.tabEvents'), soon: true },
+  ]
+
+  const initial = reduce ? false : { opacity: 0, y: 12 }
+
+  return (
+    <div className="space-y-4 md:space-y-5">
+      {/* ① Page header */}
+      <header>
+        <motion.nav
+          initial={initial}
+          animate={{ opacity: 1, y: 0 }}
+          transition={{ duration: 0.25, ease: 'easeOut' }}
+          aria-label={t('common.breadcrumb')}
+          className="font-mono text-caption text-text-muted"
+        >
+          <Link to="/" className="transition-colors hover:text-accent">{t('common.home')}</Link>
+          <span className="mx-1.5">/</span>
+          <span className="text-text-secondary">{t('nav.roaming')}</span>
+        </motion.nav>
+        <div className="mt-1.5 flex flex-wrap items-end justify-between gap-x-4 gap-y-3">
+          <motion.div
+            initial={initial}
+            animate={{ opacity: 1, y: 0 }}
+            transition={{ duration: 0.25, ease: 'easeOut', delay: 0.06 }}
+          >
+            <h1 className="font-display text-h1 text-text-primary">{t('nav.roaming')}</h1>
+            <p className="text-caption text-text-muted">{t('roaming.subtitle')}</p>
+          </motion.div>
+          <motion.button
+            initial={initial}
+            animate={{ opacity: 1, y: 0 }}
+            transition={{ duration: 0.25, ease: 'easeOut', delay: 0.12 }}
+            onClick={() => {
+              void load()
+              if (reduce) return
+              setSpin(true)
+              window.setTimeout(() => setSpin(false), 650)
+            }}
+            className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-surface px-3 text-sm font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
+          >
+            <RefreshCw className={cn('h-4 w-4 transition-transform duration-500', spin && 'rotate-[360deg]')} strokeWidth={1.75} />
+            {t('common.refresh')}
+          </motion.button>
+        </div>
+      </header>
+
+      {/* ② Pestañas */}
+      <div className="inline-flex items-center gap-1 rounded-lg border border-border bg-surface p-1" role="tablist">
+        {tabs.map((tb) => (
+          <button
+            key={tb.id}
+            role="tab"
+            aria-selected={tab === tb.id}
+            onClick={() => setTab(tb.id)}
+            className={cn(
+              'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
+              tab === tb.id ? 'bg-accent/15 text-accent' : 'text-text-muted hover:text-text-secondary',
+            )}
+          >
+            {tb.label}
+          </button>
+        ))}
+      </div>
+
+      {/* ③ Contenido */}
+      {tab !== 'matrix' && (
+        <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+          {t('roaming.comingSoon')}
+        </div>
+      )}
+
+      {tab === 'matrix' && (
+        <>
+          {loading && (!dawn || aps.length === 0) && (
+            <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+              {t('roaming.loading')}
+            </div>
+          )}
+          {error && (
+            <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+              {t('roaming.error')}
+            </div>
+          )}
+          {!loading && !error && dawn && dawn.aps.length === 0 && (
+            <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+              {t('roaming.empty')}
+            </div>
+          )}
+
+          {!error && dawn && aps.length > 0 && (
+            <motion.section
+              initial={initial}
+              animate={{ opacity: 1, y: 0 }}
+              transition={{ duration: 0.25, ease: 'easeOut', delay: 0.08 }}
+              className="rounded-2xl border border-border bg-surface p-5 md:p-6"
+            >
+              {/* Título + filtros */}
+              <div className="mb-4 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.matrix.title')}</h2>
+                    <p className="mt-0.5 max-w-2xl text-caption text-text-muted">{t('roaming.matrix.description')}</p>
+                  </div>
+                </div>
+                <div className="flex flex-wrap items-center gap-2">
+                  <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>
+                  <label className="inline-flex cursor-pointer items-center gap-2 rounded-lg border border-border bg-elevated px-2.5 py-1.5 text-caption text-text-secondary">
+                    <input
+                      type="checkbox"
+                      checked={weakOnly}
+                      onChange={(e) => setWeakOnly(e.target.checked)}
+                      className="h-3.5 w-3.5 accent-[rgb(var(--accent))]"
+                    />
+                    {t('roaming.matrix.filterWeak')}
+                  </label>
+                </div>
+              </div>
+
+              {/* Contadores */}
+              <div className="mb-4 flex flex-wrap gap-x-5 gap-y-1 text-caption text-text-muted">
+                <span>{t('roaming.matrix.aps', { count: aps.length })}</span>
+                <span>{t('roaming.matrix.clients', { count: rows.length })}</span>
+              </div>
+
+              {/* Matriz */}
+              {rows.length === 0 ? (
+                <p className="py-6 text-center text-caption text-text-muted">{t('roaming.matrix.noClients')}</p>
+              ) : (
+                <div className="overflow-x-auto">
+                  <table className="w-full border-separate border-spacing-0 text-left text-sm">
+                    <thead>
+                      <tr>
+                        <th className="sticky left-0 z-10 bg-surface pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">
+                          {t('roaming.matrix.colClient')}
+                        </th>
+                        {aps.map((ap) => (
+                          <th key={ap.bssid} className="pb-2.5 pl-2 pr-3 text-label font-medium text-text-secondary">
+                            <div className="flex flex-col gap-0.5">
+                              <span className="font-medium text-text-primary">{ap.hostname}</span>
+                              <span className="font-mono text-caption text-text-muted">
+                                {ap.band === '5 GHz' ? '5G' : '2.4G'} · ch{ap.channel}
+                              </span>
+                            </div>
+                          </th>
+                        ))}
+                      </tr>
+                    </thead>
+                    <tbody>
+                      {rows.map((r) => {
+                        const name = nameByMac.get(r.mac) ?? r.mac
+                        return (
+                          <tr key={r.mac} className="group">
+                            <th scope="row" className="sticky left-0 z-10 border-b border-border/60 bg-surface py-2 pr-3 text-left text-sm font-medium text-text-primary">
+                              <div className="flex flex-col">
+                                <span className="truncate">{name}</span>
+                                {name !== r.mac && <span className="font-mono text-caption text-text-muted">{r.mac}</span>}
+                              </div>
+                            </th>
+                            {aps.map((ap) => {
+                              const s = r.signals.get(ap.bssid)
+                              return (
+                                <td key={ap.bssid} className="border-b border-border/60 py-2 pl-2 pr-3">
+                                  {s !== undefined ? (
+                                    <span
+                                      title={`${name} → ${ap.hostname} (${ap.band}): ${s} dBm`}
+                                      className={cn('inline-block min-w-[3rem] rounded-md px-2 py-0.5 text-center font-mono text-mono-sm ring-1 ring-inset', signalClass(s))}
+                                    >
+                                      {s}
+                                    </span>
+                                  ) : (
+                                    <span className="text-text-muted">·</span>
+                                  )}
+                                </td>
+                              )
+                            })}
+                          </tr>
+                        )
+                      })}
+                    </tbody>
+                  </table>
+                </div>
+              )}
+
+              {/* Leyenda */}
+              <div className="mt-5 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.matrix.legendGood')}
+                </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.matrix.legendFair')}
+                </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.matrix.legendWeak')}
+                </span>
+              </div>
+            </motion.section>
+          )}
+        </>
+      )}
+    </div>
+  )
+}

+ 154 - 0
server-go/internal/adapters/dawn_test.go

@@ -0,0 +1,154 @@
+package adapters
+
+import (
+	"encoding/json"
+	"testing"
+)
+
+// TestDawnAPsFromNetwork parsea una salida sintética de `ubus call dawn
+// get_network` (mismo formato que producción) y verifica APs + hearing map.
+func TestDawnAPsFromNetwork(t *testing.T) {
+	// Un SSID con dos APs y clientes vistos por cada uno (hearing map). El
+	// mismo cliente (AA:BB:...) aparece bajo dos BSSIDs: DAWN lo reporta desde
+	// cada AP que lo ve. Un segundo SSID sin clientes. Un objeto sin "channel"
+	// (ruido) que debe ignorarse.
+	raw := `{
+		"home": {
+			"AA:11:BB:22:CC:01": {
+				"channel": 1,
+				"freq": 2412,
+				"channel_utilization": 70,
+				"num_sta": 2,
+				"ht_support": true,
+				"vht_support": false,
+				"local": true,
+				"iface": "wlan0",
+				"hostname": "ap-living",
+				"AA:BB:CC:DD:00:01": {"signal": -40, "ht": true, "vht": false},
+				"AA:BB:CC:DD:00:02": {"signal": -81, "ht": false, "vht": false}
+			},
+			"AA:11:BB:22:CC:02": {
+				"channel": 36,
+				"freq": 5180,
+				"channel_utilization": 6,
+				"num_sta": 1,
+				"ht_support": true,
+				"vht_support": true,
+				"local": false,
+				"iface": "wlan1",
+				"hostname": "ap-living",
+				"AA:BB:CC:DD:00:01": {"signal": -55, "ht": true, "vht": true}
+			}
+		},
+		"guest": {
+			"AA:11:BB:22:CC:03": {
+				"channel": 6,
+				"freq": 2437,
+				"channel_utilization": 20,
+				"num_sta": 0,
+				"local": true,
+				"iface": "phy1-ap1",
+				"hostname": "ap-guest"
+			}
+		}
+	}`
+	var data map[string]map[string]json.RawMessage
+	if err := json.Unmarshal([]byte(raw), &data); err != nil {
+		t.Fatalf("unmarshal fixture: %v", err)
+	}
+
+	aps := dawnAPsFromNetwork(data)
+	if len(aps) != 3 {
+		t.Fatalf("esperaba 3 APs, obtuvo %d", len(aps))
+	}
+
+	// Orden: hostname asc, luego banda. ap-guest (2.4) < ap-living (2.4) < ap-living (5).
+	want := []struct {
+		host, band string
+		ch         int
+		util       float64
+		count      int
+		nClients   int
+	}{
+		{"ap-guest", "2.4 GHz", 6, 20, 0, 0},
+		{"ap-living", "2.4 GHz", 1, 70, 2, 2},
+		{"ap-living", "5 GHz", 36, 6, 1, 1},
+	}
+	for i, w := range want {
+		ap := aps[i]
+		if ap.Hostname != w.host || ap.Band != w.band {
+			t.Errorf("AP[%d] = %s %s, queria %s %s", i, ap.Hostname, ap.Band, w.host, w.band)
+		}
+		if ap.Channel != w.ch {
+			t.Errorf("AP[%d] channel = %d, queria %d", i, ap.Channel, w.ch)
+		}
+		if ap.UtilizationPct != w.util {
+			t.Errorf("AP[%d] util = %v, queria %v", i, ap.UtilizationPct, w.util)
+		}
+		if ap.ClientCount != w.count {
+			t.Errorf("AP[%d] clientCount = %d, queria %d", i, ap.ClientCount, w.count)
+		}
+		if len(ap.Clients) != w.nClients {
+			t.Errorf("AP[%d] clients = %d, queria %d", i, len(ap.Clients), w.nClients)
+		}
+	}
+
+	// El cliente AA:BB:CC:DD:00:01 aparece bajo dos APs (hearing map): señal
+	// -40 desde el 2.4 del living y -55 desde el 5.
+	living24 := aps[1]
+	if living24.SSID != "home" || living24.BSSID != "AA:11:BB:22:CC:01" {
+		t.Fatalf("AP living 2.4 inesperado: %+v", living24)
+	}
+	sig := map[string]int{}
+	for _, c := range living24.Clients {
+		sig[c.MAC] = c.Signal
+	}
+	if sig["AA:BB:CC:DD:00:01"] != -40 {
+		t.Errorf("señal cliente 01 desde living 2.4 = %d, queria -40", sig["AA:BB:CC:DD:00:01"])
+	}
+	if sig["AA:BB:CC:DD:00:02"] != -81 {
+		t.Errorf("señal cliente 02 desde living 2.4 = %d, queria -81", sig["AA:BB:CC:DD:00:02"])
+	}
+	living5 := aps[2]
+	sig5 := map[string]int{}
+	for _, c := range living5.Clients {
+		sig5[c.MAC] = c.Signal
+	}
+	if sig5["AA:BB:CC:DD:00:01"] != -55 {
+		t.Errorf("señal cliente 01 desde living 5 = %d, queria -55", sig5["AA:BB:CC:DD:00:01"])
+	}
+
+	// MAC normalizada a mayúsculas.
+	for _, c := range living24.Clients {
+		if c.MAC != upperMAC(c.MAC) {
+			t.Errorf("MAC no normalizada: %s", c.MAC)
+		}
+	}
+
+	// clients nunca nil (serializa [] en JSON, no null): el frontend itera sin
+	// guardarse de null.
+	guest := aps[0] // ap-guest, sin clientes
+	if guest.Clients == nil {
+		t.Fatalf("AP sin clientes tiene Clients nil; debe ser []")
+	}
+}
+
+func upperMAC(s string) string {
+	out := make([]byte, len(s))
+	for i := 0; i < len(s); i++ {
+		c := s[i]
+		if c >= 'a' && c <= 'z' {
+			c -= 32
+		}
+		out[i] = c
+	}
+	return string(out)
+}
+
+// TestDawnAPsFromNetworkVacio: sin datos → slice vacío (no nil en JSON).
+func TestDawnAPsFromNetworkVacio(t *testing.T) {
+	aps := dawnAPsFromNetwork(map[string]map[string]json.RawMessage{})
+	if len(aps) != 0 {
+		t.Fatalf("esperaba 0 APs, obtuvo %d", len(aps))
+	}
+}

+ 75 - 26
server-go/internal/adapters/live.go

@@ -1682,30 +1682,31 @@ func (l *Live) GetAdguardClients(ctx context.Context) ([]AdguardClient, error) {
 	return gl.QueryClients(ctx)
 	return gl.QueryClients(ctx)
 }
 }
 
 
-// dawnNetwork es la respuesta de `ubus call dawn get_network`.
-type dawnNetwork map[string]map[string]struct {
-	Hostname           string  `json:"hostname"`
-	Freq               float64 `json:"freq"`
-	Channel            int     `json:"channel"`
-	ChannelUtilization float64 `json:"channel_utilization"`
-	NumSta             int     `json:"num_sta"`
-	Local              bool    `json:"local"`
-	Iface              string  `json:"iface"`
+// dawnAPField es el conjunto de keys escalares que describen un AP en la
+// salida de `ubus call dawn get_network`. El resto de keys de un BSSID cuyo
+// valor es un objeto (con "signal") son clientes del hearing map.
+var dawnAPField = map[string]bool{
+	"channel": true, "freq": true, "channel_utilization": true,
+	"num_sta": true, "ht_support": true, "vht_support": true,
+	"local": true, "iface": true, "hostname": true,
+	"neighbor_report": true, "op_class": true,
 }
 }
 
 
 // GetDawn: red DAWN (roaming/band-steering). nil si ningún router responde.
 // GetDawn: red DAWN (roaming/band-steering). nil si ningún router responde.
+//
+// La salida de `ubus call dawn get_network` mezcla, por cada BSSID, los campos
+// del AP (escalares) con los clientes anidados (MAC → {signal, ht, vht, ...}).
+// DAWN distribuye el hearing map entre nodos, así que la respuesta del primer
+// router que contesta ya contiene toda la malla (APs + clientes vistos por
+// cada uno). Por eso solo usamos firstData.
 func (l *Live) GetDawn(context.Context) (*Dawn, error) {
 func (l *Live) GetDawn(context.Context) (*Dawn, error) {
 	l.mu.Lock()
 	l.mu.Lock()
 	routers := append([]RouterConfig(nil), l.routers...)
 	routers := append([]RouterConfig(nil), l.routers...)
-	polled := l.lastPolled
 	l.mu.Unlock()
 	l.mu.Unlock()
-	var firstData dawnNetwork
+
+	var firstData map[string]map[string]json.RawMessage
 	mesh := []DawnMesh{}
 	mesh := []DawnMesh{}
 	for _, cfg := range routers {
 	for _, cfg := range routers {
-		p := polled[cfg.ID]
-		if p == nil {
-			continue
-		}
 		name := cfg.Name
 		name := cfg.Name
 		if name == "" {
 		if name == "" {
 			name = cfg.ID
 			name = cfg.ID
@@ -1715,7 +1716,7 @@ func (l *Live) GetDawn(context.Context) (*Dawn, error) {
 			mesh = append(mesh, DawnMesh{RouterID: cfg.ID, Name: name, Dawn: false, ApsSeen: 0})
 			mesh = append(mesh, DawnMesh{RouterID: cfg.ID, Name: name, Dawn: false, ApsSeen: 0})
 			continue
 			continue
 		}
 		}
-		var data dawnNetwork
+		var data map[string]map[string]json.RawMessage
 		if json.Unmarshal([]byte(out), &data) != nil {
 		if json.Unmarshal([]byte(out), &data) != nil {
 			mesh = append(mesh, DawnMesh{RouterID: cfg.ID, Name: name, Dawn: false, ApsSeen: 0})
 			mesh = append(mesh, DawnMesh{RouterID: cfg.ID, Name: name, Dawn: false, ApsSeen: 0})
 			continue
 			continue
@@ -1732,18 +1733,66 @@ func (l *Live) GetDawn(context.Context) (*Dawn, error) {
 	if firstData == nil {
 	if firstData == nil {
 		return nil, nil
 		return nil, nil
 	}
 	}
+	aps := dawnAPsFromNetwork(firstData)
+	return &Dawn{APs: aps, Mesh: mesh}, nil
+}
+
+// dawnAPsFromNetwork parsea la salida de `ubus call dawn get_network` ya
+// deserializada a json.RawMessage (SSID → BSSID → campos mixtos). Devuelve los
+// APs con sus clientes del hearing map. Función pura para testear sin SSH.
+func dawnAPsFromNetwork(firstData map[string]map[string]json.RawMessage) []DawnAP {
 	aps := []DawnAP{}
 	aps := []DawnAP{}
 	for ssid, bssids := range firstData {
 	for ssid, bssids := range firstData {
-		for bssid, ap := range bssids {
-			band := "2.4 GHz"
-			if ap.Freq >= 5000 {
-				band = "5 GHz"
+		for bssid, raw := range bssids {
+			var fields map[string]json.RawMessage
+			if json.Unmarshal(raw, &fields) != nil {
+				continue
 			}
 			}
-			aps = append(aps, DawnAP{
-				SSID: ssid, BSSID: bssid, Hostname: ap.Hostname, Band: band,
-				Channel: ap.Channel, UtilizationPct: ap.ChannelUtilization,
-				Clients: ap.NumSta, Local: ap.Local, Iface: ap.Iface,
-			})
+			// "channel" presente y no cero → es un AP (no un cliente suelto).
+			chRaw, ok := fields["channel"]
+			if !ok {
+				continue
+			}
+			var channel int
+			json.Unmarshal(chRaw, &channel)
+			if channel == 0 {
+				continue
+			}
+			ap := DawnAP{SSID: ssid, BSSID: bssid, Channel: channel, Clients: []DawnClient{}}
+			var freq float64
+			json.Unmarshal(fields["freq"], &freq)
+			json.Unmarshal(fields["channel_utilization"], &ap.UtilizationPct)
+			json.Unmarshal(fields["num_sta"], &ap.ClientCount)
+			json.Unmarshal(fields["local"], &ap.Local)
+			json.Unmarshal(fields["iface"], &ap.Iface)
+			json.Unmarshal(fields["hostname"], &ap.Hostname)
+			if freq >= 5000 {
+				ap.Band = "5 GHz"
+			} else {
+				ap.Band = "2.4 GHz"
+			}
+			// Clientes anidados: cualquier key MAC cuyo valor sea un objeto
+			// con "signal" negativa (en -dBm).
+			for mac, valRaw := range fields {
+				if dawnAPField[mac] {
+					continue
+				}
+				s := strings.TrimSpace(string(valRaw))
+				if !strings.HasPrefix(s, "{") {
+					continue
+				}
+				var c struct {
+					Signal int  `json:"signal"`
+					HT     bool `json:"ht"`
+					VHT    bool `json:"vht"`
+				}
+				if json.Unmarshal(valRaw, &c) == nil && c.Signal < 0 {
+					ap.Clients = append(ap.Clients, DawnClient{
+						MAC: strings.ToUpper(mac), Signal: c.Signal, HT: c.HT, VHT: c.VHT,
+					})
+				}
+			}
+			aps = append(aps, ap)
 		}
 		}
 	}
 	}
 	sort.Slice(aps, func(i, j int) bool {
 	sort.Slice(aps, func(i, j int) bool {
@@ -1752,5 +1801,5 @@ func (l *Live) GetDawn(context.Context) (*Dawn, error) {
 		}
 		}
 		return aps[i].Band < aps[j].Band
 		return aps[i].Band < aps[j].Band
 	})
 	})
-	return &Dawn{APs: aps, Mesh: mesh}, nil
+	return aps
 }
 }

+ 20 - 9
server-go/internal/adapters/types.go

@@ -375,17 +375,28 @@ type WGTotals struct {
 // DAWN (GET /api/dawn; SPEC §7.6) y AdGuard clients (§2.13)
 // DAWN (GET /api/dawn; SPEC §7.6) y AdGuard clients (§2.13)
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 
 
+// DawnClient es un cliente visto por un AP en el hearing map de DAWN.
+// Signal en -dBm (más cercano a 0 = mejor). Un cliente puede aparecer bajo
+// varios BSSIDs: cada AP que lo ve reporta su propia medición de señal.
+type DawnClient struct {
+	MAC    string `json:"mac"`
+	Signal int    `json:"signal"` // -dBm (ej. -65)
+	HT     bool   `json:"ht"`
+	VHT    bool   `json:"vht"`
+}
+
 // DawnAP es un punto de acceso visto por DAWN.
 // DawnAP es un punto de acceso visto por DAWN.
 type DawnAP struct {
 type DawnAP struct {
-	SSID           string  `json:"ssid"`
-	BSSID          string  `json:"bssid"`
-	Hostname       string  `json:"hostname"`
-	Band           string  `json:"band"` // freq >= 5000 ? "5 GHz" : "2.4 GHz"
-	Channel        int     `json:"channel"`
-	UtilizationPct float64 `json:"utilizationPct"`
-	Clients        int     `json:"clients"`
-	Local          bool    `json:"local"`
-	Iface          string  `json:"iface"`
+	SSID           string        `json:"ssid"`
+	BSSID          string        `json:"bssid"`
+	Hostname       string        `json:"hostname"`
+	Band           string        `json:"band"` // freq >= 5000 ? "5 GHz" : "2.4 GHz"
+	Channel        int           `json:"channel"`
+	UtilizationPct float64       `json:"utilizationPct"`
+	ClientCount    int           `json:"clientCount"` // num_sta reportado por DAWN
+	Clients        []DawnClient  `json:"clients"`     // clientes vistos por este AP (hearing map)
+	Local          bool          `json:"local"`
+	Iface          string        `json:"iface"`
 }
 }
 
 
 // DawnMesh marca por router si tiene DAWN y cuántos APs ve.
 // DawnMesh marca por router si tiene DAWN y cuántos APs ve.