Răsfoiți Sursa

feat(ports): per-port counters and rates from /proc/net/dev (#316)

Extend EthPort with per-port stats (iface, rx/tx bytes and errors,
instantaneous rates) so OpenWrt switches and routers expose live
per-port traffic:

- probe: ParseNetDevIfaces (per-iface counters), IfRates (pure delta),
  BuildEthPorts enriches ports matched by physical iface name
- server SSH: GetNetDev returns aggregate + per-iface rates in one
  /proc/net/dev read (replaces GetNetDevBps)
- agent: payload section netIf with absolute counters; server computes
  per-port rates with the delta between payloads and injects them
  (match by iface, fallback by id); anti-flicker keeps last good rates
- UI: PortPanel shows live port traffic under the speed and traffic/
  error stats in the port tooltip (es/en)

Closes #305

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 luni în urmă
părinte
comite
1eae95302f

+ 22 - 1
agent/probe/local.go

@@ -62,6 +62,10 @@ type Prober struct {
 	lastNetTx  float64
 	lastNetAt  time.Time
 	hasLastNet bool
+	// lastNetRaw conserva el último output de /proc/net/dev de probeSystem
+	// para derivar la sección NetIf (contadores por iface, #305) sin un
+	// segundo cat.
+	lastNetRaw string
 }
 
 // NewProber crea el prober con el runner dado.
@@ -92,6 +96,12 @@ func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
 	pl.Data.FDB = p.probeFDB(ctx)
 	pl.Data.Dawn = p.probeDawn(ctx)
 	pl.Data.LuCI = p.probeLuCI(ctx)
+	// NetIf (#305): contadores por iface desde el MISMO /proc/net/dev que
+	// leyó probeSystem (sin segundo cat). Los rates los computa el server
+	// con el delta entre payloads.
+	if p.lastNetRaw != "" {
+		pl.Data.NetIf = ParseNetDevIfaces(p.lastNetRaw)
+	}
 	return pl
 }
 
@@ -152,6 +162,7 @@ func (p *Prober) probeSystem(ctx context.Context) *SystemData {
 			sd.RxBps, sd.TxBps = NetDevBps(p.lastNetRx, p.lastNetTx, rx, tx, now.Sub(p.lastNetAt).Seconds())
 		}
 		p.lastNetRx, p.lastNetTx, p.lastNetAt, p.hasLastNet = rx, tx, now, true
+		p.lastNetRaw = out
 		any = true
 	}
 
@@ -260,7 +271,17 @@ func (p *Prober) probeFDB(ctx context.Context) *FDBData {
 				}
 			}
 		}
