4
0
Эх сурвалжийг харах

feat: per-client traffic in live mode (hostapd bytes + nlbwmon) (#558)

* feat(agent): report per-client byte counters from hostapd and nlbwmon (#551)

* feat(server): wire per-client bandwidth store with bps rollups and ingest deltas (#551)

* feat(server): expose per-device traffic API and live current rate (#551)

* feat(ui): show live per-client traffic in device detail (#551)

* fix(server): prefer nlbwmon source for live per-client rate (#551)

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 сар өмнө
parent
commit
5e00c54447

+ 105 - 0
agent/probe/clientbw.go

@@ -0,0 +1,105 @@
+// clientbw.go — tráfico por cliente desde nlbwmon (issue #551). El comando y
+// el parser viven aquí (patrón Cmd*/Parse* de probe) para que los use TANTO el
+// agente local (sección clientbw del payload) como el sondeo SSH del server.
+//
+// Contrato de disponibilidad (#551):
+//   - nlbwmon NO instalado → ClientBwData{Available:false} (hint "instala
+//     nlbwmon"; el server usa entonces los contadores hostapd por estación).
+//   - instalado pero la sonda falla esta ronda (daemon caído/socket) →
+//     Available:true con Hosts nil (el server conserva el último dato bueno).
+//   - instalado y sin hosts → Available:true con Hosts {} (vacío honesto).
+//
+// Los contadores son ACUMULADOS del periodo de nlbwmon (por defecto mes
+// natural): el server calcula el delta entre muestras para obtener bytes del
+// intervalo, como hace con NetDev.
+package probe
+
+import (
+	"encoding/json"
+	"strings"
+)
+
+// CmdNlbwmonCheck: ¿está nlbw instalado? (exit != 0 → no instalado).
+const CmdNlbwmonCheck = "command -v nlbw"
+
+// CmdNlbwmonJSON: contadores por MAC del daemon nlbwmon en JSON (igual que la
+// sonda SSH del server). Agrupación por MAC; columnas: mac, conns, rx_bytes,
+// rx_pkts, tx_bytes, tx_pkts (acumulados del periodo).
+const CmdNlbwmonJSON = "nlbw -c json -g mac 2>/dev/null"
+
+// ClientBwData: sección clientbw del payload del agente (#551).
+type ClientBwData struct {
+	// Available: false cuando nlbw no está instalado en el equipo.
+	Available bool `json:"available"`
+	// Hosts: contadores por MAC (mayúsculas). nil = sonda fallida esta ronda
+	// (el server conserva el último dato bueno); {} = cero hosts honesto.
+	// SIN omitempty a propósito: hay que distinguir nil de vacío.
+	Hosts map[string]NlbwCounter `json:"hosts"`
+}
+
+// NlbwCounter: bytes acumulados de un host en el periodo de nlbwmon.
+type NlbwCounter struct {
+	RxBytes uint64 `json:"rxBytes"`
+	TxBytes uint64 `json:"txBytes"`
+}
+
+// ParseNlbwJSON parsea `nlbw -c json -g mac`:
+//
+//	{"columns":["mac","conns","rx_bytes","rx_pkts","tx_bytes","tx_pkts"],
+//	 "data":[[<mac>,"conns",<rx_bytes>,<rx_pkts>,<tx_bytes>,<tx_pkts>], ...]}
+//
+// Defensivo: el parser mapea por NOMBRE de columna (no por posición), de forma
+// que un cambio de orden u omisión de columnas del CLI no rompa el parseo.
+// MAC normalizada a mayúsculas (contrato de claves del resto del payload).
+func ParseNlbwJSON(data []byte) (map[string]NlbwCounter, error) {
+	var root struct {
+		Columns []string          `json:"columns"`
+		Data    []json.RawMessage `json:"data"`
+	}
+	if err := json.Unmarshal(data, &root); err != nil {
+		return nil, err
+	}
+	if len(root.Columns) == 0 {
+		return map[string]NlbwCounter{}, nil
+	}
+	// Índice de las columnas que nos interesan.
+	macIdx, rxIdx, txIdx := -1, -1, -1
+	for i, c := range root.Columns {
+		switch c {
+		case "mac":
+			macIdx = i
+		case "rx_bytes":
+			rxIdx = i
+		case "tx_bytes":
+			txIdx = i
+		}
+	}
+	if macIdx < 0 {
+		return nil, nil // sin columna mac: formato inesperado, no error
+	}
+	hosts := make(map[string]NlbwCounter, len(root.Data))
+	for _, raw := range root.Data {
+		// Best-effort por fila: una fila con forma inesperada no invalida
+		// el resto (patrón lldp.go). null/42/objeto → se saltan.
+		var row []json.RawMessage
+		if err := json.Unmarshal(raw, &row); err != nil {
+			continue
+		}
+		if macIdx >= len(row) {
+			continue
+		}
+		var mac string
+		if err := json.Unmarshal(row[macIdx], &mac); err != nil || mac == "" {
+			continue
+		}
+		var h NlbwCounter
+		if rxIdx >= 0 && rxIdx < len(row) {
+			_ = json.Unmarshal(row[rxIdx], &h.RxBytes) // best-effort
+		}
+		if txIdx >= 0 && txIdx < len(row) {
+			_ = json.Unmarshal(row[txIdx], &h.TxBytes) // best-effort
+		}
+		hosts[strings.ToUpper(mac)] = h
+	}
+	return hosts, nil
+}

+ 156 - 0
agent/probe/clientbw_test.go

@@ -0,0 +1,156 @@
+// clientbw_test.go — parser de `nlbw -c json -g mac` (issue #551) y
+// comportamiento de la sonda probeClientBw con runner fake.
+package probe
+
+import (
+	"context"
+	"encoding/json"
+	"strings"
+	"testing"
+)
+
+// Fixture del formato real de nlbwmon (handle_json en client.c): agrupación
+// por MAC (-g mac) emite columnas mac, conns, rx_bytes, rx_pkts, tx_bytes,
+// tx_pkts en ese orden, con los contadores acumulados del periodo.
+const nlbwFixture = `{"columns":["mac","conns","rx_bytes","rx_pkts","tx_bytes","tx_pkts"],"data":[
+["aa:bb:cc:dd:ee:01", 34, 123456789, 98765, 111222333, 121314],
+["aa:bb:cc:dd:ee:02", 2, 1000, 5, 2000, 9]
+]}`
+
+func TestParseNlbwJSONFixture(t *testing.T) {
+	hosts, err := ParseNlbwJSON([]byte(nlbwFixture))
+	if err != nil {
+		t.Fatalf("parse: %v", err)
+	}
+	if len(hosts) != 2 {
+		t.Fatalf("hosts: %d", len(hosts))
+	}
+	h := hosts["AA:BB:CC:DD:EE:01"] // normalizada a mayúsculas
+	if h.RxBytes != 123456789 || h.TxBytes != 111222333 {
+		t.Fatalf("contadores aa:bb:...:01: %+v", h)
+	}
+	if h2 := hosts["AA:BB:CC:DD:EE:02"]; h2.RxBytes != 1000 || h2.TxBytes != 2000 {
+		t.Fatalf("contadores aa:bb:...:02: %+v", h2)
+	}
+}
+
+func TestParseNlbwJSONColumnasPorNombre(t *testing.T) {
+	// El parser mapea por NOMBRE de columna: orden distinto o columnas
+	// extra no deben romper (p.ej. versiones del CLI que añadan campos).
+	reordered := `{"columns":["conns","tx_bytes","mac","rx_bytes","foo"],"data":[
+[7, 999, "aa:bb:cc:dd:ee:03", 555, "irrelevante"]
+]}`
+	hosts, err := ParseNlbwJSON([]byte(reordered))
+	if err != nil {
+		t.Fatalf("parse reordenado: %v", err)
+	}
+	if len(hosts) != 1 {
+		t.Fatalf("hosts: %d", len(hosts))
+	}
+	if h := hosts["AA:BB:CC:DD:EE:03"]; h.RxBytes != 555 || h.TxBytes != 999 {
+		t.Fatalf("contadores reordenado: %+v", h)
+	}
+}
+
+func TestParseNlbwJSONDefensivo(t *testing.T) {
+	// JSON no válido → error.
+	if _, err := ParseNlbwJSON([]byte("nlbw: connect failed")); err == nil {
+		t.Fatal("no JSON debería dar error")
+	}
+	// Sin datos → vacío, sin error.
+	hosts, err := ParseNlbwJSON([]byte(`{"columns":["mac","rx_bytes"],"data":[]}`))
+	if err != nil || len(hosts) != 0 {
+		t.Fatalf("sin datos: %v %v", hosts, err)
+	}
+	// Sin columna mac → sin hosts, sin error (formato inesperado, no pánico).
+	if hosts, err := ParseNlbwJSON([]byte(`{"columns":["ip"],"data":[["1.2.3.4"]]}`)); err != nil || hosts != nil {
+		t.Fatalf("sin columna mac: %v %v", hosts, err)
+	}
+	// Filas con tipos raros: no pánico, se saltan.
+	weird := `{"columns":["mac","rx_bytes","tx_bytes"],"data":[[null, 1, 2],["aa:bb:cc:dd:ee:04","no-num",null],42]}`
+	hosts, err = ParseNlbwJSON([]byte(weird))
+	if err != nil {
+		t.Fatalf("filas raras: %v", err)
+	}
+	if len(hosts) != 1 {
+		t.Fatalf("hosts de filas raras: %d", len(hosts))
+	}
+	if h := hosts["AA:BB:CC:DD:EE:04"]; h.RxBytes != 0 || h.TxBytes != 0 {
+		t.Fatalf("contadores no numéricos: %+v", h)
+	}
+}
+
+// TestProberClientBw: contrato de disponibilidad de la sonda (#551).
+func TestProberClientBw(t *testing.T) {
+	ctx := context.Background()
+
+	// nlbw NO instalado: command -v falla → Available=false (el server usa
+	// entonces hostapd bytes por estación).
+	p := NewProber(fakeRunner{outs: map[string]string{}}, Options{})
+	cb := p.probeClientBw(ctx)
+	if cb == nil || cb.Available || cb.Hosts != nil {
+		t.Fatalf("sin nlbw: %+v", cb)
+	}
+
+	// Instalado con datos: fixture completo.
+	p = NewProber(fakeRunner{outs: map[string]string{
+		CmdNlbwmonCheck: "/usr/sbin/nlbw\n",
+		CmdNlbwmonJSON:  nlbwFixture,
+	}}, Options{})
+	cb = p.probeClientBw(ctx)
+	if cb == nil || !cb.Available || len(cb.Hosts) != 2 {
+		t.Fatalf("con datos: %+v", cb)
+	}
+
+	// Instalado, daemon caído: check OK pero nlbw sin salida →
+	// Available=true con Hosts nil (sonda fallida, no "no instalado").
+	p = NewProber(fakeRunner{outs: map[string]string{
+		CmdNlbwmonCheck: "/usr/sbin/nlbw\n",
+	}}, Options{})
+	cb = p.probeClientBw(ctx)
+	if cb == nil || !cb.Available || cb.Hosts != nil {
+		t.Fatalf("daemon caído: %+v", cb)
+	}
+
+	// Instalado, cero hosts: data [] → vacío honesto, no nil.
+	p = NewProber(fakeRunner{outs: map[string]string{
+		CmdNlbwmonCheck: "/usr/sbin/nlbw\n",
+		CmdNlbwmonJSON:  `{"columns":["mac","rx_bytes"],"data":[]}`,
+	}}, Options{})
+	cb = p.probeClientBw(ctx)
+	if cb == nil || !cb.Available || cb.Hosts == nil || len(cb.Hosts) != 0 {
+		t.Fatalf("cero hosts: %+v", cb)
+	}
+}
+
+// TestPayloadClientBwWire: nil vs vacío viaja distinto en el JSON (contrato
+// del anti-parpadeo del server). Sin omitempty en Hosts a propósito.
+func TestPayloadClientBwWire(t *testing.T) {
+	mustJSON := func(v any) string {
+		b, err := json.Marshal(v)
+		if err != nil {
+			t.Fatalf("marshal: %v", err)
+		}
+		return string(b)
+	}
+	// Sección presente con hosts
+	if s := mustJSON(PayloadData{ClientBw: &ClientBwData{Available: true, Hosts: map[string]NlbwCounter{"AA:BB:CC:DD:EE:01": {RxBytes: 1}}}}); !strings.Contains(s, `"hosts":{`) {
+		t.Fatalf("wire con hosts: %s", s)
+	}
+	// Sección presente, sonda fallida: hosts null (no ausente)
+	if s := mustJSON(PayloadData{ClientBw: &ClientBwData{Available: true}}); !strings.Contains(s, `"hosts":null`) {
+		t.Fatalf("wire sonda fallida: %s", s)
+	}
+	// No instalado: available false, hosts null
+	if s := mustJSON(PayloadData{ClientBw: &ClientBwData{Available: false}}); !strings.Contains(s, `"available":false`) {
+		t.Fatalf("wire no instalado: %s", s)
+	}
+	// Sección ausente (push event-driven): nada de clientBw en el JSON
+	if s := mustJSON(PayloadData{}); strings.Contains(s, "clientBw") {
+		t.Fatalf("wire sin sección: %s", s)
+	}
+	// Disponible sin hosts (vacío honesto): "hosts":{}
+	if s := mustJSON(PayloadData{ClientBw: &ClientBwData{Available: true, Hosts: map[string]NlbwCounter{}}}); !strings.Contains(s, `"hosts":{}`) {
+		t.Fatalf("wire vacío honesto: %s", s)
+	}
+}

+ 31 - 0
agent/probe/hostapd_test.go

@@ -43,6 +43,37 @@ func TestParseHostapdClientsBasura(t *testing.T) {
 	}
 }
 
+// #551: el parser de ubus hostapd get_clients debe conservar los contadores
+// rx/tx por estación (bytes.rx/tx) que el driver expone, para que el server
+// calcule el tráfico por cliente. Los drivers que NO los reportan dejan el
+// campo a cero (compatibilidad).
+func TestParseHostapdClientsBytes(t *testing.T) {
+	withBytes := `==AP==hostapd.phy0-ap0
+{
+	"freq": 2437,
+	"clients": {
+		"AA:BB:CC:DD:EE:FF": {
+			"auth": true, "assoc": true, "authorized": true, "signal": -55,
+			"bytes": { "rx": 123456, "tx": 654321 }
+		},
+		"11:22:33:44:55:66": {
+			"auth": true, "assoc": true, "authorized": true, "signal": -70
+		}
+	}
+}`
+	m := ParseHostapdClients(withBytes)
+	if len(m) != 2 {
+		t.Fatalf("clientes: %d (want 2)", len(m))
+	}
+	c := m["AA:BB:CC:DD:EE:FF"]
+	if c.RxBytes != 123456 || c.TxBytes != 654321 {
+		t.Fatalf("contadores no parseados: rx=%d tx=%d (want 123456/654321)", c.RxBytes, c.TxBytes)
+	}
+	if c2 := m["11:22:33:44:55:66"]; c2.RxBytes != 0 || c2.TxBytes != 0 {
+		t.Fatalf("estación sin bytes debe quedar a 0: %+v", c2)
+	}
+}
+
 func TestParseWirelessCombined(t *testing.T) {
 	out := `R|2.437|6|HE20|22|2
 C|AA:BB:CC:DD:EE:FF|-55|2.437

+ 21 - 0
agent/probe/local.go

@@ -116,6 +116,8 @@ func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
 	// LLDP (#489): vecinos de lldpd en el payload del agente (antes solo
 	// llegaban por la sonda SSH del server, muerta para routers con agente).
 	pl.Data.Lldp = p.probeLldp(ctx)
+	// ClientBw (#551): tráfico por cliente desde nlbwmon (solo si instalado).
+	pl.Data.ClientBw = p.probeClientBw(ctx)
 	// Discovery (#338): mDNS services + randomized MAC detection.
 	pl.Data.Discovery = p.probeDiscovery(ctx, pl.Data.Wireless)
 	// NetIf (#305): contadores por iface desde el MISMO /proc/net/dev que
@@ -428,6 +430,25 @@ func (p *Prober) probeLldp(ctx context.Context) *LldpData {
 	return &LldpData{Available: true, Neighbors: neighbors}
 }
 
+// probeClientBw: contadores por MAC de nlbwmon (#551). Contrato: Available=
+// false cuando nlbw no está instalado (el server usa hostapd bytes); true con
+// Hosts nil si la sonda falla esta ronda; {} vacío honesto si el daemon no
+// tiene datos aún. Solo en el sondeo completo (Build), como LLDP.
+func (p *Prober) probeClientBw(ctx context.Context) *ClientBwData {
+	if p.runBest(ctx, CmdNlbwmonCheck, 0) == "" {
+		return &ClientBwData{Available: false}
+	}
+	out := p.runBest(ctx, CmdNlbwmonJSON, 5*time.Second)
+	if out == "" {
+		return &ClientBwData{Available: true}
+	}
+	hosts, err := ParseNlbwJSON([]byte(out))
+	if err != nil {
+		return &ClientBwData{Available: true}
+	}
+	return &ClientBwData{Available: true, Hosts: hosts}
+}
+
 // probeLuCI: etiquetas de puertos/VLANs de LuCI (issue #258), si el router
 // las define en /etc/config/luci. Best-effort: sin fichero/sección → nil.
 func (p *Prober) probeLuCI(ctx context.Context) *LuCILabels {

+ 4 - 0
agent/probe/payload.go

@@ -50,6 +50,10 @@ type PayloadData struct {
 	// (el server conserva el último dato bueno); Available=false = lldpd
 	// no instalado (hint de UI).
 	Lldp *LldpData `json:"lldp,omitempty"`
+	// ClientBw (#551): tráfico por cliente desde nlbwmon del router. nil =
+	// sonda fallida en este push; Available=false = nlbwmon no instalado
+	// (el server usa entonces hostapd bytes por estación).
+	ClientBw *ClientBwData `json:"clientBw,omitempty"`
 	// Discovery: mDNS services and randomized MAC detection (#338).
 	Discovery *DiscoveryData `json:"discovery,omitempty"`
 }

+ 21 - 3
agent/probe/probe.go

@@ -179,10 +179,17 @@ type DhcpLease struct {
 	LeaseExpiresAt *int64 `json:"leaseExpiresAt,omitempty"` // Unix segundos; nil si no se conoce
 }
 
-// WirelessClient es {signalDbm, band} por MAC.
+// WirelessClient es {signalDbm, band} por MAC + contadores de tráfico de la
+// estación cuando el driver los expone (#551). RxBytes/TxBytes son contadores
+// ACUMULADOS desde que la estación se asoció (ubus hostapd get_clients →
+// hostapd_drv_read_sta_data); el server calcula el delta entre muestras para
+// obtener bytes del intervalo. omitempty: ausentes si la fuente no los da
+// (iwinfo, drivers sin read_sta_data).
 type WirelessClient struct {
 	SignalDbm int    `json:"signalDbm"`
 	Band      string `json:"band"`
+	RxBytes   uint64 `json:"rxBytes,omitempty"`
+	TxBytes   uint64 `json:"txBytes,omitempty"`
 }
 
 // PortState es {name, up, speed} de una interfaz (/sys operstate+speed).
@@ -1025,6 +1032,9 @@ var nonDigitRe = regexp.MustCompile(`\D`)
 
 // ParseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
 // hostapdClientsJSON es el shape de `ubus call hostapd.<if> get_clients`.
+// El objeto por estación incluye `bytes:{rx,tx}` (acumulados desde la
+// asociación) y `packets` cuando el driver responde a read_sta_data (#551);
+// si no los expone, quedan a cero.
 type hostapdClientsJSON struct {
 	Freq    float64 `json:"freq"`
 	Clients map[string]struct {
@@ -1032,6 +1042,10 @@ type hostapdClientsJSON struct {
 		Assoc      bool `json:"assoc"`
 		Authorized bool `json:"authorized"`
 		Signal     int  `json:"signal"`
+		Bytes      struct {
+			Rx uint64 `json:"rx"`
+			Tx uint64 `json:"tx"`
+		} `json:"bytes"`
 	} `json:"clients"`
 }
 
@@ -1039,7 +1053,8 @@ type hostapdClientsJSON struct {
 // "==AP==hostapd.phy0-ap0" seguidos del JSON de get_clients. Solo cuenta
 // estaciones asociadas y autorizadas (equivalente a iwinfo assoclist); la
 // banda sale del "freq" del bloque (>=5 GHz = "5 GHz"). Mismo shape que
-// ParseWirelessClients.
+// ParseWirelessClients. RxBytes/TxBytes son los contadores acumulados de la
+// estación si el driver los reportó (issue #551).
 func ParseHostapdClients(out string) map[string]WirelessClient {
 	m := map[string]WirelessClient{}
 	for _, chunk := range strings.Split(out, "==AP==") {
@@ -1068,7 +1083,10 @@ func ParseHostapdClients(out string) map[string]WirelessClient {
 			if !st.Assoc || !st.Authorized {
 				continue
 			}
-			m[strings.ToUpper(mac)] = WirelessClient{SignalDbm: st.Signal, Band: band}
+			m[strings.ToUpper(mac)] = WirelessClient{
+				SignalDbm: st.Signal, Band: band,
+				RxBytes: st.Bytes.Rx, TxBytes: st.Bytes.Tx,
+			}
 		}
 	}
 	return m

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

@@ -186,6 +186,7 @@
       "renameLocal": "Only saved in this browser.",
       "traffic24h": "Traffic 24 h",
       "trafficCurrent": "Current traffic",
+      "traffic": "Client traffic",
       "unfiltered": "Unfiltered"
     },
     "deviceType": "Device type",

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

@@ -186,6 +186,7 @@
       "renameLocal": "Solo se guarda en este navegador.",
       "traffic24h": "Tráfico 24 h",
       "trafficCurrent": "Tráfico actual",
+      "traffic": "Tráfico por cliente",
       "unfiltered": "Sin filtrar"
     },
     "deviceType": "Tipo de dispositivo",

+ 180 - 0
app/src/components/DeviceTraffic.tsx

@@ -0,0 +1,180 @@
+import { useEffect, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Sparkline } from '@/components/Sparkline'
+import { fmtEs } from '@/data/mock'
+
+interface TrafficPoint {
+  ts: string
+  rxBytes: number
+  txBytes: number
+  rxBps: number
+  txBps: number
+}
+
+interface TrafficResponse {
+  points: TrafficPoint[]
+  resolution: string
+}
+
+/** Formatea bytes a unidad legible estilo "2,1 GB" / "340 MB" (locale activo). */
+function fmtBytes(b: number): string {
+  const gb = b / 1e9
+  if (gb >= 1) return `${fmtEs(gb, 1)} GB`
+  const mb = b / 1e6
+  if (mb >= 1) return `${fmtEs(mb, mb >= 10 ? 0 : 1)} MB`
+  const kb = b / 1e3
+  return `${fmtEs(kb, kb >= 10 ? 0 : 1)} KB`
+}
+
+const RANGES = [
+  { key: '24h', secs: 24 * 3600 },
+  { key: '7d', secs: 7 * 24 * 3600 },
+  { key: '30d', secs: 30 * 24 * 3600 },
+] as const
+type RangeKey = (typeof RANGES)[number]['key']
+
+function MiniBwChart({ points }: { points: TrafficPoint[] }) {
+  if (points.length < 2) return null
+  const W = 220
+  const H = 34
+  const PAD = 3
+  const max = Math.max(...points.map((p) => p.rxBps + p.txBps), 1)
+  const stepX = (W - PAD * 2) / (points.length - 1)
+  const line = (key: 'rxBps' | 'txBps') =>
+    points
+      .map((p, i) => {
+        const x = PAD + i * stepX
+        const y = H - PAD - ((p[key] / max) * (H - PAD * 2))
+        return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`
+      })
+      .join(' ')
+  return (
+    <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} className="block" aria-hidden="true">
+      <path d={line('rxBps')} fill="none" stroke="#3b82f6" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+      <path d={line('txBps')} fill="none" stroke="#10b981" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
+    </svg>
+  )
+}
+
+/**
+ * Tráfico real por cliente (#551). Fetch bajo demanda del detalle en live
+ * (patrón PortSeriesChart); en demo no se monta (los campos del canon ya
+ * viajan en el snapshot y el endpoint no existe).
+ */
+export function DeviceTrafficDetail({ mac, online }: { mac: string; online: boolean }) {
+  const { t } = useTranslation()
+  const [range, setRange] = useState<RangeKey>('24h')
+  const [points, setPoints] = useState<TrafficPoint[] | null>(null)
+  const [loading, setLoading] = useState(false)
+
+  useEffect(() => {
+    let cancelled = false
+    if (!online || mac === '—') {
+      setPoints([])
+      return
+    }
+    const secs = RANGES.find((r) => r.key === range)!.secs
+    setLoading(true)
+    const now = Math.floor(Date.now() / 1000)
+    const from = now - secs
+    fetch(`/api/devices/${encodeURIComponent(mac)}/traffic?from=${from}&to=${now}`)
+      .then((res) => (res.ok ? res.json() : Promise.reject(res.status)))
+      .then((json: TrafficResponse) => {
+        if (!cancelled) setPoints(json.points ?? [])
+      })
+      .catch(() => {
+        if (!cancelled) setPoints([])
+      })
+      .finally(() => {
+        if (!cancelled) setLoading(false)
+      })
+    return () => {
+      cancelled = true
+    }
+  }, [mac, online, range])
+
+  const summary = useMemo(() => {
+    if (!points || points.length === 0) return null
+    const rx = points.reduce((a, p) => a + (p.rxBytes || 0), 0)
+    const tx = points.reduce((a, p) => a + (p.txBytes || 0), 0)
+    const last = points[points.length - 1]
+    const mbps = last ? ((last.rxBps || 0) + (last.txBps || 0)) / 1e6 : 0
+    return { rx, tx, mbps }
+  }, [points])
+
+  if (!online) return null
+
+  return (
+    <div className="rounded-xl border border-border bg-elevated/40 px-3 py-2.5">
+      <div className="flex items-center justify-between gap-2">
+        <span className="text-caption font-medium text-text-secondary">
+          {t('devices.detail.traffic')}
+        </span>
+        <div className="flex gap-1">
+          {RANGES.map((r) => (
+            <button
+              key={r.key}
+              type="button"
+              onClick={() => setRange(r.key)}
+              className={`rounded px-1.5 py-0.5 text-[10px] font-medium transition-colors ${
+                range === r.key ? 'bg-accent/15 text-accent' : 'text-text-muted hover:bg-canvas hover:text-text-secondary'
+              }`}
+            >
+              {r.key}
+            </button>
+          ))}
+        </div>
+      </div>
+      {loading ? (
+        <div className="flex h-8 items-center justify-center text-caption text-text-muted">...</div>
+      ) : summary && points && points.length > 1 ? (
+        <div className="mt-1.5 space-y-1">
+          <div className="flex items-center justify-between gap-2">
+            <span className="font-mono text-mono-sm text-text-secondary">
+              ↓ {fmtBytes(summary.rx)} · ↑ {fmtBytes(summary.tx)}
+            </span>
+            <span className="font-mono text-mono-sm text-accent">
+              {summary.mbps >= 1 ? fmtEs(summary.mbps, 1) : fmtEs(summary.mbps, 2)} Mbps
+            </span>
+          </div>
+          <MiniBwChart points={points} />
+        </div>
+      ) : (
+        <div className="flex h-8 items-center justify-center text-caption text-text-muted">
+          {t('routerDetail.ports.seriesNoData')}
+        </div>
+      )}
+    </div>
+  )
+}
+
+/** Sparkline del tráfico actual (24 h) para filas compactas en live. */
+export function DeviceTrafficSparkline({ mac, online, width = 60, height = 20 }: { mac: string; online: boolean; width?: number; height?: number }) {
+  const [points, setPoints] = useState<TrafficPoint[]>([])
+  useEffect(() => {
+    let cancelled = false
+    if (!online || mac === '—') {
+      setPoints([])
+      return
+    }
+    const now = Math.floor(Date.now() / 1000)
+    const from = now - 24 * 3600
+    fetch(`/api/devices/${encodeURIComponent(mac)}/traffic?from=${from}&to=${now}`)
+      .then((res) => (res.ok ? res.json() : Promise.reject(res.status)))
+      .then((json: TrafficResponse) => {
+        if (!cancelled) setPoints(json.points ?? [])
+      })
+      .catch(() => {
+        if (!cancelled) setPoints([])
+      })
+    return () => {
+      cancelled = true
+    }
+  }, [mac, online])
+  const data = useMemo(
+    () => points.filter((_, i, a) => a.length <= 48 || i % Math.ceil(a.length / 48) === 0).map((p) => (p.rxBps + p.txBps) / 1e6),
+    [points],
+  )
+  if (data.length < 2) return null
+  return <Sparkline data={data} width={width} height={height} className="text-accent" />
+}

+ 23 - 11
app/src/pages/Devices.tsx

@@ -25,6 +25,7 @@ import { EmptyState } from '@/components/EmptyState'
 import { MetricBar } from '@/components/MetricBar'
 import { SegmentedControl } from '@/components/SegmentedControl'
 import { Sparkline } from '@/components/Sparkline'
+import { DeviceTrafficDetail } from '@/components/DeviceTraffic'
 import { StatusPill } from '@/components/StatusPill'
 import {
   DropdownMenu,
@@ -574,6 +575,7 @@ function DeviceDetail({
   onEdit: () => void
 }) {
   const { t } = useTranslation()
+  const { isDemo } = useNetPulse()
   return (
     <div className="grid grid-cols-2 gap-x-4 gap-y-4 px-4 py-4 md:grid-cols-3 md:px-5">
       <DetailItem label="MAC" mono>
@@ -585,18 +587,28 @@ function DeviceDetail({
       <DetailItem label="Hostname" mono>
         {device.hostname}
       </DetailItem>
-      <DetailItem label={t('devices.detail.traffic24h')} mono>
-        ↓ {device.traffic24hRx} · ↑ {device.traffic24hTx}
-      </DetailItem>
-      <div className="min-w-0">
-        <div className="text-label uppercase text-text-muted">{t('devices.detail.trafficCurrent')}</div>
-        <div className="mt-1 inline-flex items-center gap-2">
-          <span className="font-mono text-mono-sm text-accent">
-            {device.trafficMbps >= 1 ? fmtEs(device.trafficMbps, 1) : fmtEs(device.trafficMbps, 2)} Mbps
-          </span>
-          <Sparkline data={device.sparkline} width={60} height={20} className="text-accent" />
+      {/* #551: en demo el tráfico viene en el canon; en live se pide al
+          endpoint /api/devices/{mac}/traffic bajo demanda (patrón portseries). */}
+      {isDemo ? (
+        <>
+          <DetailItem label={t('devices.detail.traffic24h')} mono>
+            ↓ {device.traffic24hRx} · ↑ {device.traffic24hTx}
+          </DetailItem>
+          <div className="min-w-0">
+            <div className="text-label uppercase text-text-muted">{t('devices.detail.trafficCurrent')}</div>
+            <div className="mt-1 inline-flex items-center gap-2">
+              <span className="font-mono text-mono-sm text-accent">
+                {device.trafficMbps >= 1 ? fmtEs(device.trafficMbps, 1) : fmtEs(device.trafficMbps, 2)} Mbps
+              </span>
+              <Sparkline data={device.sparkline} width={60} height={20} className="text-accent" />
+            </div>
+          </div>
+        </>
+      ) : (
+        <div className="col-span-2 md:col-span-1">
+          <DeviceTrafficDetail mac={device.mac} online={device.online} />
         </div>
-      </div>
+      )}
       <div className="min-w-0">
         <div className="text-label uppercase text-text-muted">AdGuard</div>
         <div className="mt-1.5">

+ 27 - 1
server-go/internal/adapters/agent.go

@@ -592,6 +592,25 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 		return lldpFromProbe(ld.Neighbors), false
 	}
 	out.lldp, out.lldpUnavailable = resolveLldp()
+	// ClientBw (#551): contadores nlbwmon por MAC. Anti-parpadeo idéntico a
+	// LLDP: la sección buena del payload manda; una sección fallida
+	// (Available=true con Hosts nil) o ausente (push event-driven) recicla
+	// la última cacheada; Available=false explícito = nlbwmon no instalado
+	// y eso SÍ pisa lo cacheado (el server cae a hostapd bytes).
+	resolveClientBw := func() *probe.ClientBwData {
+		cb := p.Data.ClientBw
+		if cb == nil || (cb.Available && cb.Hosts == nil) {
+			cb = nil
+			if cached != nil {
+				cb = cached.clientBw
+			}
+		}
+		if cb == nil || !cb.Available {
+			return nil
+		}
+		return cb
+	}
+	out.clientBw = resolveClientBw()
 	// Discovery (#338): mDNS services + randomized MACs. Best-effort.
 	if p.Data.Discovery != nil {
 		out.discovery = p.Data.Discovery
@@ -652,7 +671,8 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 		lldpSnap = cached.lldp // conserva la última sección buena (#489)
 	}
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
-		wireless: out.wireless, fdb: out.fdb, luci: out.luci, system: sysSnap, lldp: lldpSnap}
+		wireless: out.wireless, fdb: out.fdb, luci: out.luci, system: sysSnap, lldp: lldpSnap,
+		clientBw: out.clientBw}
 	l.mu.Unlock()
 
 	// Solo con un payload NUEVO alimentamos las series y el monitor de
@@ -662,6 +682,12 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	// del siguiente push).
 	if freshPayload {
 		l.recordPortSamples(cfg.ID, out.ports)
+		// #551: tráfico por cliente (nlbwmon preferente, hostapd fallback).
+		// now = ts del payload (no el reloj del server) para que el dt del
+		// delta sea el intervalo real entre pushes del agente.
+		if samples, source, ok := resolveClientBwSources(out.wireless, out.clientBw); ok {
+			l.recordClientBwSamples(cfg.ID, time.Unix(p.Ts, 0), samples, source)
+		}
 		l.portMon.Observe(cfg.ID, out.ports, l.engine)
 	}
 

+ 185 - 0
server-go/internal/adapters/clientbw.go

@@ -0,0 +1,185 @@
+// clientbw.go — ingesta del tráfico por cliente (#551). El server recibe de
+// cada router contadores ACUMULADOS por MAC (fuente nlbwmon o hostapd bytes
+// por estación del agente) y los convierte a samples delta por (router, mac)
+// en la store client_bw_raw, con el rate medio del intervalo (bps).
+//
+// Diseño (decisión del usuario, 5-Sep-2026): por router, la fuente PREFERENTE
+// es nlbwmon cuando está disponible y responde (cubre cableados y todo lo que
+// enruta el router); si no, se usan los contadores hostapd por estación
+// (clientes wifi asociados a ese AP). La demo no alimenta la store: sus datos
+// sintéticos de tráfico por device siguen intactos.
+//
+// Solapamiento futuro (nota, no bloquea): cuando el pusher del gateway (NetGrip)
+// emita clientBw con nlbwmon, el gateway reportará TODAS las MACs (cable + wifi
+// que enruta) y los APs seguirán reportando hostapd de sus clientes wifi → la
+// misma MAC tendría filas de dos fuentes y GetMACSeries sumaría el doble. La
+// flota actual NO solapa (APs sin nlbwmon, gateway sin clientBw aún): rt2/rt4
+// reportan hostapd y el gateway nada. Antes de activar nlbwmon en el gateway
+// hay que decidir la reconciliación (p. ej. marcar source en la fila y que la
+// agregación por device filtre por la fuente del router que enruta).
+package adapters
+
+import (
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/clientbw"
+)
+
+// clientBwCounter es el último contador absoluto observado de un cliente en
+// un router (para el delta entre polls) + el rate medio del último intervalo
+// (bps) para el TrafficMbps de la lista sin consultar la store.
+type clientBwCounter struct {
+	at     time.Time
+	rx     uint64
+	tx     uint64
+	source string // "nlbwmon" | "hostapd" (logging)
+	// rxBps/txBps: rate medio del ÚLTIMO intervalo persistido (0 si aún no
+	// hay delta: primera observación o reinicio del contador).
+	rxBps float64
+	txBps float64
+}
+
+// clientBwSample es el par (MAC, contadores absolutos) que reporta una fuente
+// en un poll. MAC sin normalizar (viene de los parsers en mayúsculas).
+type clientBwSample struct {
+	mac string
+	rx  uint64
+	tx  uint64
+}
+
+// canonBWMac normaliza la MAC al formato canónico del server para las rutas
+// /api/devices/{mac}/* (minúsculas con ':'). Las fuentes (hostapd/nlbwmon)
+// entregan mayúsculas; la store client_bw_raw debe casar con normalizeMAC.
+func canonBWMac(mac string) string {
+	var b strings.Builder
+	for _, r := range strings.ToLower(mac) {
+		if (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') {
+			b.WriteRune(r)
+		}
+	}
+	s := b.String()
+	var out strings.Builder
+	for i := 0; i+1 < len(s); i += 2 {
+		if i > 0 {
+			out.WriteByte(':')
+		}
+		out.WriteString(s[i : i+2])
+	}
+	return out.String()
+}
+
+// recordClientBwSamples persiste el delta de cada cliente desde el último
+// contador absoluto conocido. Debe llamarse UNA vez por poll con datos
+// frescos (no en rebuilds del snapshot con el mismo payload cacheado; patrón
+// issue #365 de portseries). now es el instante del sondeo.
+func (l *Live) recordClientBwSamples(routerID string, now time.Time, samples []clientBwSample, source string) {
+	if l.db == nil || l.db.ClientBW == nil || len(samples) == 0 {
+		return
+	}
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	if l.lastClientBw == nil {
+		l.lastClientBw = map[string]map[string]*clientBwCounter{}
+	}
+	last := l.lastClientBw[routerID]
+	if last == nil {
+		last = map[string]*clientBwCounter{}
+		l.lastClientBw[routerID] = last
+	}
+	for _, s := range samples {
+		mac := canonBWMac(s.mac)
+		if mac == "" {
+			continue
+		}
+		prev := last[mac]
+		if prev == nil {
+			// Primera observación: solo se siembra el contador; no hay
+			// delta que persistir todavía.
+			last[mac] = &clientBwCounter{at: now, rx: s.rx, tx: s.tx, source: source}
+			continue
+		}
+		dt := now.Sub(prev.at).Seconds()
+		// Delta: si el contador reinició (nlbwmon nuevo periodo, cliente
+		// que se reasoció y hostapd reinició bytes), no fabricar un delta
+		// negativo gigante: se re-siembra y se espera al siguiente poll.
+		if dt <= 0 || s.rx < prev.rx || s.tx < prev.tx {
+			prev.at = now
+			prev.rx = s.rx
+			prev.tx = s.tx
+			prev.source = source
+			prev.rxBps = 0
+			prev.txBps = 0
+			continue
+		}
+		rxDelta := s.rx - prev.rx
+		txDelta := s.tx - prev.tx
+		prev.rxBps = float64(rxDelta) * 8 / dt
+		prev.txBps = float64(txDelta) * 8 / dt
+		_ = l.db.ClientBW.Insert(clientbw.Sample{
+			MAC: mac, RouterID: routerID, TS: now,
+			RxBytes: rxDelta, TxBytes: txDelta,
+			RxBps: prev.rxBps, TxBps: prev.txBps,
+		})
+		prev.at = now
+		prev.rx = s.rx
+		prev.tx = s.tx
+		prev.source = source
+	}
+}
+
+// clientBwRateFor devuelve (rxBps, txBps) del último intervalo conocido del
+// cliente en cualquier router (para el TrafficMbps del device en la lista).
+// Protegido por mu. Sin datos → 0,0. Prioriza nlbwmon sobre hostapd cuando
+// una MAC es reportada por varias fuentes (el nlbwmon del router que enruta
+// ya contabiliza todo el tráfico de la MAC; sumar hostapd doblaría).
+func (l *Live) clientBwRateFor(mac string) (rxBps, txBps float64) {
+	mac = canonBWMac(mac)
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	if c := l.findClientBwRate(mac, "nlbwmon"); c != nil {
+		return c.rxBps, c.txBps
+	}
+	if c := l.findClientBwRate(mac, "hostapd"); c != nil {
+		return c.rxBps, c.txBps
+	}
+	return 0, 0
+}
+
+func (l *Live) findClientBwRate(mac, source string) *clientBwCounter {
+	for _, byMac := range l.lastClientBw {
+		if c := byMac[mac]; c != nil && c.source == source {
+			return c
+		}
+	}
+	return nil
+}
+
+// resolveClientBwSources resuelve los contadores por MAC de un sondeo con la
+// fuente preferente por router: nlbwmon si el poll trae ClientBw con
+// Available=true y hosts (cubre cableados + todo lo que enruta el router); si
+// no, hostapd bytes por estación (clientes wifi asociados). Devuelve las
+// muestras y la fuente usada; ok=false si no hay datos de tráfico por cliente.
+func resolveClientBwSources(wireless map[string]WirelessClient, clientBw *probe.ClientBwData) (samples []clientBwSample, source string, ok bool) {
+	// Fuente 1: nlbwmon (solo routers que enrutan; ver cabecera).
+	if clientBw != nil && clientBw.Available && len(clientBw.Hosts) > 0 {
+		out := make([]clientBwSample, 0, len(clientBw.Hosts))
+		for mac, h := range clientBw.Hosts {
+			out = append(out, clientBwSample{mac: mac, rx: h.RxBytes, tx: h.TxBytes})
+		}
+		return out, "nlbwmon", true
+	}
+	// Fuente 2: hostapd bytes por estación (clientes asociados a este AP).
+	var out []clientBwSample
+	for mac, c := range wireless {
+		if c.RxBytes == 0 && c.TxBytes == 0 {
+			continue
+		}
+		out = append(out, clientBwSample{mac: mac, rx: c.RxBytes, tx: c.TxBytes})
+	}
+	if len(out) > 0 {
+		return out, "hostapd", true
+	}
+	return nil, "", false
+}

+ 190 - 0
server-go/internal/adapters/clientbw_test.go

@@ -0,0 +1,190 @@
+// clientbw_test.go — ingesta del tráfico por cliente (#551): resolución de
+// fuentes (nlbwmon preferente, hostapd fallback) y conversión de contadores
+// absolutos a samples delta en la store client_bw_raw.
+package adapters
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// TestResolveClientBwSources: nlbwmon gana cuando está disponible con hosts;
+// si no, hostapd bytes por estación; sin datos → no ok.
+func TestResolveClientBwSources(t *testing.T) {
+	wireless := map[string]WirelessClient{
+		"AA:BB:CC:DD:EE:01": {SignalDbm: -50, RxBytes: 111, TxBytes: 222},
+		"AA:BB:CC:DD:EE:02": {SignalDbm: -60}, // sin bytes → no cuenta
+	}
+	nlbw := &probe.ClientBwData{Available: true, Hosts: map[string]probe.NlbwCounter{
+		"AA:BB:CC:DD:EE:0F": {RxBytes: 1000, TxBytes: 2000},
+	}}
+
+	// nlbwmon preferente: cubre hasta MACs que no están en wireless.
+	samples, source, ok := resolveClientBwSources(wireless, nlbw)
+	if !ok || source != "nlbwmon" || len(samples) != 1 {
+		t.Fatalf("nlbwmon: ok=%v source=%s samples=%+v", ok, source, samples)
+	}
+	if samples[0].mac != "AA:BB:CC:DD:EE:0F" || samples[0].rx != 1000 {
+		t.Fatalf("muestra nlbwmon: %+v", samples[0])
+	}
+
+	// Sin nlbwmon → hostapd bytes (solo estaciones con contadores).
+	samples, source, ok = resolveClientBwSources(wireless, nil)
+	if !ok || source != "hostapd" || len(samples) != 1 {
+		t.Fatalf("hostapd: ok=%v source=%s samples=%+v", ok, source, samples)
+	}
+	if samples[0].mac != "AA:BB:CC:DD:EE:01" || samples[0].rx != 111 || samples[0].tx != 222 {
+		t.Fatalf("muestra hostapd: %+v", samples[0])
+	}
+
+	// nlbwmon instalado pero vacío (Available con Hosts {}) → cae a hostapd.
+	nlbwEmpty := &probe.ClientBwData{Available: true, Hosts: map[string]probe.NlbwCounter{}}
+	_, source, ok = resolveClientBwSources(wireless, nlbwEmpty)
+	if !ok || source != "hostapd" {
+		t.Fatalf("nlbwmon vacío: source=%s ok=%v", source, ok)
+	}
+
+	// Sin datos en ninguna fuente → no ok.
+	_, _, ok = resolveClientBwSources(map[string]WirelessClient{"AA:BB:CC:DD:EE:02": {SignalDbm: -60}}, nil)
+	if ok {
+		t.Fatal("sin contadores debería dar ok=false")
+	}
+}
+
+// TestRecordClientBwSamplesDeltas: la ingesta convierte contadores absolutos
+// en deltas con bps, ignora reinicios (contador que baja) y siembra sin
+// escribir en la primera observación.
+func TestRecordClientBwSamplesDeltas(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d}
+	t0 := time.Now()
+
+	// Primera observación: siembra, no escribe nada.
+	l.recordClientBwSamples("gw", t0, []clientBwSample{
+		{mac: "AA:BB:CC:DD:EE:01", rx: 10000, tx: 5000},
+	}, "hostapd")
+	if n := countRawClientBW(t, d); n != 0 {
+		t.Fatalf("primera observación no debe escribir: %d filas", n)
+	}
+
+	// Segunda observación 10 s después con +1000/+500 → delta 1000/500,
+	// bps = bytes*8/dt = 800 y 400.
+	t1 := t0.Add(10 * time.Second)
+	l.recordClientBwSamples("gw", t1, []clientBwSample{
+		{mac: "AA:BB:CC:DD:EE:01", rx: 11000, tx: 5500},
+	}, "hostapd")
+	if n := countRawClientBW(t, d); n != 1 {
+		t.Fatalf("segunda observación debe escribir 1 fila: %d", n)
+	}
+	var rxBytes, txBytes int64
+	var rxBps, txBps float64
+	err := d.QueryRow("SELECT rx_bytes, tx_bytes, rx_bps, tx_bps FROM client_bw_raw").Scan(&rxBytes, &txBytes, &rxBps, &txBps)
+	if err != nil {
+		t.Fatalf("query: %v", err)
+	}
+	if rxBytes != 1000 || txBytes != 500 {
+		t.Fatalf("delta: rx=%d tx=%d (want 1000/500)", rxBytes, txBytes)
+	}
+	if rxBps != 800 || txBps != 400 {
+		t.Fatalf("bps: rx=%.0f tx=%.0f (want 800/400)", rxBps, txBps)
+	}
+	// El rate del último intervalo queda en memoria para el TrafficMbps.
+	if rrx, rtx := l.clientBwRateFor("AA:BB:CC:DD:EE:01"); rrx != 800 || rtx != 400 {
+		t.Fatalf("rate en memoria: rx=%.0f tx=%.0f (want 800/400)", rrx, rtx)
+	}
+
+	// Reinicio del contador (hostapd se reinició al reasociar / nlbwmon nuevo
+	// periodo): contador BAJA → re-siembra, no escribe delta gigante.
+	t2 := t1.Add(10 * time.Second)
+	l.recordClientBwSamples("gw", t2, []clientBwSample{
+		{mac: "AA:BB:CC:DD:EE:01", rx: 100, tx: 50},
+	}, "hostapd")
+	if n := countRawClientBW(t, d); n != 1 {
+		t.Fatalf("reinicio no debe escribir: %d filas", n)
+	}
+
+	// Tras el reinicio, siguiente delta normal sí escribe (base re-sembrada).
+	t3 := t2.Add(10 * time.Second)
+	l.recordClientBwSamples("gw", t3, []clientBwSample{
+		{mac: "AA:BB:CC:DD:EE:01", rx: 600, tx: 300},
+	}, "hostapd")
+	if n := countRawClientBW(t, d); n != 2 {
+		t.Fatalf("delta post-reinicio debe escribir: %d filas", n)
+	}
+	var rx2 int64
+	if err := d.QueryRow("SELECT rx_bytes FROM client_bw_raw ORDER BY ts DESC LIMIT 1").Scan(&rx2); err != nil {
+		t.Fatalf("query rx2: %v", err)
+	}
+	if rx2 != 500 { // 600 - 100
+		t.Fatalf("delta post-reinicio: %d (want 500)", rx2)
+	}
+
+	// Sin DB → no panic, no op.
+	(&Live{db: nil}).recordClientBwSamples("gw", t0, []clientBwSample{{mac: "x", rx: 1}}, "hostapd")
+}
+
+// TestRecordClientBwSamplesPorRouterYMac: los estados se segregan por router
+// y por MAC (un cliente en dos routers no comparte contador).
+func TestRecordClientBwSamplesPorRouterYMac(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d}
+	t0 := time.Now()
+	t1 := t0.Add(10 * time.Second)
+
+	l.recordClientBwSamples("gw", t0, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 100}}, "hostapd")
+	l.recordClientBwSamples("ap1", t0, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 100}}, "hostapd")
+	l.recordClientBwSamples("gw", t1, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 200}}, "hostapd")
+	l.recordClientBwSamples("ap1", t1, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 300}}, "hostapd")
+
+	var n int
+	if err := d.QueryRow("SELECT COUNT(*) FROM client_bw_raw").Scan(&n); err != nil {
+		t.Fatalf("count: %v", err)
+	}
+	if n != 2 {
+		t.Fatalf("filas: %d (want 2, una por router)", n)
+	}
+	var apRx int64
+	if err := d.QueryRow("SELECT rx_bytes FROM client_bw_raw WHERE router_id='ap1'").Scan(&apRx); err != nil {
+		t.Fatalf("query ap1: %v", err)
+	}
+	if apRx != 200 { // 300-100
+		t.Fatalf("delta ap1: %d (want 200)", apRx)
+	}
+}
+
+func countRawClientBW(t *testing.T, d *db.DB) int {
+	t.Helper()
+	var n int
+	if err := d.QueryRow("SELECT COUNT(*) FROM client_bw_raw").Scan(&n); err != nil {
+		t.Fatalf("count raw: %v", err)
+	}
+	return n
+}
+
+// TestClientBwRateForPriorizaFuente: cuando una MAC es reportada por nlbwmon
+// (router que enruta) y por hostapd a la vez, el rate de la lista usa el de
+// nlbwmon (el del gateway ya contabiliza todo el tráfico; sumar doblaría).
+func TestClientBwRateForPriorizaFuente(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d}
+	t0 := time.Now()
+	t1 := t0.Add(10 * time.Second)
+
+	// hostapd en ap1 y nlbwmon en gw reportan la misma MAC.
+	l.recordClientBwSamples("ap1", t0, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 10000}}, "hostapd")
+	l.recordClientBwSamples("gw", t0, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 20000}}, "nlbwmon")
+	l.recordClientBwSamples("ap1", t1, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 10100}}, "hostapd")
+	l.recordClientBwSamples("gw", t1, []clientBwSample{{mac: "AA:BB:CC:DD:EE:01", rx: 20200}}, "nlbwmon")
+
+	rx, tx := l.clientBwRateFor("AA:BB:CC:DD:EE:01")
+	// 200 bytes en 10 s → 160 bps (nlbwmon), no 80 del hostapd.
+	if rx != 160 {
+		t.Fatalf("rate rx: %.0f (want 160 del nlbwmon)", rx)
+	}
+	if tx != 0 {
+		t.Fatalf("rate tx: %.0f (want 0)", tx)
+	}
+}

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

