Selaa lähdekoodia

feat(mqtt): publish fleet state to an MQTT broker with Home Assistant discovery (#826)

Opt-in MQTT publisher for the fleet state (instance status, per-router state
and alerts) with Home Assistant discovery. Disabled by default, configured
with the NETPULSE_MQTT_* variables (mqtt_* UCI options on-box).
Nacho 2 kuukautta sitten
vanhempi
sitoutus
5b36374486

+ 5 - 0
README.es.md

@@ -141,6 +141,11 @@ por SNMP también son ciudadanos de primera.
   watchdog. O el servidor entero en modo on-box.
 - **Se actualiza solo**: el updater integrado comprueba releases y las aplica
   con swap atómico.
+- **MQTT + Home Assistant (opcional)**: publica el estado de la flota (salud,
+  clientes, vitales por router y alertas) en un broker MQTT; Home Assistant
+  descubre las entidades solo. Desactivado por defecto, se configura con las
+  variables de entorno `NETPULSE_MQTT_*` (o las opciones UCI `mqtt_*` en
+  on-box).
 
 Esto sigue siendo una selección: **[todas las funcionalidades están en la
 web](https://netpulse.cloudless.club/features)**, una a una, y todo lo

+ 4 - 0
README.md

@@ -134,6 +134,10 @@ client splits. SNMP-polled managed switches are first-class citizens too.
   whole server on-box.
 - **Self-updating**: the built-in updater checks for releases and applies them
   with an atomic swap.
+- **MQTT + Home Assistant (opt-in)**: publish the fleet state (health, clients,
+  per-router vitals and alerts) to an MQTT broker; Home Assistant discovers the
+  entities on its own. Off by default, configured with the `NETPULSE_MQTT_*`
+  environment variables (or the equivalent `mqtt_*` UCI options on-box).
 
 That is still a selection: **[every feature is on the website](https://netpulse.cloudless.club/features)**,
 one by one, and everything above is clickable in the **[live demo](https://demo.netpulse.cloudless.club)**.

+ 2 - 0
server-go/cmd/netpulse/main.go

@@ -44,6 +44,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 	"github.com/gnacho/netpulse/server-go/internal/firmware"
 	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
 	"github.com/gnacho/netpulse/server-go/internal/ntfy"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/pathanalysis"
@@ -661,6 +662,7 @@ func run() error {
 		// Aviso anónimo diario de instancia activa (#822). Fail-silent.
 		telemetry.New(dbHandle, httpapi.Version, cfg.DemoMode).Start(context.Background())
 		p.Start()
+		mqttpub.New(mqttpub.ConfigFromProcessEnv(), httpapi.Version, p.LastOverview, cfg.DemoMode).Start(context.Background())
 		upd.Start()
 		go fwScheduler.Start()
 		if eventsCollector != nil {

+ 1 - 0
server-go/go.mod

@@ -5,6 +5,7 @@ go 1.26
 require (
 	github.com/SherClockHolmes/webpush-go v1.4.0
 	github.com/gnacho/netpulse/agent v0.0.0
+	github.com/gonzalop/mq v0.9.10
 	github.com/gosnmp/gosnmp v1.44.0
 	github.com/showwin/speedtest-go v1.8.3
 	golang.org/x/crypto v0.54.0

+ 2 - 0
server-go/go.sum

@@ -7,6 +7,8 @@ github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+m
 github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
 github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
 github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/gonzalop/mq v0.9.10 h1:7uaSKq/m/n0ElV3SJtXQTZnI5HyHtgoNIL/ufsxFU+8=
+github.com/gonzalop/mq v0.9.10/go.mod h1:chaGtxnueekistsTKhDnLOoNdJPKEI6vadlUBRQS2ok=
 github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
 github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
 github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=

+ 7 - 0
server-go/internal/config/uci.go

@@ -55,6 +55,13 @@ var uciEnvMap = []struct{ uci, env string }{
 	{"agent_max_ts_drift_s", "AGENT_MAX_TS_DRIFT_S"},
 	{"auto_rearm", "NETPULSE_AUTO_REARM"},
 	{"agent_ttl_s", "NETPULSE_AGENT_TTL_S"},
+	{"mqtt_enabled", "NETPULSE_MQTT_ENABLED"},
+	{"mqtt_host", "NETPULSE_MQTT_HOST"},
+	{"mqtt_port", "NETPULSE_MQTT_PORT"},
+	{"mqtt_user", "NETPULSE_MQTT_USER"},
+	{"mqtt_pass", "NETPULSE_MQTT_PASS"},
+	{"mqtt_instance", "NETPULSE_MQTT_INSTANCE"},
+	{"mqtt_interval", "NETPULSE_MQTT_INTERVAL"},
 }
 
 // LoadUCIEnv lee `uci -q show netpulse` y aplica la sección server al

+ 304 - 0
server-go/internal/mqttpub/mqttpub.go

@@ -0,0 +1,304 @@
+// Package mqttpub publishes the NetPulse fleet state to an MQTT broker with
+// Home Assistant MQTT Discovery (#825).
+//
+// It is opt-in (NETPULSE_MQTT_ENABLED=1 plus a broker host), disabled in demo
+// mode and fail-silent: a broker that is down never affects the server. Only
+// publishing is used, so there is no subscription and no command surface.
+package mqttpub
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"log"
+	"os"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/gonzalop/mq"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+)
+
+const (
+	defaultPort     = 1883
+	defaultInterval = 30 * time.Second
+	initialBackoff  = 5 * time.Second
+	maxBackoff      = 2 * time.Minute
+	publishTimeout  = 10 * time.Second
+)
+
+// Config is the publisher configuration.
+type Config struct {
+	Enabled  bool
+	Host     string
+	Port     int
+	User     string
+	Pass     string
+	Instance string
+	Interval time.Duration
+}
+
+// ConfigFromEnv reads the configuration from the environment. lookup follows
+// the os.LookupEnv shape so it can be injected in tests. Missing values fall
+// back to defaults; an enabled config without a host is disabled.
+func ConfigFromEnv(lookup func(string) (string, bool)) Config {
+	cfg := Config{Port: defaultPort, Interval: defaultInterval, Instance: "default"}
+	if v, ok := lookup("NETPULSE_MQTT_ENABLED"); ok {
+		cfg.Enabled = isTrue(v)
+	}
+	if v, ok := lookup("NETPULSE_MQTT_HOST"); ok {
+		cfg.Host = strings.TrimSpace(v)
+	}
+	if v, ok := lookup("NETPULSE_MQTT_PORT"); ok {
+		if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && n > 0 {
+			cfg.Port = n
+		}
+	}
+	if v, ok := lookup("NETPULSE_MQTT_USER"); ok {
+		cfg.User = strings.TrimSpace(v)
+	}
+	if v, ok := lookup("NETPULSE_MQTT_PASS"); ok {
+		cfg.Pass = v
+	}
+	if v, ok := lookup("NETPULSE_MQTT_INSTANCE"); ok && strings.TrimSpace(v) != "" {
+		cfg.Instance = strings.TrimSpace(v)
+	}
+	if v, ok := lookup("NETPULSE_MQTT_INTERVAL"); ok {
+		if sec, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && sec > 0 {
+			cfg.Interval = time.Duration(sec) * time.Second
+		}
+	}
+	cfg.Instance = sanitize(cfg.Instance)
+	if cfg.Host == "" {
+		cfg.Enabled = false
+	}
+	return cfg
+}
+
+func isTrue(v string) bool {
+	switch strings.ToLower(strings.TrimSpace(v)) {
+	case "1", "true", "on", "yes":
+		return true
+	}
+	return false
+}
+
+// Publisher keeps the broker connection and publishes the state periodically.
+type Publisher struct {
+	cfg      Config
+	version  string
+	snapshot func() *adapters.Overview
+	demo     bool
+
+	seenAlerts  map[string]struct{}
+	seenInit    bool
+	lastRouters string
+}
+
+// New builds a publisher. snapshot returns the latest overview (nil allowed
+// before the first poll).
+func New(cfg Config, version string, snapshot func() *adapters.Overview, demo bool) *Publisher {
+	return &Publisher{
+		cfg:        cfg,
+		version:    version,
+		snapshot:   snapshot,
+		demo:       demo,
+		seenAlerts: map[string]struct{}{},
+	}
+}
+
+// Enabled reports whether the publisher will run.
+func (p *Publisher) Enabled() bool { return p.cfg.Enabled && !p.demo && p.snapshot != nil }
+
+// Start runs the publisher until ctx is cancelled. It is a no-op when not
+// enabled, so callers can start it unconditionally.
+func (p *Publisher) Start(ctx context.Context) {
+	if !p.Enabled() {
+		if p.cfg.Enabled && p.demo {
+			log.Printf("[mqtt] disabled in demo mode")
+		}
+		return
+	}
+	go p.run(ctx)
+}
+
+func (p *Publisher) run(ctx context.Context) {
+	backoff := initialBackoff
+	for {
+		if ctx.Err() != nil {
+			return
+		}
+		client, err := p.dial(ctx)
+		if err != nil {
+			log.Printf("[mqtt] connect to %s:%d failed: %v", p.cfg.Host, p.cfg.Port, err)
+			if !sleepCtx(ctx, backoff) {
+				return
+			}
+			backoff *= 2
+			if backoff > maxBackoff {
+				backoff = maxBackoff
+			}
+			continue
+		}
+		backoff = initialBackoff
+		log.Printf("[mqtt] connected to %s:%d as instance %q", p.cfg.Host, p.cfg.Port, p.cfg.Instance)
+
+		p.publishAvailability(client, "online")
+		p.publishDiscovery(client)
+		p.publishCycle(client)
+
+		p.loop(ctx, client)
+
+		// The retained availability must not stay "online" after an
+		// intentional stop (a graceful DISCONNECT suppresses the will).
+		p.publishAvailability(client, "offline")
+		_ = client.Disconnect(context.Background())
+		return
+	}
+}
+
+func (p *Publisher) dial(ctx context.Context) (*mq.Client, error) {
+	addr := fmt.Sprintf("tcp://%s:%d", p.cfg.Host, p.cfg.Port)
+	opts := []mq.Option{
+		mq.WithProtocolVersion(mq.ProtocolV311),
+		mq.WithClientID("netpulse-" + p.cfg.Instance),
+		mq.WithKeepAlive(60 * time.Second),
+		mq.WithAutoReconnect(true),
+		mq.WithReconnectBackoff(2*time.Second, maxBackoff, true),
+		mq.WithConnectTimeout(15 * time.Second),
+		mq.WithWill(availabilityTopic(p.cfg.Instance), []byte("offline"), 1, true),
+		mq.WithOnConnect(func(c *mq.Client) {
+			// Fires on the initial connect and on every reconnect.
+			p.publishAvailability(c, "online")
+			p.publishDiscovery(c)
+			p.publishCycle(c)
+		}),
+		mq.WithOnConnectionLost(func(_ *mq.Client, err error) {
+			log.Printf("[mqtt] connection lost: %v", err)
+		}),
+	}
+	if p.cfg.User != "" {
+		opts = append(opts, mq.WithCredentials(p.cfg.User, p.cfg.Pass))
+	}
+	dctx, cancel := context.WithTimeout(ctx, 15*time.Second)
+	defer cancel()
+	return mq.DialContext(dctx, addr, opts...)
+}
+
+// loop publishes on the configured interval until ctx ends.
+func (p *Publisher) loop(ctx context.Context, client *mq.Client) {
+	interval := p.cfg.Interval
+	if interval <= 0 {
+		interval = defaultInterval
+	}
+	t := time.NewTicker(interval)
+	defer t.Stop()
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		case <-t.C:
+			if client.IsConnected() {
+				p.publishCycle(client)
+			}
+		}
+	}
+}
+
+// publishCycle publishes the instance status, every router state and any new
+// alert. It also republishes discovery when the set of routers changes.
+func (p *Publisher) publishCycle(client *mq.Client) {
+	ov := p.snapshot()
+	if ov == nil {
+		return
+	}
+	p.publishStatus(client, ov)
+	p.publishRouters(client, ov)
+	p.publishNewAlerts(client, ov)
+
+	key := routerSetKey(ov)
+	if key != p.lastRouters {
+		p.lastRouters = key
+		p.publishDiscovery(client)
+	}
+}
+
+// publishNewAlerts emits an event per unseen alert. The first overview only
+// seeds the set, so a fresh server start does not replay the whole backlog.
+func (p *Publisher) publishNewAlerts(client *mq.Client, ov *adapters.Overview) {
+	if !p.seenInit {
+		for _, a := range ov.Alerts {
+			if a.ID != "" {
+				p.seenAlerts[a.ID] = struct{}{}
+			}
+		}
+		p.seenInit = true
+		return
+	}
+	for _, a := range ov.Alerts {
+		if a.ID == "" {
+			continue
+		}
+		if _, ok := p.seenAlerts[a.ID]; ok {
+			continue
+		}
+		p.seenAlerts[a.ID] = struct{}{}
+		payload, err := json.Marshal(alertEvent{
+			ID: a.ID, Severity: a.Severity, Title: a.Title, Description: a.Description,
+			RouterID: a.RouterID, Urgent: a.Urgent, Ts: a.Ts,
+		})
+		if err != nil {
+			continue
+		}
+		publish(client, eventTopic(p.cfg.Instance, "alert"), payload, false)
+	}
+}
+
+func (p *Publisher) publishAvailability(client *mq.Client, value string) {
+	publish(client, availabilityTopic(p.cfg.Instance), []byte(value), true)
+}
+
+// publish sends one payload at QoS 1 (retained when retain is true).
+func publish(client *mq.Client, topic string, payload []byte, retain bool) {
+	if !client.IsConnected() {
+		return
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), publishTimeout)
+	defer cancel()
+	opts := []mq.PublishOption{mq.WithQoS(mq.AtLeastOnce)}
+	if retain {
+		opts = append(opts, mq.WithRetain(true))
+	}
+	if err := client.Publish(ctx, topic, payload, opts...).Wait(ctx); err != nil {
+		log.Printf("[mqtt] publish %s: %v", topic, err)
+	}
+}
+
+// sanitize makes a string safe for use as an MQTT topic level.
+func sanitize(s string) string {
+	s = strings.TrimSpace(s)
+	if s == "" {
+		return "default"
+	}
+	return strings.NewReplacer("/", "-", "+", "-", "#", "-", " ", "-").Replace(s)
+}
+
+// sleepCtx sleeps for d, returning false when ctx ends first.
+func sleepCtx(ctx context.Context, d time.Duration) bool {
+	t := time.NewTimer(d)
+	defer t.Stop()
+	select {
+	case <-ctx.Done():
+		return false
+	case <-t.C:
+		return true
+	}
+}
+
+// envLookup is the production lookup (os.LookupEnv), used by main.
+func envLookup(k string) (string, bool) { return os.LookupEnv(k) }
+
+// ConfigFromProcessEnv reads the configuration from the process environment.
+func ConfigFromProcessEnv() Config { return ConfigFromEnv(envLookup) }

+ 297 - 0
server-go/internal/mqttpub/mqttpub_ha.go

@@ -0,0 +1,297 @@
+// mqttpub_ha.go: state payloads and Home Assistant MQTT Discovery for the
+// NetPulse publisher (#825). The builders are pure so they can be tested
+// without a broker.
+package mqttpub
+
+import (
+	"encoding/json"
+	"log"
+	"sort"
+	"strings"
+	"time"
+
+	"github.com/gonzalop/mq"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+)
+
+// statusState is the JSON published (retained) on netpulse/<instance>/status.
+type statusState struct {
+	Instance      string `json:"instance"`
+	Version       string `json:"version"`
+	HealthScore   int    `json:"health_score"`
+	HealthLabel   string `json:"health_label"`
+	ClientsOnline int    `json:"clients_online"`
+	ClientsTotal  int    `json:"clients_total"`
+	RoutersOnline int    `json:"routers_online"`
+	RoutersTotal  int    `json:"routers_total"`
+	UnreadAlerts  int    `json:"unread_alerts"`
+	Plan          string `json:"plan,omitempty"`
+	Ts            int64  `json:"ts"`
+}
+
+// routerState is the JSON published (retained) per router.
+type routerState struct {
+	Slug    string `json:"slug"`
+	Name    string `json:"name"`
+	Model   string `json:"model,omitempty"`
+	Status  string `json:"status"`
+	Health  int    `json:"health"`
+	CPU     *int   `json:"cpu"`
+	RAM     *int   `json:"ram"`
+	Temp    *int   `json:"temp"`
+	Clients int    `json:"clients"`
+	Uptime  string `json:"uptime,omitempty"`
+	Ts      int64  `json:"ts"`
+}
+
+// alertEvent is published (not retained) on netpulse/<instance>/event/alert.
+type alertEvent struct {
+	ID          string `json:"id"`
+	Severity    string `json:"severity"`
+	Title       string `json:"title"`
+	Description string `json:"description,omitempty"`
+	RouterID    string `json:"router_id,omitempty"`
+	Urgent      bool   `json:"urgent"`
+	Ts          int64  `json:"ts"`
+}
+
+func availabilityTopic(instance string) string {
+	return "netpulse/" + instance + "/availability"
+}
+
+func statusTopic(instance string) string {
+	return "netpulse/" + instance + "/status"
+}
+
+func routerStateTopic(instance, slug string) string {
+	return "netpulse/" + instance + "/router/" + slug + "/state"
+}
+
+func eventTopic(instance, kind string) string {
+	return "netpulse/" + instance + "/event/" + kind
+}
+
+// routerSlug is the stable per-router identifier used in topics and discovery.
+func routerSlug(r adapters.Router) string {
+	s := sanitize(r.ID)
+	if s == "default" && r.Name != "" {
+		s = sanitize(r.Name)
+	}
+	return s
+}
+
+func buildStatus(instance, version string, ov *adapters.Overview) statusState {
+	st := statusState{
+		Instance:      instance,
+		Version:       version,
+		HealthScore:   ov.Health.Score,
+		HealthLabel:   ov.Health.Label,
+		ClientsOnline: ov.DeviceTotals.Online,
+		ClientsTotal:  ov.DeviceTotals.Total,
+		UnreadAlerts:  ov.UnreadAlerts,
+		Ts:            time.Now().Unix(),
+	}
+	if ov.WAN.Plan != "" {
+		st.Plan = ov.WAN.Plan
+	}
+	for _, r := range ov.Routers {
+		st.RoutersTotal++
+		if r.Status == "online" || r.Status == "warn" {
+			st.RoutersOnline++
+		}
+	}
+	return st
+}
+
+func buildRouterState(r adapters.Router) routerState {
+	return routerState{
+		Slug:    routerSlug(r),
+		Name:    r.Name,
+		Model:   r.Model,
+		Status:  r.Status,
+		Health:  r.Health,
+		CPU:     r.CPU,
+		RAM:     r.RAM,
+		Temp:    r.Temp,
+		Clients: r.Clients,
+		Uptime:  r.Uptime,
+		Ts:      time.Now().Unix(),
+	}
+}
+
+// routerSetKey is a stable key of the current router set, used to detect when
+// discovery must be republished.
+func routerSetKey(ov *adapters.Overview) string {
+	slugs := make([]string, 0, len(ov.Routers))
+	for _, r := range ov.Routers {
+		slugs = append(slugs, routerSlug(r))
+	}
+	sort.Strings(slugs)
+	return strings.Join(slugs, ",")
+}
+
+func (p *Publisher) publishStatus(client *mq.Client, ov *adapters.Overview) {
+	payload, err := json.Marshal(buildStatus(p.cfg.Instance, p.version, ov))
+	if err != nil {
+		log.Printf("[mqtt] marshal status: %v", err)
+		return
+	}
+	publish(client, statusTopic(p.cfg.Instance), payload, true)
+}
+
+func (p *Publisher) publishRouters(client *mq.Client, ov *adapters.Overview) {
+	for _, r := range ov.Routers {
+		payload, err := json.Marshal(buildRouterState(r))
+		if err != nil {
+			log.Printf("[mqtt] marshal router %s: %v", r.ID, err)
+			continue
+		}
+		publish(client, routerStateTopic(p.cfg.Instance, routerSlug(r)), payload, true)
+	}
+}
+
+// haEntity is one Home Assistant discovery entry.
+type haEntity struct {
+	component string
+	nodeID    string
+	objectID  string
+	config    map[string]any
+}
+
+// publishDiscovery publishes the retained discovery configs for the instance
+// and every router.
+func (p *Publisher) publishDiscovery(client *mq.Client) {
+	ov := p.snapshot()
+	if ov == nil {
+		return
+	}
+	for _, e := range haEntities(p.cfg.Instance, p.version, ov) {
+		payload, err := json.Marshal(e.config)
+		if err != nil {
+			log.Printf("[mqtt] marshal discovery %s: %v", e.objectID, err)
+			continue
+		}
+		topic := "homeassistant/" + e.component + "/" + e.nodeID + "/" + e.objectID + "/config"
+		publish(client, topic, payload, true)
+	}
+}
+
+// haEntities builds the discovery entries: instance-level sensors plus one
+// device per router. Pure, so it is covered by unit tests.
+func haEntities(instance, version string, ov *adapters.Overview) []haEntity {
+	avail := map[string]any{
+		"availability_topic":    availabilityTopic(instance),
+		"payload_available":     "online",
+		"payload_not_available": "offline",
+	}
+	base := func(nodeID string, device map[string]any, component, objectID string, extra map[string]any) haEntity {
+		cfg := map[string]any{
+			"unique_id": nodeID + "_" + objectID,
+			"object_id": nodeID + "_" + objectID,
+			"device":    device,
+		}
+		for k, v := range avail {
+			cfg[k] = v
+		}
+		for k, v := range extra {
+			cfg[k] = v
+		}
+		return haEntity{component: component, nodeID: nodeID, objectID: objectID, config: cfg}
+	}
+
+	instNode := "netpulse_" + instance
+	instDevice := map[string]any{
+		"identifiers":  []string{instNode},
+		"name":         "NetPulse " + instance,
+		"manufacturer": "NetPulse",
+		"sw_version":   version,
+	}
+	status := statusTopic(instance)
+	jsonVal := func(field string) string { return "{{ value_json." + field + " }}" }
+
+	entities := []haEntity{
+		base(instNode, instDevice, "sensor", "health_score", map[string]any{
+			"name": "Health score", "state_topic": status,
+			"value_template": jsonVal("health_score"), "state_class": "measurement",
+			"icon": "mdi:heart-pulse",
+		}),
+		base(instNode, instDevice, "sensor", "clients_online", map[string]any{
+			"name": "Clients online", "state_topic": status,
+			"value_template": jsonVal("clients_online"), "state_class": "measurement",
+			"icon": "mdi:account-network",
+		}),
+		base(instNode, instDevice, "sensor", "routers_online", map[string]any{
+			"name": "Routers online", "state_topic": status,
+			"value_template": jsonVal("routers_online"), "state_class": "measurement",
+			"icon": "mdi:router-network",
+		}),
+		base(instNode, instDevice, "sensor", "unread_alerts", map[string]any{
+			"name": "Unread alerts", "state_topic": status,
+			"value_template": jsonVal("unread_alerts"), "state_class": "measurement",
+			"icon": "mdi:bell-alert",
+		}),
+		base(instNode, instDevice, "sensor", "version", map[string]any{
+			"name": "NetPulse version", "state_topic": status,
+			"value_template": jsonVal("version"),
+			"icon":           "mdi:information-outline", "entity_category": "diagnostic",
+		}),
+	}
+
+	for _, r := range ov.Routers {
+		slug := routerSlug(r)
+		node := instNode + "_" + slug
+		name := r.Name
+		if name == "" {
+			name = slug
+		}
+		dev := map[string]any{
+			"identifiers":  []string{node},
+			"name":         name,
+			"manufacturer": "NetPulse",
+			"via_device":   instNode,
+		}
+		if r.Model != "" {
+			dev["model"] = r.Model
+		}
+		state := routerStateTopic(instance, slug)
+
+		entities = append(entities,
+			base(node, dev, "binary_sensor", "online", map[string]any{
+				"name": "Online", "state_topic": state,
+				"value_template": "{{ 'ON' if value_json.status in ['online', 'warn'] else 'OFF' }}",
+				"device_class":   "connectivity",
+				"payload_on":     "ON",
+				"payload_off":    "OFF",
+			}),
+			base(node, dev, "sensor", "health", map[string]any{
+				"name": "Health", "state_topic": state,
+				"value_template": jsonVal("health"), "state_class": "measurement",
+				"icon": "mdi:heart-pulse",
+			}),
+			base(node, dev, "sensor", "cpu_usage", map[string]any{
+				"name": "CPU usage", "state_topic": state,
+				"value_template": jsonVal("cpu"), "unit_of_measurement": "%",
+				"state_class": "measurement", "icon": "mdi:speedometer",
+				"entity_category": "diagnostic",
+			}),
+			base(node, dev, "sensor", "memory_usage", map[string]any{
+				"name": "Memory usage", "state_topic": state,
+				"value_template": jsonVal("ram"), "unit_of_measurement": "%",
+				"state_class": "measurement", "icon": "mdi:memory",
+				"entity_category": "diagnostic",
+			}),
+			base(node, dev, "sensor", "temperature", map[string]any{
+				"name": "Temperature", "state_topic": state,
+				"value_template": jsonVal("temp"), "unit_of_measurement": "°C",
+				"device_class": "temperature", "state_class": "measurement",
+			}),
+			base(node, dev, "sensor", "clients", map[string]any{
+				"name": "Clients", "state_topic": state,
+				"value_template": jsonVal("clients"), "state_class": "measurement",
+				"icon": "mdi:account-network", "entity_category": "diagnostic",
+			}),
+		)
+	}
+	return entities
+}

+ 161 - 0
server-go/internal/mqttpub/mqttpub_test.go

@@ -0,0 +1,161 @@
+package mqttpub
+
+import (
+	"context"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+)
+
+func lookupFrom(m map[string]string) func(string) (string, bool) {
+	return func(k string) (string, bool) {
+		v, ok := m[k]
+		return v, ok
+	}
+}
+
+func TestConfigFromEnv(t *testing.T) {
+	// Disabled by default.
+	if cfg := ConfigFromEnv(lookupFrom(nil)); cfg.Enabled {
+		t.Fatal("config must be disabled by default")
+	}
+
+	// Enabled without host stays disabled.
+	cfg := ConfigFromEnv(lookupFrom(map[string]string{"NETPULSE_MQTT_ENABLED": "1"}))
+	if cfg.Enabled {
+		t.Fatal("enabled without a host must be disabled")
+	}
+
+	// Full config.
+	cfg = ConfigFromEnv(lookupFrom(map[string]string{
+		"NETPULSE_MQTT_ENABLED":  "true",
+		"NETPULSE_MQTT_HOST":     "broker.local",
+		"NETPULSE_MQTT_PORT":     "1884",
+		"NETPULSE_MQTT_USER":     "netpulse",
+		"NETPULSE_MQTT_PASS":     "s3cret",
+		"NETPULSE_MQTT_INSTANCE": "home",
+		"NETPULSE_MQTT_INTERVAL": "15",
+	}))
+	if !cfg.Enabled || cfg.Host != "broker.local" || cfg.Port != 1884 ||
+		cfg.User != "netpulse" || cfg.Pass != "s3cret" || cfg.Instance != "home" {
+		t.Fatalf("unexpected config: %+v", cfg)
+	}
+	if cfg.Interval.Seconds() != 15 {
+		t.Fatalf("interval = %v, want 15s", cfg.Interval)
+	}
+
+	// Instance is sanitized for MQTT topics.
+	cfg = ConfigFromEnv(lookupFrom(map[string]string{
+		"NETPULSE_MQTT_ENABLED":  "1",
+		"NETPULSE_MQTT_HOST":     "b",
+		"NETPULSE_MQTT_INSTANCE": "home/#1",
+	}))
+	if cfg.Instance != "home--1" {
+		t.Fatalf("instance = %q, want home--1", cfg.Instance)
+	}
+}
+
+func sampleOverview() *adapters.Overview {
+	cpu, ram, temp := 12, 40, 55
+	return &adapters.Overview{
+		Health:       adapters.HealthScore{Score: 92, Label: "Excelente"},
+		DeviceTotals: adapters.DeviceTotals{Total: 30, Online: 27},
+		UnreadAlerts: 2,
+		WAN:          adapters.WAN{Plan: "600/600"},
+		Routers: []adapters.Router{
+			{ID: "gw", Name: "Gateway", Model: "MT6000", Status: "online", Health: 100,
+				CPU: &cpu, RAM: &ram, Temp: &temp, Clients: 18, Uptime: "3d 4h"},
+			{ID: "ap-1", Name: "AP 1", Status: "offline", Health: 0},
+		},
+		Alerts: []adapters.AlertEvent{{ID: "a1", Severity: "warn", Title: "Temp",
+			RouterID: "gw", Ts: 1000}},
+	}
+}
+
+func TestBuildStatus(t *testing.T) {
+	st := buildStatus("home", "v1.2.3", sampleOverview())
+	if st.HealthScore != 92 || st.ClientsOnline != 27 || st.ClientsTotal != 30 {
+		t.Fatalf("unexpected status: %+v", st)
+	}
+	if st.RoutersOnline != 1 || st.RoutersTotal != 2 {
+		t.Fatalf("router counts = %d/%d, want 1/2", st.RoutersOnline, st.RoutersTotal)
+	}
+	if st.UnreadAlerts != 2 || st.Plan != "600/600" {
+		t.Fatalf("unexpected status: %+v", st)
+	}
+}
+
+func TestBuildRouterState(t *testing.T) {
+	r := sampleOverview().Routers[0]
+	rs := buildRouterState(r)
+	if rs.Slug != "gw" || rs.Status != "online" || rs.Clients != 18 {
+		t.Fatalf("unexpected router state: %+v", rs)
+	}
+	if rs.CPU == nil || *rs.CPU != 12 || rs.Temp == nil || *rs.Temp != 55 {
+		t.Fatalf("vitals not carried over: %+v", rs)
+	}
+}
+
+func TestRouterSlugFallsBackToName(t *testing.T) {
+	if got := routerSlug(adapters.Router{Name: "AP 1"}); got != "AP-1" {
+		t.Fatalf("slug = %q, want AP-1", got)
+	}
+}
+
+func TestRouterSetKeyIsStable(t *testing.T) {
+	ov := sampleOverview()
+	k1 := routerSetKey(ov)
+	// Reorder the routers: the key must not change.
+	ov.Routers[0], ov.Routers[1] = ov.Routers[1], ov.Routers[0]
+	if k2 := routerSetKey(ov); k2 != k1 {
+		t.Fatalf("routerSetKey changed with order: %q vs %q", k1, k2)
+	}
+}
+
+func TestHAEntities(t *testing.T) {
+	ents := haEntities("home", "v1.2.3", sampleOverview())
+	if len(ents) == 0 {
+		t.Fatal("no discovery entities")
+	}
+	seen := map[string]bool{}
+	var instanceEntities, routerEntities int
+	for _, e := range ents {
+		uid, _ := e.config["unique_id"].(string)
+		if uid == "" {
+			t.Fatalf("%s/%s: no unique_id", e.nodeID, e.objectID)
+		}
+		if seen[uid] {
+			t.Fatalf("duplicate unique_id %q", uid)
+		}
+		seen[uid] = true
+		if got, _ := e.config["availability_topic"].(string); got != availabilityTopic("home") {
+			t.Fatalf("%s: availability_topic = %q", uid, got)
+		}
+		if e.nodeID == "netpulse_home" {
+			instanceEntities++
+		} else {
+			routerEntities++
+		}
+	}
+	if instanceEntities == 0 || routerEntities == 0 {
+		t.Fatalf("expected instance and router entities, got %d/%d", instanceEntities, routerEntities)
+	}
+	// The per-router state topic must be the one we publish.
+	for _, e := range ents {
+		if e.nodeID == "netpulse_home_gw" && e.objectID == "cpu_usage" {
+			if got, _ := e.config["state_topic"].(string); got != "netpulse/home/router/gw/state" {
+				t.Fatalf("router state_topic = %q", got)
+			}
+			return
+		}
+	}
+	t.Fatal("no cpu_usage entity for the gw router")
+}
+
+func TestStartIsNoopWhenDisabled(t *testing.T) {
+	p := New(Config{}, "v1", func() *adapters.Overview { return nil }, false)
+	if p.Enabled() {
+		t.Fatal("publisher must be disabled")
+	}
+	p.Start(context.Background()) // must not panic nor block
+}