-		fd.Ports = BuildEthPorts(layout, states, members)
+		// Contadores por iface (#305): absolutos del MISMO /proc/net/dev de
+		// probeSystem (si ya corrió este ciclo); los rates los computa el
+		// server con el delta entre payloads.
+		var ifaces map[string]IfRate
+		if p.lastNetRaw != "" {
+			ifaces = map[string]IfRate{}
+			for name, c := range ParseNetDevIfaces(p.lastNetRaw) {
+				ifaces[name] = IfRate{IfCounters: c}
+			}
+		}
+		fd.Ports = BuildEthPorts(layout, states, members, ifaces)
 		any = true
 	}
 	if !any {

+ 6 - 2
agent/probe/payload.go

@@ -17,8 +17,8 @@ type Payload struct {
 	// Interval declara la cadencia de push en SEGUNDOS (#288). 0 = default
 	// del agente nativo (~30 s). Un pusher externo que empuja cada 5 min
 	// declara 300 y el server amplía su TTL a 3x ese intervalo.
-	Interval int           `json:"interval,omitempty"`
-	Data     PayloadData   `json:"data"`
+	Interval int         `json:"interval,omitempty"`
+	Data     PayloadData `json:"data"`
 }
 
 // PayloadData agrupa las secciones del tier rápido. Punteros/mapas nil =
@@ -33,6 +33,10 @@ type PayloadData struct {
 	// LuCI: etiquetas de puertos/VLANs del router (issue #258), si están
 	// definidas en /etc/config/luci.
 	LuCI *LuCILabels `json:"luci,omitempty"`
+	// NetIf: contadores acumulados POR INTERFAZ de /proc/net/dev (issue
+	// #305). El servidor calcula los rates por boca con el delta entre
+	// payloads. nil = sonda fallida (conserva la última buena).
+	NetIf map[string]IfCounters `json:"netIf,omitempty"`
 }
 
 // SystemData: salud del equipo + tráfico + latencias.

+ 88 - 3
agent/probe/probe.go

@@ -143,12 +143,40 @@ type PortLayout struct {
 	Role  string `json:"role"` // "lan" | "wan"
 }
 
-// EthPort es una boca ethernet lista para el detalle ({id, label, up, speed?}).
+// EthPort es una boca ethernet lista para el detalle ({id, label, up, speed?}
+// + contadores por puerto #305: iface física, bytes/errores acumulados y
+// rates instantáneos; omitempty para no engordar el contrato viejo).
 type EthPort struct {
 	ID    string `json:"id"`
 	Label string `json:"label"`
 	Up    bool   `json:"up"`
 	Speed string `json:"speed,omitempty"` // solo si up
+	// Iface física de la boca (/proc/net/dev); puede diferir del id en
+	// plataformas swconfig ("1" vs "eth0.1").
+	Iface string `json:"iface,omitempty"`
+	// Contadores acumulados de la iface (issue #305).
+	RxBytes uint64   `json:"rxBytes,omitempty"`
+	TxBytes uint64   `json:"txBytes,omitempty"`
+	RxErrs  uint64   `json:"rxErrors,omitempty"`
+	TxErrs  uint64   `json:"txErrors,omitempty"`
+	RxBps   *float64 `json:"rxBps,omitempty"`
+	TxBps   *float64 `json:"txBps,omitempty"`
+}
+
+// IfCounters son los contadores acumulados de UNA interfaz de /proc/net/dev.
+type IfCounters struct {
+	Rx    uint64 // bytes
+	Tx    uint64 // bytes
+	RxErr uint64
+	TxErr uint64
+}
+
+// IfRate añade a los contadores los rates instantáneos (delta entre muestras;
+// punteros nil = primera muestra o iface nueva, sin rate todavía).
+type IfRate struct {
+	IfCounters
+	RxBps *float64
+	TxBps *float64
 }
 
 // Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).
@@ -242,6 +270,48 @@ func ParseNetDev(out string) (rx, tx float64) {
 	return rx, tx
 }
 
+// ParseNetDevIfaces devuelve los contadores POR INTERFAZ de /proc/net/dev
+// (sin filtrar: el consumidor decide qué ifaces le interesan; las bocas
+// físicas se casan por nombre con el layout, issue #305).
+func ParseNetDevIfaces(out string) map[string]IfCounters {
+	res := map[string]IfCounters{}
+	lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		m := lineRe.FindStringSubmatch(line)
+		if m == nil {
+			continue
+		}
+		fields := strings.Fields(strings.TrimSpace(m[2]))
+		num := func(i int) uint64 {
+			if i < len(fields) {
+				n, _ := strconv.ParseUint(fields[i], 10, 64)
+				return n
+			}
+			return 0
+		}
+		res[m[1]] = IfCounters{
+			Rx: num(0), Tx: num(8), // bytes
+			RxErr: num(2), TxErr: num(10),
+		}
+	}
+	return res
+}
+
+// IfRates calcula los rates por interfaz con el delta de contadores entre
+// dos muestras separadas dt segundos. Ifaces nuevas o dt <= 0 → nil rates.
+// Contadores reseteados (reboot) → max0 dentro de NetDevBps da 0, no negativos.
+func IfRates(prev, cur map[string]IfCounters, dt float64) map[string]IfRate {
+	res := make(map[string]IfRate, len(cur))
+	for name, c := range cur {
+		r := IfRate{IfCounters: c}
+		if p, ok := prev[name]; ok && dt > 0 {
+			r.RxBps, r.TxBps = NetDevBps(float64(p.Rx), float64(p.Tx), float64(c.Rx), float64(c.Tx), dt)
+		}
+		res[name] = r
+	}
+	return res
+}
+
 // NetDevBps: bps por delta de contadores en dt segundos (nil si dt <= 0 o
 // contadores reseteados).
 func NetDevBps(prevRx, prevTx, rx, tx, dt float64) (rxBps, txBps *float64) {
@@ -526,8 +596,20 @@ func ParsePortLayout(out string) ([]PortLayout, error) {
 
 // BuildEthPorts: layout + estado /sys → []EthPort listo para el detalle.
 // brMembers = miembros del bridge br-lan (AP en bridge re-etiqueta wan→LAN
-// N+1); sin layout, fallback heurístico. Literal de openwrt.go GetEthPorts.
-func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool) []EthPort {
+// N+1); sin layout, fallback heurístico. ifaces = contadores/rates por iface
+// física (issue #305; nil = sin datos, las bocas salen sin stats). Literal de
+// openwrt.go GetEthPorts.
+func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool, ifaces map[string]IfRate) []EthPort {
+	applyStats := func(ep *EthPort, iface string) {
+		st, ok := ifaces[iface]
+		if !ok {
+			return
+		}
+		ep.Iface = iface
+		ep.RxBytes, ep.TxBytes = st.Rx, st.Tx
+		ep.RxErrs, ep.TxErrs = st.RxErr, st.TxErr
+		ep.RxBps, ep.TxBps = st.RxBps, st.TxBps
+	}
 	byName := map[string]PortState{}
 	for _, p := range states {
 		byName[p.Name] = p
@@ -551,6 +633,7 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 			if up {
 				ep.Speed = st.Speed
 			}
+			applyStats(&ep, p.Name)
 			ports = append(ports, ep)
 		}
 		return ports
@@ -570,6 +653,7 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 		if p.Up {
 			ep.Speed = p.Speed
 		}
+		applyStats(&ep, p.Name)
 		ports = append(ports, ep)
 	}
 	wanName := ""
@@ -586,6 +670,7 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 		if st.Up {
 			ep.Speed = st.Speed
 		}
+		applyStats(&ep, wanName)
 		ports = append([]EthPort{ep}, ports...)
 	}
 	return ports