@@ -122,6 +122,10 @@ type routerPolled struct {
 	// lldpUnavailable: lldpd no está instalado en este router (issue #247) →
 	// el view-model expone `lldpAvailable:false` para el hint de instalación.
 	lldpUnavailable bool
+	// clientBw (#551): contadores nlbwmon por MAC del último payload del
+	// agente. nil = nlbwmon no instalado o sonda no disponible (→ la fuente
+	// de tráfico por cliente cae a hostapd bytes de wireless).
+	clientBw *probe.ClientBwData
 	// luci: etiquetas de puertos/VLANs de LuCI (issue #258), si el router las
 	// define en /etc/config/luci. Fuente de nombres para la topología.
 	luci *probe.LuCILabels
@@ -162,6 +166,10 @@ type extrasSnapshot struct {
 	// los pushes event-driven van sin ella y la topología no debe perder
 	// los switches managed entre pushes completos.
 	lldp *probe.LldpData
+	// clientBw (#551): última sección clientbw del payload del agente.
+	// Los pushes event-driven van sin ella; conservar la última buena evita
+	// que la fuente nlbwmon parpadee entre pushes completos.
+	clientBw *probe.ClientBwData
 }
 
 // backhaulCacheTTL: el medio del uplink cambia muy raro; no se sondea cada 5 s.
@@ -216,6 +224,10 @@ type Live struct {
 	// (contadores absolutos + ts) para calcular los rates por boca con el
 	// delta entre payloads (issue #305). Protegido por mu.
 	lastAgentIf map[string]*agentIfSample
+	// lastClientBw (#551): contadores absolutos por (router, mac) de la
+	// última muestra observada, para calcular el delta por cliente entre
+	// polls. Mapa: routerID → mac → estado. Protegido por mu.
+	lastClientBw map[string]map[string]*clientBwCounter
 	// lastObsTs: ts del último payload del agente que alimentó las series
 	// por puerto y el PortMonitor (issue #365). Protegido por mu.
 	lastObsTs map[string]int64
@@ -323,6 +335,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		layoutCache:          map[string][]PortLayout{},
 		extrasCache:          map[string]*extrasSnapshot{},
 		lastAgentIf:          map[string]*agentIfSample{},
+		lastClientBw:         map[string]map[string]*clientBwCounter{},
 		lastObsTs:            map[string]int64{},
 		snmpPorts:            map[string]map[string]snmpPortSample{},
 		snmpLastPoll:         map[string]time.Time{},
@@ -458,6 +471,11 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.lastAgentIf, id)
 		}
 	}
