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

feat(channelplan): full-width spectrum, all-channel scores strip and better own detection (#1078)

- The spectrum chart takes the whole width; the score panel moves to a
  full-width strip below it, grouped by congestion tier (optimal /
  moderate / busy). Every channel is now scored, not just the
  recommendable candidates: all 13 channels at 2.4 GHz and every
  non-overlapping width block at 5 GHz, DFS ranges included as
  informational items. Blocks stride by their own width so they no
  longer overlap each other, and only UNII-1/UNII-3 blocks (plus the
  orthodox 1/6/11 at 2.4 GHz) are recommendable - the 5350-5470 MHz
  range is not RLAN in ETSI. Clicking a channel in the strip focuses
  its block in the spectrum and dims the rest.
- Bell labels stack in two rows above each peak, strongest first with a
  tighter collision threshold, so dense 2.4 GHz airspace gets labeled
  instead of only the own networks.
- Own-network detection: once any BSSID of an SSID prefix-matches the
  fleet, the whole SSID is flagged own (guest BSS of the same unit keep
  different MAC blocks). SSIDs with no fleet MAC match at all still
  cannot be detected until the agent reports BSSIDs.
- The legend gains hide-all / show-all / only-mine toggles.

closes #1076
Nacho 2 месяцев назад
Родитель
Сommit
9ea1c8b11a

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

@@ -2034,7 +2034,15 @@
     },
     "sortable": "sort",
     "sortAsc": "ascending order, click to reverse",
-    "sortDesc": "descending order, click to reverse"
+    "sortDesc": "descending order, click to reverse",
+    "tier": {
+      "optimal": "Optimal",
+      "moderate": "Moderate",
+      "busy": "Busy"
+    },
+    "hideAll": "Hide all",
+    "showAll": "Show all",
+    "onlyMine": "Only mine"
   },
   "firmwareUpgrades": {
     "title": "Firmware upgrades",

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

@@ -2034,7 +2034,15 @@
     },
     "sortable": "ordenar",
     "sortAsc": "orden ascendente, clic para invertir",