+ 76 - 2
agent/probe/probe_test.go

@@ -64,6 +64,80 @@ func TestParseNetDevYBps(t *testing.T) {
 	}
 }
 
+func TestParseNetDevIfaces(t *testing.T) {
+	out := "  eth0: 1000000 5 2 0 0 0 0 0 500000 7 1 0 0 0 0 0\n" +
+		"  lan1: 2000000 9 0 0 0 0 0 0 1000000 4 3 0 0 0 0 0\n" +
+		"basura sin formato\n"
+	ifaces := ParseNetDevIfaces(out)
+	if len(ifaces) != 2 {
+		t.Fatalf("ifaces: %+v", ifaces)
+	}
+	e, ok := ifaces["eth0"]
+	if !ok || e.Rx != 1000000 || e.Tx != 500000 || e.RxErr != 2 || e.TxErr != 1 {
+		t.Fatalf("eth0: %+v", e)
+	}
+	l, ok := ifaces["lan1"]
+	if !ok || l.RxErr != 0 || l.TxErr != 3 {
+		t.Fatalf("lan1: %+v", l)
+	}
+	if ParseNetDevIfaces("") == nil {
+		t.Fatal("vacío → mapa no nil")
+	}
+}
+
+func TestIfRates(t *testing.T) {
+	prev := map[string]IfCounters{"lan1": {Rx: 1000, Tx: 2000}, "wan": {Rx: 500, Tx: 500}}
+	cur := map[string]IfCounters{"lan1": {Rx: 3000, Tx: 6000}, "wan": {Rx: 400, Tx: 900}, "lan2": {Rx: 10, Tx: 10}}
+	rates := IfRates(prev, cur, 2)
+	if len(rates) != 3 {
+		t.Fatalf("rates: %+v", rates)
+	}
+	l1 := rates["lan1"]
+	if l1.RxBps == nil || *l1.RxBps != 8000 || l1.TxBps == nil || *l1.TxBps != 16000 {
+		t.Fatalf("lan1 rates: %+v", l1)
+	}
+	// Contador reseteado (cur < prev) → 0, no negativo
+	w := rates["wan"]
+	if w.RxBps == nil || *w.RxBps != 0 || w.TxBps == nil || *w.TxBps != 1600 {
+		t.Fatalf("wan reset: %+v", w)
+	}
+	// Iface nueva sin previa → sin rate
+	if rates["lan2"].RxBps != nil || rates["lan2"].TxBps != nil {
+		t.Fatalf("lan2 nueva: %+v", rates["lan2"])
+	}
+	// dt <= 0 → todo sin rate
+	rates = IfRates(prev, cur, 0)
+	if rates["lan1"].RxBps != nil {
+		t.Fatal("dt=0 → nil rates")
+	}
+}
+
+func TestBuildEthPortsConIfaces(t *testing.T) {
+	layout := []PortLayout{{ID: "lan1", Name: "lan1", Label: "LAN 1", Role: "lan"}}
+	states := []PortState{{Name: "lan1", Up: true, Speed: "1 Gbps"}}
+	rxb, txb := 40e6, 12e6
+	ifaces := map[string]IfRate{
+		"lan1":  {IfCounters: IfCounters{Rx: 1000, Tx: 2000, RxErr: 3}, RxBps: &rxb, TxBps: &txb},
+		"wlan0": {IfCounters: IfCounters{Rx: 99}}, // no es boca: se ignora
+	}
+	ports := BuildEthPorts(layout, states, nil, ifaces)
+	if len(ports) != 1 {
+		t.Fatalf("ports: %+v", ports)
+	}
+	p := ports[0]
+	if p.Iface != "lan1" || p.RxBytes != 1000 || p.TxBytes != 2000 || p.RxErrs != 3 {
+		t.Fatalf("stats: %+v", p)
+	}
+	if p.RxBps == nil || *p.RxBps != rxb || p.TxBps == nil || *p.TxBps != txb {
+		t.Fatalf("rates: %+v", p)
+	}
+	// Fallback (sin layout) también enriquece
+	ports = BuildEthPorts(nil, []PortState{{Name: "lan1", Up: true, Speed: "1 Gbps"}}, nil, ifaces)
+	if len(ports) != 1 || ports[0].Iface != "lan1" || ports[0].RxBytes != 1000 {
+		t.Fatalf("fallback stats: %+v", ports)
+	}
+}
+
 func TestParsePingSummary(t *testing.T) {
 	out := "3 packets transmitted, 3 received, 0% packet loss, time 2003ms\nrtt min/avg/max/mdev = 8.123/9.456/10.999/0.5 ms"
 	lat, loss := ParsePingSummary(out)
@@ -152,12 +226,12 @@ func TestParsePortsYLayout(t *testing.T) {
 		t.Fatalf("layout: %v %+v", err, layout)
 	}
 	// AP en bridge: wan en br-lan → se re-etiqueta LAN 5
-	ports := BuildEthPorts(layout, states, map[string]bool{"wan": true})
+	ports := BuildEthPorts(layout, states, map[string]bool{"wan": true}, nil)
 	if len(ports) != 5 || ports[0].Label != "LAN 5" {
 		t.Fatalf("ethports bridge: %+v", ports)
 	}
 	// Sin layout: fallback heurístico
-	ports = BuildEthPorts(nil, ParsePortStates("lan2 up 1000\nlan10 up 100\nwan down -1\n"), nil)
+	ports = BuildEthPorts(nil, ParsePortStates("lan2 up 1000\nlan10 up 100\nwan down -1\n"), nil, nil)
 	if len(ports) != 3 || ports[0].ID != "wan" || ports[1].ID != "lan2" || ports[2].ID != "lan10" {
 		t.Fatalf("ethports fallback: %+v", ports)
 	}

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

@@ -495,6 +495,8 @@
       "wanGateway": "Gateway",
       "wanDns": "DNS",
       "deviceDetail": "Detail",
+      "traffic": "Traffic",
+      "errors": "Errors",
       "wirelessUplink": " · wireless uplink (mesh)"
     },
     "radios": {

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

@@ -495,6 +495,8 @@
       "wanGateway": "Puerta de enlace",
       "wanDns": "Servidor DNS",
       "deviceDetail": "Detalle",
+      "traffic": "Tráfico",
+      "errors": "Errores",
       "wirelessUplink": " · uplink inalámbrico (mesh)"
     },
     "radios": {

+ 31 - 0
app/src/components/routers/PortPanel.tsx

@@ -16,6 +16,16 @@ import { cn } from '@/lib/utils'
  * Variante compacta (APs, col-span-5) y ancha (gateway, col-span-12).
  */
 
+/** fmtPortBps: rate de una boca en humano ("12.4 Mbps" · "320 kbps" · "0").
+ *  undefined (sin dato todavía) → "—" para no confundirlo con 0 real. */
+function fmtPortBps(bps?: number): string {
+  if (bps === undefined || Number.isNaN(bps)) return '—'
+  if (bps >= 1e9) return `${(bps / 1e9).toFixed(1)} Gbps`
+  if (bps >= 1e6) return `${(bps / 1e6).toFixed(1)} Mbps`
+  if (bps >= 1e3) return `${Math.round(bps / 1e3)} kbps`
+  return `${Math.round(bps)} bps`
+}
+
 function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInfo }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