+	for id := range l.lastClientBw {
+		if !ids[id] {
+			delete(l.lastClientBw, id)
+		}
+	}
 	for id := range l.snmpPorts {
 		if !ids[id] {
 			delete(l.snmpPorts, id)
@@ -966,6 +984,16 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		tempV = *temp
 	}
 	l.recordPortSamples(cfg.ID, portsGood)
+	// #551: tráfico por cliente. La vía SSH no sondea nlbwmon (el router
+	// gestionado por SSH raramente lo corre); la fuente resuelta es hostapd
+	// bytes por estación cuando el driver los expone. Gate de frescura:
+	// solo con la sonda wireless de ESTE poll (wireless != nil); si falló y
+	// se recicla la cache, los contadores repetidos darían deltas 0.
+	if wireless != nil {
+		if samples, source, ok := resolveClientBwSources(wireless, nil); ok {
+			l.recordClientBwSamples(cfg.ID, time.Now(), samples, source)
+		}
+	}
 	l.portMon.Observe(cfg.ID, portsGood, l.engine)
 	return &routerPolled{
 		cfg: cfg, client: client, sysInfo: sysInfo, board: board,
@@ -2032,6 +2060,14 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			d.Band = k.band
 			d.SignalDbm = k.signal
 		}
+		// #551: TrafficMbps del cliente desde el rate en memoria (nlbwmon u
+		// hostapd) sin consultar la store en cada rebuild. Solo online; los
+		// offline no tienen rate (la UI pinta "—").
+		if isSeen {
+			if rxBps, txBps := l.clientBwRateFor(mac); rxBps+txBps > 0 {
+				d.TrafficMbps = (rxBps + txBps) / 1e6
+			}
+		}
 		devices = append(devices, d)
 	}
 	return devices

