Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(unifi): add UniFi Network Controller integration

slmingole9e1d3187d7a
diff --git a/backend/app/api/routes/unifi.py b/backend/app/api/routes/unifi.py
new file mode 100644
index 0000000..cdc66f7
--- /dev/null
+++ b/backend/app/api/routes/unifi.py
@@ -0,0 +1,260 @@
+"""FastAPI router for UniFi Network Controller import + auto-sync config."""
+
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+from fastapi import APIRouter, Depends, HTTPException
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.deps import get_current_user
+from app.core.config import settings
+from app.core.scheduler import reschedule_unifi_sync, set_unifi_sync_enabled
+from app.db.database import AsyncSessionLocal, get_db
+from app.db.models import InventoryDevice, ScanRun
+from app.schemas.unifi import (
+ UnifiConfig,
+ UnifiConnectionRequest,
+ UnifiImportResponse,
+ UnifiSyncConfig,
+ UnifiTestConnectionResponse,
+)
+from app.services.discovery_sources import add_source
+from app.services.unifi_service import fetch_unifi_inventory, test_unifi_connection
+
+logger = logging.getLogger(__name__)
+router = APIRouter()
+
+_UNIFI_SOURCE = "unifi"
+
+
+def _resolve_credentials(payload: UnifiConnectionRequest) -> tuple[str, str]:
+ username = payload.username or settings.unifi_username
+ password = payload.password or settings.unifi_password
+ if not username or not password:
+ raise HTTPException(
+ status_code=400,
+ detail="No UniFi credentials provided and none configured on the server.",
+ )
+ return username, password
+
+
[email protected]("/test-connection", response_model=UnifiTestConnectionResponse)
+async def test_connection_endpoint(
+ payload: UnifiConnectionRequest,
+ _: str = Depends(get_current_user),
+) -> UnifiTestConnectionResponse:
+ username, password = _resolve_credentials(payload)
+ connected, message = await test_unifi_connection(
+ host=payload.host,
+ port=payload.port,
+ site=payload.site,
+ username=username,
+ password=password,
+ verify_tls=payload.verify_tls,
+ )
+ return UnifiTestConnectionResponse(connected=connected, message=message)
+
+
[email protected]("/import-pending", response_model=UnifiImportResponse)
+async def import_unifi_pending(
+ payload: UnifiConnectionRequest,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> UnifiImportResponse:
+ """Fetch UniFi inventory and upsert into pending device inventory."""
+ username, password = _resolve_credentials(payload)
+ try:
+ devices = await fetch_unifi_inventory(
+ host=payload.host,
+ port=payload.port,
+ site=payload.site,
+ username=username,
+ password=password,
+ verify_tls=payload.verify_tls,
+ )
+ except ConnectionError as exc:
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
+ except Exception as exc:
+ logger.exception("Unexpected error during UniFi import")
+ raise HTTPException(status_code=500, detail="Unexpected error during UniFi import") from exc
+
+ result = await _persist_devices(db, devices)
+ return result
+
+
[email protected]("/sync-now", response_model=UnifiImportResponse)
+async def sync_unifi_now(
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> UnifiImportResponse:
+ if not (settings.unifi_effective_host and settings.unifi_username and settings.unifi_password):
+ raise HTTPException(
+ status_code=400,
+ detail="Cannot sync: no UniFi host/credentials configured on the server.",
+ )
+ try:
+ devices = await fetch_unifi_inventory(
+ host=settings.unifi_effective_host,
+ port=settings.unifi_effective_port,
+ site=settings.unifi_site,
+ username=settings.unifi_username,
+ password=settings.unifi_password,
+ verify_tls=settings.unifi_verify_tls,
+ )
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
+
+ return await _persist_devices(db, devices)
+
+
[email protected]("/config", response_model=UnifiConfig)
+async def get_unifi_config(_: str = Depends(get_current_user)) -> UnifiConfig:
+ return UnifiConfig(
+ host=settings.unifi_effective_host,
+ port=settings.unifi_effective_port,
+ site=settings.unifi_site,
+ verify_tls=settings.unifi_verify_tls,
+ sync_enabled=settings.unifi_sync_enabled,
+ sync_interval=settings.unifi_sync_interval,
+ credentials_configured=bool(settings.unifi_username and settings.unifi_password),
+ )
+
+
[email protected]("/config", response_model=UnifiConfig)
+async def save_unifi_config(
+ payload: UnifiSyncConfig,
+ _: str = Depends(get_current_user),
+) -> UnifiConfig:
+ if payload.sync_enabled and not (
+ settings.unifi_effective_host and settings.unifi_username and settings.unifi_password
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail="Cannot enable auto-sync: no UniFi host/credentials configured in the server env.",
+ )
+ try:
+ settings.unifi_sync_enabled = payload.sync_enabled
+ settings.unifi_sync_interval = payload.sync_interval
+ settings.save_overrides()
+ set_unifi_sync_enabled(payload.sync_enabled)
+ if payload.sync_enabled:
+ reschedule_unifi_sync(payload.sync_interval)
+ except HTTPException:
+ raise
+ except Exception as exc:
+ raise HTTPException(status_code=500, detail=str(exc)) from exc
+
+ return await get_unifi_config()
+
+
+async def _find_existing(
+ db: AsyncSession, ieee: str, mac: str | None
+) -> InventoryDevice | None:
+ row = (
+ await db.execute(select(InventoryDevice).where(InventoryDevice.ieee_address == ieee))
+ ).scalars().first()
+ if row is not None:
+ return row
+ if mac:
+ row = (
+ await db.execute(
+ select(InventoryDevice).where(
+ InventoryDevice.mac == mac,
+ InventoryDevice.ieee_address.is_(None),
+ )
+ )
+ ).scalars().first()
+ return row
+
+
+async def _persist_devices(
+ db: AsyncSession,
+ devices: list[dict[str, Any]],
+) -> UnifiImportResponse:
+ pending_created = 0
+ pending_updated = 0
+
+ for dev in devices:
+ ieee = dev.get("ieee_address")
+ if not ieee:
+ continue
+ ip = dev.get("ip")
+ mac = dev.get("mac")
+
+ existing = await _find_existing(db, ieee, mac)
+
+ if existing is None:
+ row = InventoryDevice(
+ ieee_address=ieee,
+ ip=ip,
+ mac=mac,
+ hostname=dev.get("hostname"),
+ friendly_name=dev.get("label"),
+ suggested_type=dev.get("type"),
+ vendor=dev.get("vendor"),
+ model=dev.get("model"),
+ properties=dev.get("properties", []),
+ status="pending",
+ discovery_source=_UNIFI_SOURCE,
+ discovery_sources=[_UNIFI_SOURCE],
+ )
+ db.add(row)
+ pending_created += 1
+ else:
+ existing.discovery_sources = add_source(
+ list(existing.discovery_sources or []),
+ _UNIFI_SOURCE,
+ )
+ existing.ieee_address = existing.ieee_address or ieee
+ existing.ip = ip or existing.ip
+ existing.mac = existing.mac or mac
+ existing.hostname = dev.get("hostname") or existing.hostname
+ existing.friendly_name = dev.get("label") or existing.friendly_name
+ existing.suggested_type = dev.get("type") or existing.suggested_type
+ existing.vendor = dev.get("vendor") or existing.vendor
+ existing.model = dev.get("model") or existing.model
+ # Status preserved — an approved device stays approved.
+ # Only reset hidden devices (they came back visible in UniFi).
+ if existing.status == "hidden":
+ existing.status = "pending"
+ pending_updated += 1
+
+ await db.commit()
+ return UnifiImportResponse(
+ device_count=len(devices),
+ pending_created=pending_created,
+ pending_updated=pending_updated,
+ )
+
+
+async def _background_unifi_sync(run_id: str) -> None:
+ async with AsyncSessionLocal() as db:
+ try:
+ devices = await fetch_unifi_inventory(
+ host=settings.unifi_effective_host,
+ port=settings.unifi_effective_port,
+ site=settings.unifi_site,
+ username=settings.unifi_username,
+ password=settings.unifi_password,
+ verify_tls=settings.unifi_verify_tls,
+ )
+ result = await _persist_devices(db, devices)
+ run = await db.get(ScanRun, run_id)
+ if run:
+ run.status = "done"
+ run.devices_found = result.device_count
+ run.finished_at = datetime.now(timezone.utc)
+ await db.commit()
+ from app.api.routes.status import broadcast_scan_update
+ await broadcast_scan_update(run_id=run_id, devices_found=result.device_count)
+ except Exception as exc:
+ logger.exception("UniFi sync %s failed", run_id)
+ await db.rollback()
+ run = await db.get(ScanRun, run_id)
+ if run:
+ run.status = "error"
+ run.error = str(exc)[:500]
+ run.finished_at = datetime.now(timezone.utc)
+ await db.commit()
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index eceb932..eb3e7e8 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -4,7 +4,7 @@ from pathlib import Path
from typing import Literal
from urllib.parse import urlsplit
-from pydantic import Field, model_validator
+from pydantic import AliasChoices, Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
logger = logging.getLogger(__name__)
@@ -253,6 +253,37 @@ class Settings(BaseSettings):
# (the Z-Wave node dump today). Same rationale as the Zigbee twin above.
mqtt_response_timeout: int = 300
+ # UniFi Network Controller import.
+ # Credentials are secrets → env/.env ONLY, never persisted.
+ # Accepts UNIFI_USER or UNIFI_USERNAME; UNIFI_PASS or UNIFI_PASSWORD.
+ unifi_username: str = Field("", alias="unifi_user", validation_alias=AliasChoices("unifi_username", "unifi_user"))
+ unifi_password: str = Field("", alias="unifi_pass", validation_alias=AliasChoices("unifi_password", "unifi_pass"))
+ # Non-secret connection + auto-sync config (persisted via save_overrides).
+ # Accepts UNIFI_URL (full URL) or UNIFI_HOST (bare host/IP).
+ unifi_url: str = ""
+ unifi_host: str = ""
+ unifi_port: int = 8443
+ unifi_site: str = "default"
+ unifi_verify_tls: bool = False
+ unifi_sync_enabled: bool = False
+ unifi_sync_interval: int = 3600
+
+ @property
+ def unifi_effective_host(self) -> str:
+ """Return bare host extracted from UNIFI_URL, or UNIFI_HOST."""
+ if self.unifi_url:
+ parsed = urlsplit(self.unifi_url)
+ return parsed.hostname or self.unifi_url
+ return self.unifi_host
+
+ @property
+ def unifi_effective_port(self) -> int:
+ """Return port from UNIFI_URL if set, else UNIFI_PORT."""
+ if self.unifi_url:
+ parsed = urlsplit(self.unifi_url)
+ return parsed.port or self.unifi_port
+ return self.unifi_port
+
def _override_path(self) -> Path:
return Path(self.sqlite_path).parent / "scan_config.json"
@@ -300,6 +331,18 @@ class Settings(BaseSettings):
self.zwave_sync_enabled = bool(data["zwave_sync_enabled"])
if "zwave_sync_interval" in data:
self.zwave_sync_interval = int(data["zwave_sync_interval"])
+ if "unifi_sync_enabled" in data:
+ self.unifi_sync_enabled = bool(data["unifi_sync_enabled"])
+ if "unifi_sync_interval" in data:
+ self.unifi_sync_interval = int(data["unifi_sync_interval"])
+ if "unifi_host" in data:
+ self.unifi_host = str(data["unifi_host"])
+ if "unifi_port" in data:
+ self.unifi_port = int(data["unifi_port"])
+ if "unifi_site" in data:
+ self.unifi_site = str(data["unifi_site"])
+ if "unifi_verify_tls" in data:
+ self.unifi_verify_tls = bool(data["unifi_verify_tls"])
except Exception:
pass
@@ -325,6 +368,14 @@ class Settings(BaseSettings):
"zigbee_sync_interval": self.zigbee_sync_interval,
"zwave_sync_enabled": self.zwave_sync_enabled,
"zwave_sync_interval": self.zwave_sync_interval,
+ # UniFi: non-secret connection config + auto-sync activation persisted.
+ # Credentials (username/password) are env-only and never written here.
+ "unifi_sync_enabled": self.unifi_sync_enabled,
+ "unifi_sync_interval": self.unifi_sync_interval,
+ "unifi_host": self.unifi_host,
+ "unifi_port": self.unifi_port,
+ "unifi_site": self.unifi_site,
+ "unifi_verify_tls": self.unifi_verify_tls,
}))
diff --git a/backend/app/core/scheduler.py b/backend/app/core/scheduler.py
index e2d317a..68969b5 100644
--- a/backend/app/core/scheduler.py
+++ b/backend/app/core/scheduler.py
@@ -244,6 +244,30 @@ async def _run_zwave_sync() -> None:
await _run_mesh_sync("zwave")
+async def _run_unifi_sync() -> None:
+ """Fetch the UniFi inventory and upsert it into pending (auto-sync)."""
+ if not settings.unifi_sync_enabled:
+ return
+ if not (settings.unifi_effective_host and settings.unifi_username and settings.unifi_password):
+ logger.warning("UniFi auto-sync enabled but host/credentials not configured — skipping")
+ return
+ from app.api.routes.unifi import _background_unifi_sync
+ from app.db.models import ScanRun
+
+ async with AsyncSessionLocal() as db:
+ run = ScanRun(
+ status="running",
+ kind="unifi",
+ ranges=[f"{settings.unifi_effective_host}:{settings.unifi_effective_port}"],
+ )
+ db.add(run)
+ await db.commit()
+ await db.refresh(run)
+ run_id = run.id
+
+ await _background_unifi_sync(run_id)
+
+
def _add_service_check_job() -> None:
scheduler.add_job(
_run_service_checks,
@@ -288,6 +312,17 @@ def _add_zwave_sync_job() -> None:
)
+def _add_unifi_sync_job() -> None:
+ scheduler.add_job(
+ _run_unifi_sync,
+ "interval",
+ seconds=settings.unifi_sync_interval,
+ id="unifi_sync",
+ max_instances=1,
+ coalesce=True,
+ )
+
+
def start_scheduler() -> None:
global scheduler
if scheduler.running:
@@ -312,6 +347,8 @@ def start_scheduler() -> None:
_add_zigbee_sync_job()
if settings.zwave_sync_enabled:
_add_zwave_sync_job()
+ if settings.unifi_sync_enabled:
+ _add_unifi_sync_job()
scheduler.start()
logger.info("Scheduler started — status checks every %ds", settings.status_checker_interval)
@@ -427,6 +464,29 @@ def set_zwave_sync_enabled(enabled: bool) -> None:
logger.info("Z-Wave auto-sync disabled")
+def reschedule_unifi_sync(interval_seconds: int) -> None:
+ if interval_seconds < 300:
+ raise ValueError(f"interval_seconds must be >= 300, got {interval_seconds}")
+ if not scheduler.running:
+ logger.warning("Scheduler not running, skipping reschedule")
+ return
+ if scheduler.get_job("unifi_sync"):
+ scheduler.reschedule_job("unifi_sync", trigger="interval", seconds=interval_seconds)
+ logger.info("UniFi auto-sync rescheduled to every %ds", interval_seconds)
+
+
+def set_unifi_sync_enabled(enabled: bool) -> None:
+ if not scheduler.running:
+ return
+ job = scheduler.get_job("unifi_sync")
+ if enabled and not job:
+ _add_unifi_sync_job()
+ logger.info("UniFi auto-sync enabled — every %ds", settings.unifi_sync_interval)
+ elif not enabled and job:
+ scheduler.remove_job("unifi_sync")
+ logger.info("UniFi auto-sync disabled")
+
+
def stop_scheduler() -> None:
if scheduler.running:
scheduler.shutdown(wait=False)
diff --git a/backend/app/main.py b/backend/app/main.py
index cbe2499..70d16d1 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -23,6 +23,7 @@ from app.api.routes import (
scan,
stats,
status,
+ unifi,
zigbee,
zwave,
)
@@ -97,6 +98,7 @@ app.include_router(liveview.router, prefix="/api/v1/liveview", tags=["liveview"]
app.include_router(zigbee.router, prefix="/api/v1/zigbee", tags=["zigbee"])
app.include_router(zwave.router, prefix="/api/v1/zwave", tags=["zwave"])
app.include_router(proxmox.router, prefix="/api/v1/proxmox", tags=["proxmox"])
+app.include_router(unifi.router, prefix="/api/v1/unifi", tags=["unifi"])
app.include_router(stats.router, prefix="/api/v1/stats", tags=["stats"])
app.include_router(media.router, prefix="/api/v1/media", tags=["media"])
app.include_router(documents.router, prefix="/api/v1/documents", tags=["documents"])
diff --git a/backend/app/schemas/unifi.py b/backend/app/schemas/unifi.py
new file mode 100644
index 0000000..f1d0265
--- /dev/null
+++ b/backend/app/schemas/unifi.py
@@ -0,0 +1,50 @@
+"""Pydantic v2 schemas for UniFi Network Controller import."""
+
+from pydantic import BaseModel, Field
+
+
+class UnifiConnectionRequest(BaseModel):
+ host: str = Field(..., description="UniFi controller host or IP")
+ port: int = Field(8443, ge=1, le=65535, description="Controller port (8443 legacy, 443 UDM)")
+ site: str = Field("default", description="UniFi site name")
+ username: str | None = Field(None, description="Controller username (falls back to server env)")
+ password: str | None = Field(None, description="Controller password (falls back to server env)")
+ verify_tls: bool = Field(False, description="Verify TLS certificate (usually false for local controllers)")
+
+
+class UnifiTestConnectionResponse(BaseModel):
+ connected: bool
+ message: str
+
+
+class UnifiDeviceOut(BaseModel):
+ ieee_address: str
+ mac: str | None = None
+ ip: str | None = None
+ hostname: str | None = None
+ label: str | None = None
+ type: str
+ vendor: str | None = None
+ model: str | None = None
+ raw_type: str | None = None
+
+
+class UnifiImportResponse(BaseModel):
+ device_count: int
+ pending_created: int
+ pending_updated: int
+
+
+class UnifiConfig(BaseModel):
+ host: str
+ port: int
+ site: str
+ verify_tls: bool
+ sync_enabled: bool
+ sync_interval: int
+ credentials_configured: bool
+
+
+class UnifiSyncConfig(BaseModel):
+ sync_enabled: bool
+ sync_interval: int = Field(3600, ge=300)
diff --git a/backend/app/services/unifi_service.py b/backend/app/services/unifi_service.py
new file mode 100644
index 0000000..99156a1
--- /dev/null
+++ b/backend/app/services/unifi_service.py
@@ -0,0 +1,290 @@
+"""UniFi Network Controller REST API client.
+
+Cookie-based auth: POST /api/login, then /api/s/<site>/stat/device.
+Supports both legacy UniFi Controller (port 8443) and UniFi OS (port 443).
+"""
+import contextlib
+import logging
+from typing import Any
+
+import httpx
+
+logger = logging.getLogger(__name__)
+
+# Map UniFi device type codes to homelable node types
+_TYPE_MAP: dict[str, str] = {
+ "ugw": "router", # UniFi Security Gateway
+ "udm": "router", # UniFi Dream Machine / Dream Router
+ "usg": "router",
+ "usw": "switch", # UniFi Switch
+ "uap": "ap", # UniFi Access Point
+ "uxg": "router", # UniFi Express Gateway
+}
+
+
+async def test_unifi_connection(
+ host: str,
+ port: int,
+ site: str,
+ username: str,
+ password: str,
+ verify_tls: bool = False,
+) -> tuple[bool, str]:
+ """Test UniFi controller reachability and credentials."""
+ try:
+ client = httpx.AsyncClient(verify=verify_tls, timeout=10.0)
+ try:
+ cookies = await _login(client, host, port, username, password)
+ if not cookies:
+ return False, "Login failed: invalid credentials or unreachable host"
+ devices = await _fetch_devices(client, host, port, site, cookies)
+ return True, f"Connected — {len(devices)} device(s) found in site '{site}'"
+ finally:
+ await client.aclose()
+ except httpx.ConnectError as exc:
+ return False, f"Cannot reach {host}:{port} — {exc}"
+ except Exception as exc:
+ return False, str(exc)
+
+
+async def fetch_unifi_inventory(
+ host: str,
+ port: int,
+ site: str,
+ username: str,
+ password: str,
+ verify_tls: bool = False,
+) -> list[dict[str, Any]]:
+ """Fetch all devices from the UniFi controller and return normalized dicts."""
+ client = httpx.AsyncClient(verify=verify_tls, timeout=15.0)
+ try:
+ cookies = await _login(client, host, port, username, password)
+ if not cookies:
+ raise ConnectionError("UniFi login failed: invalid credentials or unreachable host")
+ raw = await _fetch_devices(client, host, port, site, cookies)
+ return [_normalize(d) for d in raw]
+ finally:
+ await client.aclose()
+
+
+async def _login(
+ client: httpx.AsyncClient,
+ host: str,
+ port: int,
+ username: str,
+ password: str,
+) -> dict[str, str] | None:
+ """Try both UniFi OS and legacy controller login paths."""
+ base = f"https://{host}:{port}"
+ payload = {"username": username, "password": password}
+
+ # UniFi OS (Dream Machine series) uses /api/auth/login
+ for path in ["/api/auth/login", "/api/login"]:
+ try:
+ r = await client.post(f"{base}{path}", json=payload, follow_redirects=True)
+ if r.status_code in (200, 201):
+ return dict(r.cookies)
+ except Exception:
+ continue
+ return None
+
+
+async def _fetch_devices(
+ client: httpx.AsyncClient,
+ host: str,
+ port: int,
+ site: str,
+ cookies: dict[str, str],
+) -> list[dict[str, Any]]:
+ base = f"https://{host}:{port}"
+ headers = {}
+ # UniFi OS requires X-CSRF-Token header
+ if "csrf_token" in cookies:
+ headers["X-CSRF-Token"] = cookies["csrf_token"]
+
+ # Try UniFi OS proxy path first, then legacy path
+ for path in [
+ f"/proxy/network/api/s/{site}/stat/device",
+ f"/api/s/{site}/stat/device",
+ ]:
+ try:
+ r = await client.get(
+ f"{base}{path}",
+ cookies=cookies,
+ headers=headers,
+ follow_redirects=True,
+ )
+ if r.status_code == 200:
+ data = r.json()
+ devices: list[dict[str, Any]] = data.get("data", [])
+ return devices
+ except Exception:
+ continue
+ return []
+
+
+async def fetch_unifi_topology(
+ host: str,
+ port: int,
+ site: str,
+ username: str,
+ password: str,
+ verify_tls: bool = False,
+) -> dict[str, Any]:
+ """Return UniFi topology: LLDP edges between infra, client uplinks, infra MAC map."""
+ empty: dict[str, Any] = {
+ "lldp_edges": [], "client_uplinks": {}, "infra_macs": {}, "device_uplinks": {}, "stp_priorities": {}
+ }
+ client = httpx.AsyncClient(verify=verify_tls, timeout=15.0)
+ try:
+ cookies = await _login(client, host, port, username, password)
+ if not cookies:
+ return empty
+
+ infra_devices = await _fetch_devices(client, host, port, site, cookies)
+ clients = await _fetch_clients(client, host, port, site, cookies)
+
+ lldp_edges: list[tuple[str, str]] = []
+ infra_macs: dict[str, dict[str, str]] = {}
+
+ # device_uplinks: maps a UniFi device MAC → its uplink device MAC.
+ # When the uplink resolves to a known device, BFS can route correctly.
+ # When it doesn't (e.g. uplink is the router), the device is a core switch
+ # that should be wired directly to the BFS root.
+ device_uplinks: dict[str, str] = {}
+ # Maps device MAC → STP bridge priority (lower = closer to root bridge).
+ # UniFi exposes this as stp_priority at the top level of each switch device.
+ stp_priorities: dict[str, int] = {}
+
+ for device in infra_devices:
+ dev_mac = (device.get("mac") or "").lower()
+ raw_type = (device.get("type") or "").lower()
+ node_type = _TYPE_MAP.get(raw_type, "device")
+ name = device.get("name") or device.get("hostname") or dev_mac
+ if dev_mac:
+ infra_macs[dev_mac] = {"type": node_type, "name": name}
+ for neighbor in (device.get("lldp_table") or []):
+ neighbor_mac = (
+ neighbor.get("chassis_id") or neighbor.get("lldp_chassis_id") or ""
+ ).lower()
+ if dev_mac and neighbor_mac and dev_mac != neighbor_mac:
+ lldp_edges.append((dev_mac, neighbor_mac))
+ # Uplink field — present on switches/APs managed by UniFi.
+ # The uplink dict uses "mac" for the upstream device MAC (not "uplink_mac").
+ uplink = device.get("uplink") or {}
+ uplink_mac = (uplink.get("mac") or uplink.get("uplink_mac") or "").lower()
+ if dev_mac and uplink_mac and uplink_mac != dev_mac:
+ device_uplinks[dev_mac] = uplink_mac
+ # STP bridge priority — lowest value = root bridge. UniFi stores this
+ # as stp_priority on the switch device. Only meaningful for switches.
+ if raw_type.startswith("usw"):
+ stp_val = device.get("stp_priority")
+ if stp_val is None:
+ # Also try nested locations some firmware versions use
+ stp_val = (device.get("config") or {}).get("stp_priority")
+ if stp_val is not None:
+ with contextlib.suppress(ValueError, TypeError):
+ stp_priorities[dev_mac] = int(stp_val)
+
+ logger.info(
+ "unifi_topology: device_uplinks (%d entries): %s",
+ len(device_uplinks),
+ {infra_macs.get(k, {}).get("name", k): v for k, v in device_uplinks.items()},
+ )
+ logger.info(
+ "unifi_topology: stp_priorities (%d entries): %s",
+ len(stp_priorities),
+ {infra_macs.get(k, {}).get("name", k): v for k, v in sorted(stp_priorities.items(), key=lambda x: x[1])},
+ )
+
+ client_uplinks: dict[str, str] = {}
+ for sta in clients:
+ sta_mac = (sta.get("mac") or "").lower()
+ if not sta_mac:
+ continue
+ uplink = (sta.get("ap_mac") or sta.get("sw_mac") or "").lower()
+ if uplink:
+ client_uplinks[sta_mac] = uplink
+
+ return {
+ "lldp_edges": lldp_edges,
+ "client_uplinks": client_uplinks,
+ "infra_macs": infra_macs,
+ "device_uplinks": device_uplinks,
+ "stp_priorities": stp_priorities,
+ }
+ except Exception as exc:
+ logger.warning("UniFi topology fetch failed: %s", exc)
+ return empty
+ finally:
+ await client.aclose()
+
+
+async def _fetch_clients(
+ client: httpx.AsyncClient,
+ host: str,
+ port: int,
+ site: str,
+ cookies: dict[str, str],
+) -> list[dict[str, Any]]:
+ """Fetch connected client stations from the UniFi controller."""
+ base = f"https://{host}:{port}"
+ headers = {}
+ if "csrf_token" in cookies:
+ headers["X-CSRF-Token"] = cookies["csrf_token"]
+
+ for path in [
+ f"/proxy/network/api/s/{site}/stat/sta",
+ f"/api/s/{site}/stat/sta",
+ ]:
+ try:
+ r = await client.get(
+ f"{base}{path}",
+ cookies=cookies,
+ headers=headers,
+ follow_redirects=True,
+ )
+ if r.status_code == 200:
+ devices: list[dict[str, Any]] = r.json().get("data", [])
+ return devices
+ except Exception:
+ continue
+ return []
+
+
+def _normalize(d: dict[str, Any]) -> dict[str, Any]:
+ """Convert a raw UniFi device record to a homelable-compatible dict."""
+ raw_type = (d.get("type") or "").lower()
+ node_type = _TYPE_MAP.get(raw_type, "device")
+
+ mac = (d.get("mac") or "").lower()
+ ip = d.get("ip") or None
+ name = d.get("name") or d.get("hostname") or mac or "unknown"
+ model = d.get("model") or None
+ version = d.get("version") or None
+
+ ieee = f"unifi-{mac}" if mac else f"unifi-{name}"
+
+ props: list[dict[str, str]] = []
+ if raw_type:
+ props.append({"name": "UniFi type", "value": raw_type})
+ if model:
+ props.append({"name": "Model", "value": model})
+ if version:
+ props.append({"name": "Firmware", "value": version})
+ uptime = d.get("uptime")
+ if uptime is not None:
+ props.append({"name": "Uptime (s)", "value": str(uptime)})
+
+ return {
+ "ieee_address": ieee,
+ "mac": mac,
+ "ip": ip,
+ "hostname": name,
+ "label": name,
+ "type": node_type,
+ "vendor": "Ubiquiti",
+ "model": model,
+ "properties": props,
+ "raw_type": raw_type,
+ }
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index a0999e0..f21fd79 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -46,6 +46,7 @@ async def db_session():
"app.api.routes.zigbee",
"app.api.routes.zwave",
"app.api.routes.proxmox",
+ "app.api.routes.unifi",
"app.api.routes.scan",
)
]
diff --git a/backend/tests/test_scheduler.py b/backend/tests/test_scheduler.py
index b5e3785..f6ee084 100644
--- a/backend/tests/test_scheduler.py
+++ b/backend/tests/test_scheduler.py
@@ -218,6 +218,7 @@ def test_scheduler_uses_settings_interval():
mock_settings.proxmox_sync_enabled = False
mock_settings.zigbee_sync_enabled = False
mock_settings.zwave_sync_enabled = False
+ mock_settings.unifi_sync_enabled = False
start_scheduler()
_, kwargs = mock_sched.add_job.call_args
assert kwargs["seconds"] == 45
@@ -233,6 +234,7 @@ def test_start_and_stop_scheduler():
mock_settings.proxmox_sync_enabled = False
mock_settings.zigbee_sync_enabled = False
mock_settings.zwave_sync_enabled = False
+ mock_settings.unifi_sync_enabled = False
start_scheduler()
stop_scheduler()
mock_sched.add_job.assert_called_once()
diff --git a/backend/tests/test_unifi_router.py b/backend/tests/test_unifi_router.py
new file mode 100644
index 0000000..87a51c2
--- /dev/null
+++ b/backend/tests/test_unifi_router.py
@@ -0,0 +1,136 @@
+"""API + persistence tests for /api/v1/unifi/*."""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.routes.unifi import _find_existing, _persist_devices
+from app.core.config import settings
+from app.db.models import InventoryDevice
+
+
[email protected](autouse=True)
+def _clear_unifi_env():
+ host = settings.unifi_host
+ url = settings.unifi_url
+ user = settings.unifi_username
+ pw = settings.unifi_password
+ settings.unifi_host = ""
+ settings.unifi_url = ""
+ settings.unifi_username = ""
+ settings.unifi_password = ""
+ yield
+ settings.unifi_host = host
+ settings.unifi_url = url
+ settings.unifi_username = user
+ settings.unifi_password = pw
+# --- auth ------------------------------------------------------------------
+
+async def test_requires_auth_sync_now(client: AsyncClient) -> None:
+ res = await client.post("/api/v1/unifi/sync-now")
+ assert res.status_code == 401
+async def test_requires_auth_config_get(client: AsyncClient) -> None:
+ res = await client.get("/api/v1/unifi/config")
+ assert res.status_code == 401
+# --- config endpoint -------------------------------------------------------
+
+async def test_config_omits_credentials(client: AsyncClient, headers: dict) -> None:
+ settings.unifi_host = "unifi.local"
+ settings.unifi_username = "admin"
+ settings.unifi_password = "supersecret"
+ res = await client.get("/api/v1/unifi/config", headers=headers)
+ assert res.status_code == 200
+ body = res.text
+ assert "supersecret" not in body
+ assert res.json()["credentials_configured"] is True
+async def test_config_credentials_configured_false_when_empty(client: AsyncClient, headers: dict) -> None:
+ res = await client.get("/api/v1/unifi/config", headers=headers)
+ assert res.status_code == 200
+ assert res.json()["credentials_configured"] is False
+# --- sync-now --------------------------------------------------------------
+
+async def test_sync_now_rejected_without_credentials(client: AsyncClient, headers: dict) -> None:
+ res = await client.post("/api/v1/unifi/sync-now", headers=headers)
+ assert res.status_code == 400
+async def test_enable_sync_without_credentials_rejected(client: AsyncClient, headers: dict) -> None:
+ res = await client.post(
+ "/api/v1/unifi/config",
+ json={"sync_enabled": True, "sync_interval": 3600},
+ headers=headers,
+ )
+ assert res.status_code == 400
+# --- _find_existing --------------------------------------------------------
+
+async def test_find_existing_by_ieee(db_session: AsyncSession) -> None:
+ row = InventoryDevice(
+ ieee_address="unifi-aa:bb:cc:dd:ee:ff",
+ mac="aa:bb:cc:dd:ee:ff",
+ status="pending",
+ discovery_source="unifi",
+ )
+ db_session.add(row)
+ await db_session.commit()
+
+ found = await _find_existing(db_session, "unifi-aa:bb:cc:dd:ee:ff", "aa:bb:cc:dd:ee:ff")
+ assert found is not None
+ assert found.ieee_address == "unifi-aa:bb:cc:dd:ee:ff"
+async def test_find_existing_mac_not_stolen_from_ieee_device(db_session: AsyncSession) -> None:
+ row = InventoryDevice(
+ ieee_address="scan-device-xyz",
+ mac="11:22:33:44:55:66",
+ status="approved",
+ discovery_source="scan",
+ )
+ db_session.add(row)
+ await db_session.commit()
+
+ found = await _find_existing(db_session, "unifi-11:22:33:44:55:66", "11:22:33:44:55:66")
+ assert found is None
+# --- approved status preserved ---------------------------------------------
+
+async def test_approved_device_stays_approved(db_session: AsyncSession) -> None:
+ ieee = "unifi-aa:00:11:22:33:44"
+ row = InventoryDevice(
+ ieee_address=ieee,
+ mac="aa:00:11:22:33:44",
+ status="approved",
+ discovery_source="unifi",
+ discovery_sources=["unifi"],
+ )
+ db_session.add(row)
+ await db_session.commit()
+
+ devices = [{
+ "ieee_address": ieee,
+ "mac": "aa:00:11:22:33:44",
+ "ip": "10.1.1.5",
+ "hostname": "ap-living",
+ "label": "ap-living",
+ "type": "device",
+ "vendor": "Ubiquiti",
+ "model": "UAP-AC-PRO",
+ "properties": [],
+ }]
+ await _persist_devices(db_session, devices)
+
+ updated = (
+ await db_session.execute(
+ select(InventoryDevice).where(InventoryDevice.ieee_address == ieee)
+ )
+ ).scalars().first()
+ assert updated is not None
+ assert updated.status == "approved", (
+ f"Status changed to '{updated.status}'; auto-sync must not un-approve devices"
+ )