@@ -105,6 +115,11 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
                   )}
                 </div>
                 {port.speed && <div className="font-mono text-[10px] text-text-muted">{port.speed}</div>}
+                {(port.rxBps !== undefined || port.txBps !== undefined) && (
+                  <div className="font-mono text-[10px] text-text-muted">
+                    ↓{fmtPortBps(port.rxBps)} ↑{fmtPortBps(port.txBps)}
+                  </div>
+                )}
               </>
             ) : (
               <div className="mt-0.5 text-caption text-text-muted">{t('routerDetail.ports.free')}</div>
@@ -161,6 +176,22 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
                 <div className="mt-2 grid grid-cols-2 gap-1.5">
                   <MiniStat label="MAC" value={port.deviceMac} />
                   {port.detail && <MiniStat label={t('routerDetail.ports.deviceDetail')} value={port.detail} />}
+                  {(port.rxBps !== undefined || port.txBps !== undefined) && (
+                    <div className="col-span-2">
+                      <MiniStat
+                        label={t('routerDetail.ports.traffic')}
+                        value={`↓ ${fmtPortBps(port.rxBps)} · ↑ ${fmtPortBps(port.txBps)}`}
+                      />
+                    </div>
+                  )}
+                  {(port.rxErrors ?? 0) + (port.txErrors ?? 0) > 0 && (
+                    <div className="col-span-2">
+                      <MiniStat
+                        label={t('routerDetail.ports.errors')}
+                        value={`RX ${port.rxErrors ?? 0} · TX ${port.txErrors ?? 0}`}
+                      />
+                    </div>
+                  )}
                 </div>
               )
             )}