+ 146 - 7
server-go/internal/clientbw/store.go

@@ -2,6 +2,7 @@ package clientbw
 
 import (
 	"database/sql"
+	"log"
 	"time"
 )
 
@@ -11,6 +12,11 @@ const (
 	BucketMS          = 5 * 60 * 1000
 )
 
+// client_bw_raw guarda una muestra por (mac, router_id, ts): los bytes del
+// INTERVALO (delta entre contadores absolutos de dos sondeos) y el rate medio
+// de ese intervalo (rx_bps = delta*8/dt). El server calcula ambos en la
+// ingesta desde los contadores acumulados que reporta la fuente (nlbwmon o
+// hostapd bytes por estación, issue #551).
 const schemaSQL = `
 CREATE TABLE IF NOT EXISTS client_bw_raw (
   mac TEXT NOT NULL,
@@ -18,6 +24,8 @@ CREATE TABLE IF NOT EXISTS client_bw_raw (
   ts INTEGER NOT NULL,
   rx_bytes INTEGER NOT NULL DEFAULT 0,
   tx_bytes INTEGER NOT NULL DEFAULT 0,
+  rx_bps REAL NOT NULL DEFAULT 0,
+  tx_bps REAL NOT NULL DEFAULT 0,
   PRIMARY KEY (mac, router_id, ts)
 );
 CREATE INDEX IF NOT EXISTS idx_client_bw_raw_ts ON client_bw_raw(ts);
@@ -52,6 +60,8 @@ CREATE TABLE IF NOT EXISTS client_bw_daily (
 );
 `
 