-    "sortDesc": "orden descendente, clic para invertir"
+    "sortDesc": "orden descendente, clic para invertir",
+    "tier": {
+      "optimal": "Óptimos",
+      "moderate": "Moderados",
+      "busy": "Saturados"
+    },
+    "hideAll": "Ocultar todas",
+    "showAll": "Mostrar todas",
+    "onlyMine": "Solo mías"
   },
   "firmwareUpgrades": {
     "title": "Actualizaciones de firmware",

+ 38 - 14
app/src/components/channels/ChannelSpectrum.tsx

@@ -100,6 +100,7 @@ export function ChannelSpectrum({
   widthMhz,
   hidden,
   selected,
+  focus,
   onHover,
   tSuggest,
   tDfs,
@@ -112,6 +113,8 @@ export function ChannelSpectrum({
   widthMhz: number
   hidden: Set<string>
   selected: string | null
+  /** Canal con foco (click en la tira de puntuación): el resto se atenúa. */
+  focus: number | null
   onHover: (net: SpectrumNet | null, x: number, y: number) => void
   tSuggest: string
   tDfs: string
@@ -223,7 +226,6 @@ export function ChannelSpectrum({
 
       // Campanas.
       const visible = nets.filter((n) => !hidden.has(n.key))
-      const placed: { px: number; py: number }[] = []
       for (const n of visible) {
         if (n.freq <= 0) continue
         const sigma = Math.max(n.widthMhz * 0.62, 8)
@@ -243,26 +245,48 @@ export function ChannelSpectrum({
         grad.addColorStop(0, withAlpha(n.color, 0.3))
         grad.addColorStop(1, withAlpha(n.color, 0.04))
         g.fillStyle = grad
-        g.fill()
         g.strokeStyle = n.color
         g.lineWidth = n.own ? 2.2 : 1.5
-        g.globalAlpha = selected && selected !== n.key ? 0.22 : 1
+        const dimmed = (selected && selected !== n.key) || (focus != null && n.channel !== focus)
+        g.globalAlpha = dimmed ? 0.14 : 1
+        g.fill()
         g.stroke()
         g.globalAlpha = 1
 
-        if (n.own || n.signal > -75) {
+      }
+
+      // Etiquetas: se asignan de la más fuerte a la más débil en DOS filas
+      // sobre el pico (la propia siempre en la fila interior). Umbral -80 y
+      // clash horizontal corto: en 2.4 GHz denso el draw-order anterior solo
+      // etiquetaba a las propias (#1076).
+      {
+        const labelables = visible
+          .filter((n) => n.freq > 0 && (n.own || n.signal > -80))
+          .sort((a, b) => Number(b.own ?? false) - Number(a.own ?? false) || b.signal - a.signal)
+        const rows: { px: number; py: number }[][] = [[], []]
+        for (const n of labelables) {
           const px = Math.min(Math.max(x(n.freq), PAD.l + 42), w - PAD.r - 42)
-          const py = peak - 8
-          const clash = placed.some((p) => Math.abs(p.px - px) < 95 && Math.abs(p.py - py) < 15)
-          if (!clash || n.own) {
-            g.fillStyle = n.color
-            g.textAlign = 'center'
-            g.font = n.own ? CANVAS_FONT_BOLD : CANVAS_FONT_SEMI
-            g.fillText(n.ssid, px, py)
-            g.font = CANVAS_FONT
-            placed.push({ px, py })
+          const peakY = y(Math.max(n.signal, DBM_TOP))
+          let done = false
+          for (const rowIdx of n.own ? [0, 1] : [0, 1]) {
+            const py = peakY - 8 - rowIdx * 13
+            const clash = rows[rowIdx]!.some((q) => Math.abs(q.px - px) < 60)
+            if (!clash || (n.own && rowIdx === 0 && !rows[0]!.some((q) => Math.abs(q.px - px) < 40))) {
+              g.fillStyle = n.color
+              g.textAlign = 'center'
+              g.font = n.own ? CANVAS_FONT_BOLD : '10px Inter, ui-sans-serif, system-ui, sans-serif'
+              g.globalAlpha = selected && selected !== n.key ? 0.3 : 1
+              g.fillText(n.ssid, px, py)
+              g.globalAlpha = 1
+              g.font = CANVAS_FONT
+              rows[rowIdx]!.push({ px, py })
+              done = true
+              break
+            }
           }
+          void done
         }
+        void labelables
       }
 
       // Marcador del canal actual (red propia del radio).
@@ -331,7 +355,7 @@ export function ChannelSpectrum({
       ro.disconnect()
       mo.disconnect()
     }
-  }, [band, nets, suggested, widthMhz, hidden, selected, tSuggest, tDfs, tActual, tDbm])
+  }, [band, nets, suggested, widthMhz, hidden, selected, focus, tSuggest, tDfs, tActual, tDbm])
 
   const onMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
     const geom = geomRef.current

+ 144 - 77
app/src/pages/ChannelPlan.tsx

@@ -34,11 +34,13 @@ interface Scan {
   own?: boolean
 }
 
-interface Candidate {
+interface Score {
   channel: number
   score: number
   neighbors: number
   strongest: number // dBm de la vecina más fuerte considerada
+  dfs: boolean
+  recommendable: boolean
 }
 
 interface RadioRec {
@@ -50,7 +52,7 @@ interface RadioRec {
   recommended: number
   currentScore: number
   bestScore: number
-  candidates?: Candidate[]
+  scores?: Score[]
 }
 
 interface ChannelPlanData {
@@ -151,6 +153,8 @@ export default function ChannelPlan() {
   const [selected, setSelected] = useState<string | null>(null)
   const [hover, setHover] = useState<{ net: SpectrumNet; x: number; y: number } | null>(null)
   const [sort, setSort] = useState<{ key: 'signal' | 'ssid' | 'channel'; dir: 'asc' | 'desc' } | null>(null)
+  const [focus, setFocus] = useState<number | null>(null)
+  const [onlyMine, setOnlyMine] = useState(false)
   const [lastRefresh, setLastRefresh] = useState<number>(0)
   const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null)
 
@@ -245,24 +249,47 @@ export default function ChannelPlan() {
     return [...neighbors, own]
   }, [active, bandScans, t])
 
-  // Puntuación normalizada (0-100) de cada candidato: 100 = el más limpio.
+  const allKeys = useMemo(() => new Set(nets.map((n) => n.key)), [nets])
+  const nonOwnKeys = useMemo(() => new Set(nets.filter((n) => !n.own).map((n) => n.key)), [nets])
+
+  // "Solo mías": oculta las vecinas mientras el toggle esté activo.
+  useEffect(() => {
+    if (onlyMine) setHidden(new Set(nonOwnKeys))
+  }, [onlyMine, nonOwnKeys])
+
+  // Puntuación normalizada (0-100) de cada canal/bloque de la banda: 100 =
+  // el más limpio. Incluye DFS informativos (#1076); el sugerido es el mejor
+  // recomendable.
   const scored = useMemo(() => {
-    if (!active?.candidates || active.candidates.length === 0) return []
-    const scores = active.candidates.map((c) => c.score)
-    if (active.currentScore > 0 && active.currentScore < 900000) scores.push(active.currentScore)
-    const worst = Math.max(...scores)
-    const best = Math.min(...scores)
+    if (!active?.scores || active.scores.length === 0) return []
+    const raw = active.scores.map((c) => c.score)
+    if (active.currentScore > 0 && active.currentScore < 900000) raw.push(active.currentScore)
+    const worst = Math.max(...raw)
+    const best = Math.min(...raw)
     const pctOf = (score: number) => (worst <= best ? 100 : Math.round((100 * (worst - score)) / (worst - best)))
-    return active.candidates
+    return active.scores
       .map((c) => ({
         ...c,
         pct: pctOf(c.score),
         isCurrent: c.channel === active.channel,
         isBest: c.channel === active.recommended && c.channel !== active.channel,
       }))
-      .sort((a, b) => b.pct - a.pct)
+      .sort((a, b) => b.pct - a.pct || a.channel - b.channel)
   }, [active])
 
+  // Grupos por congestión para la tira de puntuación (#1076).
+  const tiers = useMemo(() => {
+    const t: { key: string; items: typeof scored }[] = [
+      { key: 'optimal', items: [] },
+      { key: 'moderate', items: [] },
+      { key: 'busy', items: [] },
+    ]
+    for (const s of scored) {
+      (s.pct >= 80 ? t[0]! : s.pct >= 55 ? t[1]! : t[2]!).items.push(s)
+    }
+    return t.filter((g) => g.items.length > 0)
+  }, [scored])
+
   const currentScoreValid = !!active && active.currentScore > 0 && active.currentScore < 900000
   const currentPct = useMemo(() => {
     if (!active) return 0
@@ -368,6 +395,7 @@ export default function ChannelPlan() {
                     setActiveRadio(key)
                     setHidden(new Set())
                     setSelected(null)
+                    setFocus(null)
                   }}
                   className={cn(
                     'rounded-lg px-3.5 py-1.5 text-[13px] font-semibold transition-all',
@@ -526,8 +554,9 @@ export default function ChannelPlan() {
             <p className="rounded-2xl border border-border bg-surface px-4 py-3 text-caption text-warn">{t('channelPlan.noScans')}</p>
           ) : (
             <>
-              {/* Espectro + panel de puntuación */}
-              <div className="grid gap-3 xl:grid-cols-[minmax(0,1fr)_320px]">
+              {/* Espectro a todo lo ancho (#1076); la puntuación baja a una
+                  tira debajo, agrupada por congestión */}
+              <div>
                 <div className="rounded-2xl border border-border bg-surface">
                   <div className="flex items-start justify-between gap-3 px-5 pt-4">
                     <div>
@@ -547,6 +576,7 @@ export default function ChannelPlan() {
                       widthMhz={active.widthMhz}
                       hidden={hidden}
                       selected={selected}
+                      focus={focus}
                       onHover={(net, x, y) => setHover(net ? { net, x, y } : null)}
                       tSuggest={t('channelPlan.suggested')}
                       tDfs={t('channelPlan.tagDfs')}
@@ -584,8 +614,110 @@ export default function ChannelPlan() {
                     </div>
                   </div>
 
+                  {/* Puntuación por canal: tira a todo lo ancho agrupada por
+                      congestión; clic enfoca el bloque en el espectro (#1076) */}
+                  <div className="border-t border-border px-5 py-3">
+                    <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
+                      <h2 className="text-sm font-bold text-text-primary">{t('channelPlan.scoresTitle')}</h2>
+                      <span className="text-caption text-text-muted">
+                        {active.name === '5 GHz'
+                          ? t('channelPlan.scoresBlocks', { w: active.widthMhz > 0 ? active.widthMhz : 80 })
+                          : t('channelPlan.scoresChannels')}
+                        {' · '}
+                        {t('channelPlan.scoresFoot')}
+                      </span>
+                    </div>
+                    {tiers.map((g) => (
+                      <div key={g.key} className="mt-2 flex flex-wrap items-center gap-1.5">
+                        <span
+                          className={cn(
+                            'w-24 shrink-0 text-[11px] font-bold uppercase tracking-wide',
+                            g.key === 'optimal' ? 'text-ok' : g.key === 'moderate' ? 'text-warn' : 'text-danger',
+                          )}
+                        >
+                          {t(`channelPlan.tier.${g.key}`)}
+                        </span>
+                        {g.items.map((s) => (
+                          <button
+                            key={s.channel}
+                            onClick={() => setFocus(focus === s.channel ? null : s.channel)}
+                            title={
+                              s.neighbors === 0
+                                ? t('channelPlan.whyAlone')
+                                : t('channelPlan.whyNeighbors', { n: s.neighbors, dbm: s.strongest })
+                            }
+                            className={cn(
+                              'inline-flex items-center gap-1.5 rounded-lg border px-2 py-1 text-xs transition-colors',
+                              focus === s.channel
+                                ? 'border-accent/60 bg-accent/10'
+                                : s.isCurrent
+                                  ? 'border-accent/40 bg-accent/5'
+                                  : s.isBest
+                                    ? 'border-ok/40 bg-ok/5'
+                                    : 'border-border hover:border-border-strong',
+                              !s.recommendable && 'opacity-70',
+                            )}
+                          >
+                            <span className="font-mono font-bold text-text-primary">{s.channel}</span>
+                            {s.isCurrent && (
+                              <span className="rounded bg-accent/15 px-1 py-px text-[9px] font-bold uppercase text-accent">
+                                {t('channelPlan.tagCurrent')}
+                              </span>
+                            )}
+                            {s.isBest && (
+                              <span className="rounded bg-ok/15 px-1 py-px text-[9px] font-bold uppercase text-ok">
+                                ★ {t('channelPlan.tagBest')}
+                              </span>
+                            )}
+                            {s.dfs && (
+                              <span className="rounded bg-elevated px-1 py-px text-[9px] font-bold uppercase text-text-muted">
+                                {t('channelPlan.tagDfs')}
+                              </span>
+                            )}
+                            <span
+                              className={cn(
+                                'font-mono font-bold',
+                                s.pct >= 80 ? 'text-ok' : s.pct >= 55 ? 'text-warn' : 'text-danger',
+                              )}
+                            >
+                              {s.pct}
+                            </span>
+                          </button>
+                        ))}
+                      </div>
+                    ))}
+                    {scored.length === 0 && <p className="mt-1 text-caption text-text-muted">{t('channelPlan.noBandScans')}</p>}
+                  </div>
+
                   {/* Leyenda interactiva */}
                   <div className="flex flex-wrap gap-1.5 border-t border-border px-5 py-3">
+                    <button
+                      onClick={() => {
+                        setOnlyMine(false)
+                        setHidden(new Set(allKeys))
+                      }}
+                      className="inline-flex items-center rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-text-secondary transition-colors hover:border-border-strong hover:text-text-primary"
+                    >
+                      {t('channelPlan.hideAll')}
+                    </button>
+                    <button
+                      onClick={() => {
+                        setOnlyMine(false)
+                        setHidden(new Set())
+                      }}
+                      className="inline-flex items-center rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-text-secondary transition-colors hover:border-border-strong hover:text-text-primary"
+                    >
+                      {t('channelPlan.showAll')}
+                    </button>
+                    <button
+                      onClick={() => setOnlyMine((v) => !v)}
+                      className={cn(
+                        'inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold transition-colors',
+                        onlyMine ? 'border-accent/50 bg-accent/10 text-accent' : 'border-border text-text-secondary hover:border-border-strong hover:text-text-primary',
+                      )}
+                    >
+                      {t('channelPlan.onlyMine')}
+                    </button>
                     {nets.map((n) => (
                       <button
                         key={n.key}
@@ -612,71 +744,6 @@ export default function ChannelPlan() {
                     ))}
                   </div>
                 </div>
-
-                {/* Puntuación por canal */}
-                <div className="flex flex-col rounded-2xl border border-border bg-surface">
-                  <div className="px-4 pt-4">
-                    <h2 className="text-sm font-bold text-text-primary">{t('channelPlan.scoresTitle')}</h2>
-                    <p className="mt-0.5 text-caption text-text-muted">
-                      {active.name === '5 GHz'
-                        ? t('channelPlan.scoresBlocks', { w: active.widthMhz > 0 ? active.widthMhz : 80 })
-                        : t('channelPlan.scoresChannels')}
-                    </p>
-                  </div>
-                  <div className="flex flex-col gap-2 overflow-auto p-3">
-                    {scored.map((s) => (
-                      <div
-                        key={s.channel}
-                        className={cn(
-                          'rounded-xl border px-3 py-2.5',
-                          s.isCurrent ? 'border-accent/40 bg-accent/5' : s.isBest ? 'border-ok/30' : 'border-border',
-                        )}
-                      >
-                        <div className="flex items-center gap-2">
-                          <span className="text-[13px] font-bold text-text-primary">
-                            {active.name === '2.4 GHz' || active.name === '6 GHz'
-                              ? t('channelPlan.channelWord', { ch: s.channel })
-                              : s.channel}
-                            <span className="ml-1 text-[11px] font-medium text-text-muted">
-                              {active.widthMhz > 0 ? `${active.widthMhz} MHz` : '20 MHz'}
-                            </span>
-                          </span>
-                          {s.isCurrent && (
-                            <span className="rounded-md bg-accent/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-accent">
-                              {t('channelPlan.tagCurrent')}
-                            </span>
-                          )}
-                          {s.isBest && (
-                            <span className="rounded-md bg-ok/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-ok">
-                              ★ {t('channelPlan.tagBest')}
-                            </span>
-                          )}
-                          <span
-                            className={cn(
-                              'ml-auto text-sm font-extrabold',
-                              s.pct >= 80 ? 'text-ok' : s.pct >= 55 ? 'text-warn' : 'text-danger',
-                            )}
-                          >
-                            {s.pct}
-                          </span>
-                        </div>
-                        <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-canvas">
-                          <div
-                            className={cn('h-full rounded-full', s.pct >= 80 ? 'bg-ok' : s.pct >= 55 ? 'bg-warn' : 'bg-danger')}
-                            style={{ width: `${s.pct}%` }}
-                          />
-                        </div>
-                        <div className="mt-1 text-[11.5px] text-text-muted">
-                          {s.neighbors === 0 ? t('channelPlan.whyAlone') : t('channelPlan.whyNeighbors', { n: s.neighbors, dbm: s.strongest })}
-                        </div>
-                      </div>
-                    ))}
-                    {scored.length === 0 && <p className="px-1 py-3 text-caption text-text-muted">{t('channelPlan.noBandScans')}</p>}
-                  </div>
-                  <div className="mt-auto border-t border-border px-4 py-3 text-[11.5px] leading-relaxed text-text-muted">
-                    {t('channelPlan.scoresFoot')}
-                  </div>
-                </div>
               </div>
 
               {/* Tabla de redes */}

+ 116 - 24
server-go/internal/channelplan/store.go

@@ -111,7 +111,28 @@ func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, e
 		r.Own = isOwnMeshBSSID(r.BSSID, prefixes)
 		out = append(out, r)
 	}
-	return out, rows.Err()
+	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.
@@ -123,22 +144,92 @@ type Radio struct {
 	Recommended  int    `json:"recommended"` // canal recomendado; 0 = sin datos
 	CurrentScore int    `json:"currentScore"`
 	BestScore    int    `json:"bestScore"`
-	// Candidates es la puntuación de CADA canal candidato (no solo la
-	// mejor), para el panel de puntuación del informe (#1070).
-	Candidates []Candidate `json:"candidates,omitempty"`
+	// 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"`
 }
 
-// Candidate puntúa un canal candidato de la banda del radio. Los candidatos
-// son no-DFS por construcción (#518/#631): el motor recomienda solo bloques
-// usables sin espera de radar.
-type Candidate struct {
-	Channel   int `json:"channel"`
-	Score     int `json:"score"` // weighted neighbor score; menor = más limpio
-	Neighbors int `json:"neighbors"`
-	Strongest int `json:"strongest"` // dBm de la vecina más fuerte considerada
+// 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 solo los no-DFS (no
+// mantenemos la tabla PSC).
+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
+	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
@@ -186,23 +277,24 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 		if rec.Iface == "" {
 			rec.Iface = ifaceForBand(band) // placeholder; el agente no reporta iface por radio
 		}
-		candidates := candidateChannels(band, r.WidthMhz)
+		blocks := bandBlocks(band, r.WidthMhz)
 		bestCh, bestScore := 0, math.MaxInt
 		currentScore := math.MaxInt
-		cands := make([]Candidate, 0, len(candidates))
-		for _, ch := range candidates {
-			score, neighbors, strongest := channelScoreDetailed(byBand[band], ch)
-			cands = append(cands, Candidate{Channel: ch, Score: score, Neighbors: neighbors, Strongest: strongest})
-			if ch == r.Channel {
-				currentScore = score
+		scores := make([]ChannelScore, 0, len(blocks))
+		for _, b := range blocks {
+			b.Score, b.Neighbors, b.Strongest = channelScoreDetailed(byBand[band], b.Channel)
+			if b.Channel == r.Channel {
+				currentScore = b.Score
 			}
-			if score < bestScore {
-				bestScore = score
-				bestCh = ch
+			// 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(cands) > 0 {
-			rec.Candidates = cands
+		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

+ 96 - 12
server-go/internal/channelplan/store_test.go

@@ -36,10 +36,10 @@ func TestSaveAndRecentScans(t *testing.T) {
 	}
 }
 
-// TestRecommendDevuelveCandidatos (#1070): el informe muestra la puntuación
-// de CADA canal candidato (panel lateral). Los candidatos son no-DFS por
-// construcción (#518/#631).
-func TestRecommendDevuelveCandidatos(t *testing.T) {
+// TestRecommendDevuelveScores (#1070/#1076): el informe puntúa TODOS los
+// bloques de la banda a su ancho, DFS incluidos (informativos); los
+// recomendables son no-DFS y el mejor de ellos es el Recommended.
+func TestRecommendDevuelveScores(t *testing.T) {
 	d, err := db.Open(t.TempDir())
 	if err != nil {
 		t.Fatalf("db: %v", err)
@@ -51,19 +51,103 @@ func TestRecommendDevuelveCandidatos(t *testing.T) {
 	if err != nil {
 		t.Fatalf("recommend: %v", err)
 	}
-	if len(recs) != 1 || len(recs[0].Candidates) == 0 {
-		t.Fatalf("esperaba candidatos, got %+v", recs)
+	if len(recs) != 1 || len(recs[0].Scores) == 0 {
+		t.Fatalf("esperaba scores, got %+v", recs)
 	}
-	byCh := map[int]channelplan.Candidate{}
-	for _, c := range recs[0].Candidates {
-		if c.Channel >= 52 && c.Channel <= 144 {
-			t.Errorf("candidato DFS no esperado: %+v", c)
+	byCh := map[int]channelplan.ChannelScore{}
+	var dfsCount int
+	for _, c := range recs[0].Scores {
+		if c.DFS {
+			dfsCount++
 		}
 		byCh[c.Channel] = c
 	}
+	if dfsCount == 0 {
+		t.Errorf("a 80 MHz deben puntuarse también bloques DFS: %+v", recs[0].Scores)
+	}
 	rec := recs[0]
-	if byCh[rec.Recommended].Score != rec.BestScore {
-		t.Errorf("el score del candidato recomendado debe ser BestScore: cand %+v, rec %+v", byCh[rec.Recommended], rec)
+	best := byCh[rec.Recommended]
+	if best.DFS || !best.Recommendable {
+		t.Errorf("el recomendado debe ser un bloque no-DFS recomendable: %+v", best)
+	}
+	// #1076: el rango 68-92 (5350-5470 MHz) no es RLAN en ETSI: se puntúa
+	// pero nunca se recomienda.
+	if b, ok := byCh[68]; ok && b.Recommendable {
+		t.Errorf("el bloque 68 no debe ser recomendable (no RLAN ETSI): %+v", b)
+	}
+	if b, ok := byCh[52]; !ok || !b.DFS {
+		t.Errorf("el bloque 52-64 debe marcarse DFS: %+v", b)
+	}
+	if best.Score != rec.BestScore {
+		t.Errorf("el score del bloque recomendado debe ser BestScore: %+v, rec %+v", best, rec)
+	}
+}
+
+// TestRecommendScores24GHzTodosLosCanales (#1076): a 2.4 GHz se puntúan los
+// 13 canales (no solo los no solapados 1/6/11), todos recomendables.
+func TestRecommendScores24GHzTodosLosCanales(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	recs, err := st.Recommend("rt1", []probe.Radio{{Name: "2.4 GHz", Channel: 6, WidthMhz: 20}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	if len(recs) != 1 || len(recs[0].Scores) != 13 {
+		t.Fatalf("esperaba 13 scores en 2.4 GHz, got %+v", recs)
+	}
+	for _, s := range recs[0].Scores {
+		want := s.Channel == 1 || s.Channel == 6 || s.Channel == 11
+		if s.Recommendable != want || s.DFS {
+			t.Errorf("recommendable solo en 1/6/11 (#631): %+v", s)
+		}
+	}
+}
+
+// TestRecentScansOwnPorSSIDTransitable (#1076): si un BSSID de un SSID es
+// propio por prefijo MAC, el resto de filas del mismo SSID también se
+// marcan propias aunque su MAC no case (guest de la misma unidad).
+func TestRecentScansOwnPorSSIDTransitable(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+	if _, err := d.DB.Exec(`INSERT INTO routers (id, name, host, type, mac, is_gateway, created_at)
+		VALUES ('rt2', 'RT2 AX6', '192.168.1.2', 'openwrt', '8C:DE:F9:33:71:58', 0, ?)`,
+		time.Now().UnixMilli()); err != nil {
+		t.Fatalf("insert router: %v", err)
+	}
+
+	st := channelplan.NewStore(d.DB)
+	now := time.Now().Unix()
+	// La main BSS de la malla casa con el prefijo; la guest (misma unidad,
+	// MAC distinta) no.
+	scans := []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "8C:DE:F9:33:71:59", SSID: "casa-guest", Channel: 6, Freq: 2437, Signal: -30},
+		{Iface: "wlan0", BSSID: "1E:BF:CE:02:7F:48", SSID: "casa-guest", Channel: 6, Freq: 2437, Signal: -53},
+		{Iface: "wlan0", BSSID: "00:11:22:33:44:55", SSID: "vecino", Channel: 11, Freq: 2462, Signal: -80},
+	}
+	if err := st.SaveScan("rt1", now, scans); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	got, err := st.RecentScans("rt1", time.Hour)
+	if err != nil {
+		t.Fatalf("recent: %v", err)
+	}
+	bySSID := map[string]bool{}
+	for _, r := range got {
+		bySSID[r.SSID] = r.Own
+	}
+	if !bySSID["casa-guest"] {
+		t.Errorf("toda fila de casa-guest debe ser own (transitividad): %+v", got)
+	}
+	if bySSID["vecino"] {
+		t.Errorf("vecino NO debe ser own: %+v", got)
 	}
 }