+ 7 - 0
app/src/components/routers/routerExtras.ts

@@ -42,6 +42,13 @@ export interface EthPort {
   label: string // "WAN" | "LAN 1"
   up: boolean
   speed?: string // "2.5 Gbps" | "1 Gbps"
+  iface?: string // interfaz física (/proc/net/dev), si difiere del id
+  rxBytes?: number // contadores acumulados de la boca (#305)
+  txBytes?: number
+  rxErrors?: number
+  txErrors?: number
+  rxBps?: number // rates instantáneos (#305)
+  txBps?: number
   connectedTo?: string // "NAS Synology" | "Salón · AX3000T"
   deviceMac?: string // MAC del dispositivo conectado (para enlazar a /devices)
   detail?: string // "192.168.8.10 · full duplex"

+ 53 - 0
server-go/internal/adapters/agent.go

@@ -315,6 +315,40 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 	return false, nil
 }
 
+// agentIfSample: contadores por iface del último payload del agente (para
+// el delta de rates por boca, issue #305).
+type agentIfSample struct {
+	at     time.Time
+	ifaces map[string]probe.IfCounters
+}
+
+// injectPortRates copia absolutos + rates de rates (keyed por iface física)
+// sobre las bocas: match por Iface si la boca la declara, si no por ID (en
+// DSA coinciden; en swconfig el ID es numérico y solo Iface casa).
+func injectPortRates(ports []EthPort, rates map[string]probe.IfRate) {
+	for i := range ports {
+		key := ports[i].Iface
+		if key == "" {
+			key = ports[i].ID
+		}
+		r, ok := rates[key]
+		if !ok {
+			continue
+		}
+		ports[i].Iface = key
+		ports[i].RxBytes = r.Rx
+		ports[i].TxBytes = r.Tx
+		ports[i].RxErrs = r.RxErr
+		ports[i].TxErrs = r.TxErr
+		if r.RxBps != nil {
+			ports[i].RxBps = *r.RxBps
+		}
+		if r.TxBps != nil {
+			ports[i].TxBps = *r.TxBps
+		}
+	}
+}
+
 // polledFromAgent convierte el payload del agente en el routerPolled del
 // pipeline (mismos shapes que el sondeo SSH). Aplica el mismo anti-parpadeo
 // que pollRouter: sección ausente en el payload = sonda fallida → conserva
@@ -428,6 +462,25 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	if out.luci == nil {
 		out.luci = cached.luci
 	}
+
+	// NetIf (issue #305): rates por boca con el delta entre payloads del
+	// agente. El payload trae contadores ABSOLUTOS por iface; el server
+	// calcula bps con la muestra anterior (ts del propio payload, no el
+	// reloj del server). Sección ausente → conserva los rates cacheados.
+	// Corre tras el anti-parpadeo (bocas definitivas) y ANTES de guardar el
+	// snapshot para que el cache lleve los rates frescos.
+	if p.Data.NetIf != nil {
+		now := time.Unix(p.Ts, 0)
+		l.mu.Lock()
+		prev := l.lastAgentIf[cfg.ID]
+		l.lastAgentIf[cfg.ID] = &agentIfSample{at: now, ifaces: p.Data.NetIf}
+		l.mu.Unlock()
+		if prev != nil && now.Sub(prev.at).Seconds() > 0 && len(out.ports) > 0 {
+			rates := probe.IfRates(prev.ifaces, p.Data.NetIf, now.Sub(prev.at).Seconds())
+			injectPortRates(out.ports, rates)
+		}
+	}
+
 	l.mu.Lock()
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
 		wireless: out.wireless, fdb: out.fdb, luci: out.luci}