+// Sample es una muestra de tráfico de UN cliente en UN router: bytes del
+// intervalo (delta) y rate medio del intervalo en bps.
 type Sample struct {
 	MAC      string
 	RouterID string
@@ -79,18 +89,41 @@ func NewStore(db *sql.DB) (*Store, error) {
 		if _, err := db.Exec(schemaSQL); err != nil {
 			return nil, err
 		}
+		// Migración tolerante: DBs creadas antes del #551 no tienen las
+		// columnas bps en raw (el esquema viejo las ignoraba).
+		ensureColumn(db, "client_bw_raw", "rx_bps", "ALTER TABLE client_bw_raw ADD COLUMN rx_bps REAL NOT NULL DEFAULT 0")
+		ensureColumn(db, "client_bw_raw", "tx_bps", "ALTER TABLE client_bw_raw ADD COLUMN tx_bps REAL NOT NULL DEFAULT 0")
 	}
 	return &Store{db: db}, nil
 }
 
+func ensureColumn(db *sql.DB, table, column, alterSQL string) {
+	rows, err := db.Query("PRAGMA table_info(" + table + ")")
+	if err != nil {
+		return
+	}
+	defer rows.Close()
+	for rows.Next() {
+		var cid int
+		var name, ctype string
+		var notnull, pk int
+		var dflt any
+		if err := rows.Scan(&cid, &name, &ctype, &notnull, &dflt, &pk); err == nil && name == column {
+			return
+		}
+	}
+	_, _ = db.Exec(alterSQL)
+}
+
 func (s *Store) Insert(sample Sample) error {
 	if s.db == nil {
 		return nil
 	}
 	_, err := s.db.Exec(
-		`INSERT OR REPLACE INTO client_bw_raw (mac, router_id, ts, rx_bytes, tx_bytes)
-		 VALUES (?,?,?,?,?)`,
-		sample.MAC, sample.RouterID, sample.TS.UnixMilli(), sample.RxBytes, sample.TxBytes)
+		`INSERT OR REPLACE INTO client_bw_raw (mac, router_id, ts, rx_bytes, tx_bytes, rx_bps, tx_bps)
+		 VALUES (?,?,?,?,?,?,?)`,
+		sample.MAC, sample.RouterID, sample.TS.UnixMilli(), sample.RxBytes, sample.TxBytes,
+		sample.RxBps, sample.TxBps)
 	return err
 }
 
@@ -112,9 +145,97 @@ func (s *Store) GetSeries(mac, routerID string, from, to time.Time, resolution s
 	}
 }
 
+// GetMACSeries devuelve la serie de un cliente (MAC) agregando a través de
+// TODOS los routers: un dispositivo puede verse en varios APs a lo largo del
+// día (roaming), y la UI del detalle quiere el total, no el de un router.
+func (s *Store) GetMACSeries(mac string, from, to time.Time, resolution string) ([]Point, error) {
+	if s.db == nil {
+		return nil, nil
+	}
+	fromMs, toMs := from.UnixMilli(), to.UnixMilli()
+	switch resolution {
+	case "raw":
+		return s.queryRawMAC(mac, fromMs, toMs)
+	case "5m":
+		return s.query5mMAC(mac, fromMs, toMs)
+	case "daily":
+		return s.queryDailyMAC(mac, from, to)
+	default:
+		return s.queryRawMAC(mac, fromMs, toMs)
+	}
+}
+
+func (s *Store) queryRawMAC(mac string, fromMs, toMs int64) ([]Point, error) {
+	rows, err := s.db.Query(
+		`SELECT ts, SUM(rx_bytes), SUM(tx_bytes), AVG(rx_bps), AVG(tx_bps)
+		 FROM client_bw_raw
+		 WHERE mac = ? AND ts >= ? AND ts <= ?
+		 GROUP BY ts ORDER BY ts`, mac, fromMs, toMs)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	var out []Point
+	for rows.Next() {
+		var p Point
+		var ts int64
+		if err := rows.Scan(&ts, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
+			p.TS = time.UnixMilli(ts)
+			out = append(out, p)
+		}
+	}
+	return out, rows.Err()
+}
+
+func (s *Store) query5mMAC(mac string, fromMs, toMs int64) ([]Point, error) {
+	rows, err := s.db.Query(
+		`SELECT bucket_ts, SUM(rx_bytes), SUM(tx_bytes), AVG(rx_bps_avg), AVG(tx_bps_avg)
+		 FROM client_bw_5m
+		 WHERE mac = ? AND bucket_ts >= ? AND bucket_ts <= ?
+		 GROUP BY bucket_ts ORDER BY bucket_ts`, mac, fromMs, toMs)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	var out []Point
+	for rows.Next() {
+		var p Point
+		var ts int64
+		if err := rows.Scan(&ts, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
+			p.TS = time.UnixMilli(ts)
+			out = append(out, p)
+		}
+	}
+	return out, rows.Err()
+}
+
+func (s *Store) queryDailyMAC(mac string, from, to time.Time) ([]Point, error) {
+	fromDate := from.Format("2006-01-02")
+	toDate := to.Format("2006-01-02")
+	rows, err := s.db.Query(
+		`SELECT date, SUM(rx_bytes), SUM(tx_bytes), AVG(rx_bps_avg), AVG(tx_bps_avg)
+		 FROM client_bw_daily
+		 WHERE mac = ? AND date >= ? AND date <= ?
+		 GROUP BY date ORDER BY date`, mac, fromDate, toDate)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	var out []Point
+	for rows.Next() {
+		var p Point
+		var date string
+		if err := rows.Scan(&date, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
+			p.TS, _ = time.Parse("2006-01-02", date)
+			out = append(out, p)
+		}
+	}
+	return out, rows.Err()
+}
+
 func (s *Store) queryRaw(mac, routerID string, fromMs, toMs int64) ([]Point, error) {
 	rows, err := s.db.Query(
-		`SELECT ts, rx_bytes, tx_bytes FROM client_bw_raw
+		`SELECT ts, rx_bytes, tx_bytes, rx_bps, tx_bps FROM client_bw_raw
 		 WHERE mac = ? AND router_id = ? AND ts >= ? AND ts <= ?
 		 ORDER BY ts`, mac, routerID, fromMs, toMs)
 	if err != nil {
@@ -125,7 +246,7 @@ func (s *Store) queryRaw(mac, routerID string, fromMs, toMs int64) ([]Point, err
 	for rows.Next() {
 		var p Point
 		var ts int64
-		if err := rows.Scan(&ts, &p.RxBytes, &p.TxBytes); err == nil {
+		if err := rows.Scan(&ts, &p.RxBytes, &p.TxBytes, &p.RxBps, &p.TxBps); err == nil {
 			p.TS = time.UnixMilli(ts)
 			out = append(out, p)
 		}
@@ -189,7 +310,8 @@ func (s *Store) RollupRawTo5m(window time.Duration) error {
 		SELECT
 			mac, router_id, (ts / ?) * ?, COUNT(*),
 			SUM(rx_bytes), SUM(tx_bytes),
-			0, 0, 0, 0, 0, 0
+			MIN(rx_bps), MAX(rx_bps), AVG(rx_bps),
+			MIN(tx_bps), MAX(tx_bps), AVG(tx_bps)
 		FROM client_bw_raw
 		WHERE ts >= ?
 		GROUP BY mac, router_id, (ts / ?)`,
@@ -207,7 +329,7 @@ func (s *Store) Rollup5mToDaily(window time.Duration) error {
 			(mac, router_id, date, n, rx_bytes, tx_bytes, rx_bps_avg, tx_bps_avg)
 		SELECT
 			mac, router_id, strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch'),
-			SUM(n), SUM(rx_bytes), SUM(tx_bytes), 0, 0
+			SUM(n), SUM(rx_bytes), SUM(tx_bytes), AVG(rx_bps_avg), AVG(tx_bps_avg)
 		FROM client_bw_5m
 		WHERE bucket_ts >= ?
 		GROUP BY mac, router_id, strftime('%Y-%m-%d', bucket_ts / 1000, 'unixepoch')`,
@@ -227,6 +349,23 @@ func (s *Store) Purge() error {
 	return nil
 }
 
+// NightlyJob: escalera de rollup + purga (patrón portseries). La agrega
+// DB.NightlyJob tras los rollups de métricas.
+func (s *Store) NightlyJob() {
+	start := time.Now()
+	log.Printf("[netpulse:clientbw] nightly rollup: start")
+	if err := s.RollupRawTo5m(48 * time.Hour); err != nil {
+		log.Printf("[netpulse:clientbw] rollup raw->5m error: %v", err)
+	}
+	if err := s.Rollup5mToDaily(35 * 24 * time.Hour); err != nil {
+		log.Printf("[netpulse:clientbw] rollup 5m->daily error: %v", err)
+	}
+	if err := s.Purge(); err != nil {
+		log.Printf("[netpulse:clientbw] purge error: %v", err)
+	}
+	log.Printf("[netpulse:clientbw] nightly rollup: done (%s)", time.Since(start).Round(time.Millisecond))
+}
+
 func (s *Store) TopClients(routerID string, since time.Time, limit int) ([]TopClient, error) {
 	if s.db == nil {
 		return nil, nil

+ 71 - 31
server-go/internal/clientbw/store_test.go

@@ -1,30 +1,48 @@
 package clientbw
 
 import (
+	"database/sql"
 	"testing"
 	"time"
 
-	"github.com/gnacho/netpulse/server-go/internal/db"
+	_ "modernc.org/sqlite"
 )
 
-func TestInsertAndQuery(t *testing.T) {
-	d, err := db.Open(t.TempDir())
+func openTestStore(t *testing.T) *Store {
+	t.Helper()
+	sqldb, err := sql.Open("sqlite", ":memory:?_pragma=journal_mode(WAL)")
 	if err != nil {
-		t.Fatalf("db: %v", err)
+		t.Fatal(err)
 	}
-	defer d.Close()
-
-	s, err := NewStore(d.DB)
+	sqldb.SetMaxOpenConns(1)
+	s, err := NewStore(sqldb)
 	if err != nil {
-		t.Fatalf("store: %v", err)
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { sqldb.Close() })
+	return s
+}
+
+func TestSchemaCreation(t *testing.T) {
+	s := openTestStore(t)
+	for _, tbl := range []string{"client_bw_raw", "client_bw_5m", "client_bw_daily"} {
+		var name string
+		err := s.db.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name=?", tbl).Scan(&name)
+		if err != nil {
+			t.Errorf("table %s not created: %v", tbl, err)
+		}
 	}
+}
 
+func TestInsertAndQuery(t *testing.T) {
+	s := openTestStore(t)
 	now := time.Now()
 	for i := 0; i < 10; i++ {
 		if err := s.Insert(Sample{
 			MAC: "aa:bb:cc:dd:ee:ff", RouterID: "gw",
 			TS: now.Add(time.Duration(i) * time.Minute),
 			RxBytes: uint64(i * 1000), TxBytes: uint64(i * 500),
+			RxBps: float64(i * 8000), TxBps: float64(i * 4000),
 		}); err != nil {
 			t.Fatalf("insert: %v", err)
 		}
@@ -38,26 +56,21 @@ func TestInsertAndQuery(t *testing.T) {
 	if len(points) != 10 {
 		t.Fatalf("expected 10 points, got %d", len(points))
 	}
+	// El bps viaja hasta la serie (patrón portseries, #551).
+	if points[9].RxBps != 9*8000 || points[9].TxBps != 9*4000 {
+		t.Fatalf("bps no persistido: %+v", points[9])
+	}
 }
 
 func TestRollup(t *testing.T) {
-	d, err := db.Open(t.TempDir())
-	if err != nil {
-		t.Fatalf("db: %v", err)
-	}
-	defer d.Close()
-
-	s, err := NewStore(d.DB)
-	if err != nil {
-		t.Fatalf("store: %v", err)
-	}
-
+	s := openTestStore(t)
 	now := time.Now()
 	for i := 0; i < 20; i++ {
 		_ = s.Insert(Sample{
 			MAC: "aa:bb:cc:dd:ee:ff", RouterID: "gw",
-			TS: now.Add(time.Duration(i) * time.Minute),
+			TS:      now.Add(time.Duration(i) * time.Minute),
 			RxBytes: 1000, TxBytes: 500,
+			RxBps: 8000, TxBps: 4000,
 		})
 	}
 
@@ -73,20 +86,16 @@ func TestRollup(t *testing.T) {
 	if len(points) == 0 {
 		t.Fatal("expected 5m buckets after rollup")
 	}
+	// Los rollups YA calculan bps reales (antes quedaban a 0, #551).
+	for _, p := range points {
+		if p.RxBps != 8000 || p.TxBps != 4000 {
+			t.Fatalf("bps en bucket: %+v", p)
+		}
+	}
 }
 
 func TestTopClients(t *testing.T) {
-	d, err := db.Open(t.TempDir())
-	if err != nil {
-		t.Fatalf("db: %v", err)
-	}
-	defer d.Close()
-
-	s, err := NewStore(d.DB)
-	if err != nil {
-		t.Fatalf("store: %v", err)
-	}
-
+	s := openTestStore(t)
 	now := time.Now()
 	macs := []string{"aa:bb:cc:dd:ee:01", "aa:bb:cc:dd:ee:02", "aa:bb:cc:dd:ee:03"}
 	for i, mac := range macs {
@@ -111,6 +120,37 @@ func TestTopClients(t *testing.T) {
 	}
 }
 
+func TestGetMACSeriesAgregaRouters(t *testing.T) {
+	s := openTestStore(t)
+	now := time.Now().Truncate(time.Minute).Add(time.Minute)
+	// La misma MAC vista en dos routers (roaming) a la misma hora.
+	for _, rid := range []string{"rt2", "rt4"} {
+		for i := 0; i < 3; i++ {
+			_ = s.Insert(Sample{
+				MAC: "aa:bb:cc:dd:ee:ff", RouterID: rid,
+				TS:      now.Add(time.Duration(i) * time.Minute),
+				RxBytes: 1000, TxBytes: 500, RxBps: 8000, TxBps: 4000,
+			})
+		}
+	}
+	// GetSeries con router filtra; GetMACSeries agrega ambos.
+	one, err := s.GetSeries("aa:bb:cc:dd:ee:ff", "rt2", now.Add(-time.Hour), now.Add(time.Hour), "raw")
+	if err != nil || len(one) != 3 {
+		t.Fatalf("serie por router: %d %v", len(one), err)
+	}
+	all, err := s.GetMACSeries("aa:bb:cc:dd:ee:ff", now.Add(-time.Hour), now.Add(time.Hour), "raw")
+	if err != nil {
+		t.Fatalf("serie mac: %v", err)
+	}
+	// Mismo ts en ambos routers → cada punto agrega 2 muestras.
+	if len(all) != 3 {
+		t.Fatalf("serie mac puntos: %d (want 3)", len(all))
+	}
+	if all[0].RxBytes != 2000 || all[0].TxBytes != 1000 {
+		t.Fatalf("agregación mac: %+v", all[0])
+	}
+}
+
 func TestNilDB(t *testing.T) {
 	s, err := NewStore(nil)
 	if err != nil {

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

@@ -19,6 +19,7 @@ import (
 
 	_ "modernc.org/sqlite"
 
+	"github.com/gnacho/netpulse/server-go/internal/clientbw"
 	"github.com/gnacho/netpulse/server-go/internal/portseries"
 )
 
@@ -365,6 +366,9 @@ type DB struct {
 	rollbackJournal bool
 	// PortSeries: per-port time series store (issue #302).
 	PortSeries *portseries.Store
+	// ClientBW: per-client bandwidth store (issue #337/#551). Wiring añadido
+	// en el #551: la ingesta escribe samples delta por (mac, router).
+	ClientBW *clientbw.Store
 }
 
 // NowMS devuelve el epoch actual en milisegundos (como Date.now()).
@@ -480,6 +484,12 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 		return nil, fmt.Errorf("port_series store: %w", err)
 	}
 	d.PortSeries = ps
+	cb, err := clientbw.NewStore(sqldb)
+	if err != nil {
+		sqldb.Close()
+		return nil, fmt.Errorf("client_bw store: %w", err)
+	}
+	d.ClientBW = cb
 	d.wg.Add(1)
 	go d.maintenanceLoop()
 	return d, nil
@@ -606,6 +616,11 @@ func (d *DB) NightlyJob() {
 	if d.PortSeries != nil {
 		d.PortSeries.NightlyJob()
 	}
+
+	// Per-client bandwidth rollup (#337/#551).
+	if d.ClientBW != nil {
+		d.ClientBW.NightlyJob()
+	}
 }
 
 // BucketMS es el tamaño del bucket medio en ms (5 minutos).

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

@@ -12,6 +12,7 @@ import (
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/clientbw"
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 	"github.com/gnacho/netpulse/server-go/internal/portseries"
 	"github.com/gnacho/netpulse/server-go/internal/roamevents"
@@ -580,3 +581,66 @@ func (s *server) handlePortSeries(w http.ResponseWriter, r *http.Request) {
 		"portId":     portID,
 	})
 }
+
+// handleDeviceTraffic: GET /api/devices/{mac}/traffic
+// Serie de tráfico por cliente (issue #551) agregando a través de TODOS los
+// routers (roaming). Query params: from (unix s), to (unix s), resolution
+// (raw|5m|daily). La UI del detalle lo llama bajo demanda (patrón portseries).
+func (s *server) handleDeviceTraffic(w http.ResponseWriter, r *http.Request) {
+	if s.db == nil || s.db.ClientBW == nil {
+		writeError(w, http.StatusServiceUnavailable, "unavailable")
+		return
+	}
+	mac := normalizeMAC(r.PathValue("mac"))
+	if len(mac) != len("aa:bb:cc:dd:ee:ff") {
+		writeError(w, http.StatusBadRequest, "invalid_mac")
+		return
+	}
+	q := r.URL.Query()
+	now := time.Now()
+	to := now
+	from := now.Add(-24 * time.Hour)
+	if v := q.Get("from"); v != "" {
+		if ts, err := strconv.ParseInt(v, 10, 64); err == nil {
+			from = time.Unix(ts, 0)
+		}
+	}
+	if v := q.Get("to"); v != "" {
+		if ts, err := strconv.ParseInt(v, 10, 64); err == nil {
+			to = time.Unix(ts, 0)
+		}
+	}
+	resolution := q.Get("resolution")
+	if resolution == "" {
+		resolution = clientbwResolution(from, to)
+	}
+	if resolution != "raw" && resolution != "5m" && resolution != "daily" {
+		writeError(w, http.StatusBadRequest, "invalid_resolution")
+		return
+	}
+	points, err := s.db.ClientBW.GetMACSeries(mac, from, to, resolution)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "query_error", err.Error())
+		return
+	}
+	if points == nil {
+		points = []clientbw.Point{}
+	}
+	writeJSON(w, http.StatusOK, map[string]any{
+		"points":     points,
+		"resolution": resolution,
+		"mac":        mac,
+	})
+}
+
+// clientbwResolution elige el tier según el rango (misma escala que portseries).
+func clientbwResolution(from, to time.Time) string {
+	dur := to.Sub(from)
+	if dur <= 24*time.Hour {
+		return "raw"
+	}
+	if dur <= 30*24*time.Hour {
+		return "5m"
+	}
+	return "daily"
+}

+ 67 - 0
server-go/internal/httpapi/httpapi_test.go

@@ -19,6 +19,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/channelplan"
 	"github.com/gnacho/netpulse/server-go/internal/config"
 	"github.com/gnacho/netpulse/server-go/internal/configbackup"
+	"github.com/gnacho/netpulse/server-go/internal/clientbw"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/httpapi"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
@@ -1037,3 +1038,69 @@ func TestPortSeriesInvalidResolution(t *testing.T) {
 		t.Errorf("expected 400 for invalid resolution, got %d", res.StatusCode)
 	}
 }
+
+func TestDeviceTrafficEndpoint(t *testing.T) {
+	srv := makeTestServer(t)
+	defer srv.Close()
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	if srv.db.ClientBW == nil {
+		t.Fatal("ClientBW store not initialized")
+	}
+	now := time.Now()
+	err := srv.db.ClientBW.Insert(clientbw.Sample{
+		MAC: "aa:bb:cc:dd:ee:01", RouterID: "rt2", TS: now,
+		RxBytes: 1000, TxBytes: 2000, RxBps: 8000, TxBps: 16000,
+	})
+	if err != nil {
+		t.Fatalf("insert sample: %v", err)
+	}
+
+	from := now.Add(-time.Hour).Unix()
+	to := now.Add(time.Hour).Unix()
+	req, _ := http.NewRequest("GET",
+		fmt.Sprintf("%s/api/devices/aa:bb:cc:dd:ee:01/traffic?from=%d&to=%d", srv.URL, from, to), nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("request: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != 200 {
+		t.Fatalf("expected 200, got %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	points, ok := body["points"].([]any)
+	if !ok || len(points) == 0 {
+		t.Fatalf("expected points, got %T %v", body["points"], body["points"])
+	}
+	// La MAC del path se normaliza: formato con guiones también vale.
+	req2, _ := http.NewRequest("GET",
+		fmt.Sprintf("%s/api/devices/aa-bb-cc-dd-ee-01/traffic?from=%d&to=%d", srv.URL, from, to), nil)
+	req2.Header.Set("Cookie", "session="+cookie)
+	res2, err := http.DefaultClient.Do(req2)
+	if err != nil {
+		t.Fatalf("request guiones: %v", err)
+	}
+	defer res2.Body.Close()
+	if res2.StatusCode != 200 {
+		t.Fatalf("guiones expected 200, got %d", res2.StatusCode)
+	}
+}
+
+func TestDeviceTrafficInvalidMAC(t *testing.T) {
+	srv := makeTestServer(t)
+	defer srv.Close()
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	req, _ := http.NewRequest("GET", srv.URL+"/api/devices/not-a-mac/traffic", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("request: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != 400 {
+		t.Fatalf("expected 400 for invalid mac, got %d", res.StatusCode)
+	}
+}

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

@@ -316,6 +316,7 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("GET /api/device-events", s.handleDeviceEvents)
 	mux.HandleFunc("GET /api/adguard/clients", s.handleAdguardClients)
 	mux.HandleFunc("GET /api/routers/{id}/ports/{portId}/series", s.handlePortSeries)
+	mux.HandleFunc("GET /api/devices/{mac}/traffic", s.handleDeviceTraffic)
 	mux.HandleFunc("GET /api/system/info", s.handleSystemInfo)
 	mux.HandleFunc("GET /api/reports/weekly", s.handleWeeklyReport)
 	mux.HandleFunc("GET /api/reports/availability", s.handleAvailabilityReport)