+ 14 - 3
server-go/internal/adapters/live.go

@@ -182,6 +182,10 @@ type Live struct {
 	boardCache  map[string]*BoardInfo
 	layoutCache map[string][]PortLayout
 	extrasCache map[string]*extrasSnapshot
+	// lastAgentIf: /proc/net/dev por iface del ÚLTIMO payload del agente
+	// (contadores absolutos + ts) para calcular los rates por boca con el
+	// delta entre payloads (issue #305). Protegido por mu.
+	lastAgentIf map[string]*agentIfSample
 	lastPolled  map[string]*routerPolled
 	failCount   map[string]int
 	lastErr     map[string]error // último error del sondeo (issue #257: distinguir sin-acceso de caído)
@@ -252,6 +256,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		boardCache:           map[string]*BoardInfo{},
 		layoutCache:          map[string][]PortLayout{},
 		extrasCache:          map[string]*extrasSnapshot{},
+		lastAgentIf:          map[string]*agentIfSample{},
 		lastPolled:           map[string]*routerPolled{},
 		failCount:            map[string]int{},
 		lastErr:              map[string]error{},
@@ -351,6 +356,11 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.extrasCache, id)
 		}
 	}
+	for id := range l.lastAgentIf {
+		if !ids[id] {
+			delete(l.lastAgentIf, id)
+		}
+	}
 	for id := range l.lastPolled {
 		if !ids[id] {
 			delete(l.lastPolled, id)
@@ -719,8 +729,9 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	}
 	cpu, _ := client.GetCPUPercent()
 	temp, _ := client.GetTempC()
-	net, nerr := client.GetNetDevBps()
-	if nerr != nil || net == nil {
+	// NetDev: total agregado + rates POR IFACE (#305) en una sola lectura.
+	net, ifRates := client.GetNetDev()
+	if net == nil {
 		net = &NetDevBps{}
 	}
 	leases := client.GetDhcpLeases()
@@ -729,7 +740,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	// — coste: una llamada ubus local por poll.
 	glClients := client.GetGlClients()
 	wireless := client.GetWirelessClients()
-	ports := client.GetEthPorts(layout)
+	ports := client.GetEthPorts(layout, ifRates)
 	radios := client.GetRadios()
 	fdb := client.GetBridgeFdb()
 	brMac := client.GetBridgeMac()

+ 39 - 12
server-go/internal/adapters/openwrt.go

@@ -45,6 +45,9 @@ type OpenWrtClient struct {
 	sid        string     // sesión ubus HTTP cacheada
 	lastStat   *cpuSample // /proc/stat previo
 	lastNetDev *netSample // /proc/net/dev previo
+	// lastNetIf: /proc/net/dev previo POR INTERFAZ (contadores por boca,
+	// issue #305). Acceso serializado por mu.
+	lastNetIf *netIfSample
 	// lldpDownUntil: indisponibilidad de lldpd cacheada (≥5 min) para no
 	// martillear con un comando que no existe. Acceso serializado por mu.
 	lldpDownUntil time.Time
@@ -56,6 +59,11 @@ type netSample struct {
 	at     time.Time
 }
 
+type netIfSample struct {
+	at     time.Time
+	ifaces map[string]probe.IfCounters
+}
+
 // Aliases a los shapes compartidos de agent/probe: el agente nativo parsea
 // LOCALMENTE con el mismo package (misma fuente de verdad) y empuja esos
 // shapes al endpoint de ingesta (SPEC-AGENTE-PILOTO §1-2).
@@ -265,23 +273,33 @@ type NetDevBps struct {
 	TxBps *float64
 }
 
-// GetNetDevBps: tráfico agregado por delta (excluye lo, bridges, ifb, wg,
-// tun/tap para no duplicar contadores). Primera muestra: null/null.
-func (c *OpenWrtClient) GetNetDevBps() (*NetDevBps, error) {
+// GetNetDev: tráfico agregado por delta de /proc/net/dev (excluye lo,
+// bridges, ifb, wg, tun/tap para no duplicar contadores) + rates POR INTERFAZ
+// (issue #305, para las bocas del chasis). Una sola lectura de /proc/net/dev;
+// primera muestra: rates null.
+func (c *OpenWrtClient) GetNetDev() (*NetDevBps, map[string]probe.IfRate) {
 	out, err := c.pool.Run(c.Host, probe.CmdNetDev, 0)
 	if err != nil {
-		return nil, err
+		return nil, nil
 	}
 	rx, tx := parseNetDev(out)
+	curIf := probe.ParseNetDevIfaces(out)
 	now := time.Now()
+	c.mu.Lock()
+	defer c.mu.Unlock()
 	prev := c.lastNetDev
 	c.lastNetDev = &netSample{rx: rx, tx: tx, at: now}
+	prevIf := c.lastNetIf
+	c.lastNetIf = &netIfSample{at: now, ifaces: curIf}
 	res := &NetDevBps{}
-	if prev == nil {
-		return res, nil
+	if prev != nil {
+		res.RxBps, res.TxBps = probe.NetDevBps(prev.rx, prev.tx, rx, tx, now.Sub(prev.at).Seconds())
+	}
+	var rates map[string]probe.IfRate
+	if prevIf != nil {
+		rates = probe.IfRates(prevIf.ifaces, curIf, now.Sub(prevIf.at).Seconds())
 	}
-	res.RxBps, res.TxBps = probe.NetDevBps(prev.rx, prev.tx, rx, tx, now.Sub(prev.at).Seconds())
-	return res, nil
+	return res, rates
 }
 
 // parseNetDev suma rx/tx de las interfaces físicas (compartido con el agente).
@@ -432,8 +450,9 @@ func parsePortLayout(out string) ([]PortLayout, error) {
 }
 
 // GetEthPorts: layout + estado /sys; AP en bridge re-etiqueta wan→LAN N+1;
-// fallback heurístico sin config. Devuelve []EthPort listo para el detalle.
-func (c *OpenWrtClient) GetEthPorts(layout []PortLayout) []EthPort {
+// fallback heurístico sin config. rates = contadores por iface (#305, de
+// GetNetDev; nil = sin stats). Devuelve []EthPort listo para el detalle.
+func (c *OpenWrtClient) GetEthPorts(layout []PortLayout, rates map[string]probe.IfRate) []EthPort {
 	states := c.GetPortStates()
 	members := map[string]bool{}
 	if len(layout) > 0 {
@@ -445,14 +464,22 @@ func (c *OpenWrtClient) GetEthPorts(layout []PortLayout) []EthPort {
 			}
 		}
 	}
-	return ethPortsToAdapter(probe.BuildEthPorts(layout, states, members))
+	return ethPortsToAdapter(probe.BuildEthPorts(layout, states, members, rates))
 }
 
 // ethPortsToAdapter convierte el shape compartido al EthPort del contrato.
 func ethPortsToAdapter(in []probe.EthPort) []EthPort {
+	f := func(v *float64) float64 {
+		if v == nil {
+			return 0
+		}
+		return *v
+	}
 	out := make([]EthPort, 0, len(in))
 	for _, p := range in {
-		ep := EthPort{ID: p.ID, Label: p.Label, Up: p.Up}
+		ep := EthPort{ID: p.ID, Label: p.Label, Up: p.Up, Iface: p.Iface,
+			RxBytes: p.RxBytes, TxBytes: p.TxBytes, RxErrs: p.RxErrs, TxErrs: p.TxErrs,
+			RxBps: f(p.RxBps), TxBps: f(p.TxBps)}
 		if p.Up {
 			ep.Speed = p.Speed
 		}

+ 70 - 0
server-go/internal/adapters/portstats_agent_test.go

@@ -0,0 +1,70 @@
+// portstats_agent_test.go — #305: rates por boca desde el payload del agente.
+// El payload trae contadores ABSOLUTOS por iface (NetIf); el server calcula
+// bps con el delta entre payloads y los inyecta en las bocas (match por
+// Iface, fallback por ID). Sección ausente → conserva los rates cacheados.
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func TestPolledFromAgentNetIfRates(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{{ID: "patio", Host: "192.168.8.2", Name: "Patio"}}, nil)
+	cfg := l.routers[0]
+
+	// Primer push: bocas con iface + absolutos, NetIf presente. Sin previo
+	// no hay rates todavía.
+	p1 := &probe.Payload{Router: "patio", Ts: 1000, Version: "t"}
+	p1.Data.FDB = &probe.FDBData{
+		MACs:  map[string]string{},
+		Ports: []probe.EthPort{{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", Iface: "lan1", RxBytes: 1000, TxBytes: 2000}},
+	}
+	p1.Data.NetIf = map[string]probe.IfCounters{"lan1": {Rx: 1000, Tx: 2000}}
+	out := l.polledFromAgent(cfg, p1)
+	if out.ports[0].RxBps != 0 || out.ports[0].TxBps != 0 {
+		t.Fatalf("primera muestra sin rates: %+v", out.ports[0])
+	}
+
+	// Segundo push 30 s después: +3000 B rx / +6000 B tx → 800/1600 bps.
+	p2 := &probe.Payload{Router: "patio", Ts: 1030, Version: "t"}
+	p2.Data.FDB = &probe.FDBData{
+		MACs:  map[string]string{},
+		Ports: []probe.EthPort{{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", Iface: "lan1"}},
+	}
+	p2.Data.NetIf = map[string]probe.IfCounters{"lan1": {Rx: 4000, Tx: 8000, RxErr: 2}}
+	out = l.polledFromAgent(cfg, p2)
+	p := out.ports[0]
+	if p.RxBps != 800 || p.TxBps != 1600 {
+		t.Fatalf("rates: %+v", p)
+	}
+	if p.RxBytes != 4000 || p.TxBytes != 8000 || p.RxErrs != 2 {
+		t.Fatalf("absolutos: %+v", p)
+	}
+
+	// Push SIN NetIf (BuildWireless): conserva bocas cacheadas con rates.
+	p3 := &probe.Payload{Router: "patio", Ts: 1060, Version: "t"}
+	out = l.polledFromAgent(cfg, p3)
+	if out.ports[0].RxBps != 800 || out.ports[0].RxBytes != 4000 {
+		t.Fatalf("anti-parpadeo rates: %+v", out.ports[0])
+	}
+
+	// Match por ID cuando la boca no declara Iface (pusher externo).
+	l2 := NewLive(nil, nil, []RouterConfig{{ID: "sw", Host: "192.168.8.9", Name: "SW"}}, nil)
+	q1 := &probe.Payload{Router: "sw", Ts: 2000, Version: "t",
+		Data: probe.PayloadData{
+			FDB:   &probe.FDBData{MACs: map[string]string{}, Ports: []probe.EthPort{{ID: "lan1", Label: "P1", Up: true}}},
+			NetIf: map[string]probe.IfCounters{"lan1": {Rx: 100, Tx: 100}},
+		}}
+	q2 := &probe.Payload{Router: "sw", Ts: 2010, Version: "t",
+		Data: probe.PayloadData{
+			FDB:   &probe.FDBData{MACs: map[string]string{}, Ports: []probe.EthPort{{ID: "lan1", Label: "P1", Up: true}}},
+			NetIf: map[string]probe.IfCounters{"lan1": {Rx: 300, Tx: 300}},
+		}}
+	l2.polledFromAgent(l2.routers[0], q1)
+	out = l2.polledFromAgent(l2.routers[0], q2)
+	if out.ports[0].Iface != "lan1" || out.ports[0].RxBps != 160 || out.ports[0].TxBps != 160 {
+		t.Fatalf("match por ID: %+v", out.ports[0])
+	}
+}

+ 16 - 8
server-go/internal/adapters/types.go

@@ -376,15 +376,23 @@ type PerfSeries struct {
 }
 
 // EthPort es una boca ethernet ({id, label, up, speed?} + enriquecimiento de
-// vecino en el detalle: connectedTo/deviceMac/detail, SPEC §7.8).
+// vecino en el detalle: connectedTo/deviceMac/detail, SPEC §7.8 + contadores
+// por puerto #305: iface física, bytes/errores acumulados y rates).
 type EthPort struct {
-	ID          string `json:"id"`
-	Label       string `json:"label"`
-	Up          bool   `json:"up"`
-	Speed       string `json:"speed,omitempty"` // solo si up ("1 Gbps"|"100 Mbps")
-	ConnectedTo string `json:"connectedTo,omitempty"`
-	DeviceMac   string `json:"deviceMac,omitempty"`
-	Detail      string `json:"detail,omitempty"`
+	ID          string  `json:"id"`
+	Label       string  `json:"label"`
+	Up          bool    `json:"up"`
+	Speed       string  `json:"speed,omitempty"` // solo si up ("1 Gbps"|"100 Mbps")
+	Iface       string  `json:"iface,omitempty"` // iface física (/proc/net/dev)
+	RxBytes     uint64  `json:"rxBytes,omitempty"`
+	TxBytes     uint64  `json:"txBytes,omitempty"`
+	RxErrs      uint64  `json:"rxErrors,omitempty"`
+	TxErrs      uint64  `json:"txErrors,omitempty"`
+	RxBps       float64 `json:"rxBps,omitempty"`
+	TxBps       float64 `json:"txBps,omitempty"`
+	ConnectedTo string  `json:"connectedTo,omitempty"`
+	DeviceMac   string  `json:"deviceMac,omitempty"`
+	Detail      string  `json:"detail,omitempty"`
 }
 
 // Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).