UniFi integration: network devices, Wi-Fi and networks, as part of the dependency map

A UniFi controller (API key on Network 9+, or a read-only local login on any
version) is read every five minutes. Its switches, access points and gateways
are kept with state, IP, uptime, firmware and uplink; its networks and Wi-Fi
names beside them (passphrases are never read). Nothing is written to the
controller.

Network > Network devices lists them. Devices are a new node type in the
dependency map: uplinks become dependencies by themselves, others can be
written by hand. A device offline past a limit is an offline alert, folds what
depends on it, can be silenced with maintenance and have runbooks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 00:35:48 +02:00
1 parent 73a06ebe63
commit 396e074108
48 files changed
+6893 -102

No files matched your search

+2
View File
@@ -25,6 +25,7 @@ const TYPE_LABELS: Record<IntegrationType, string> = {
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
};
/** The page each kind of integration gets once it is connected. */
@@ -39,6 +40,7 @@ const TYPE_PAGES: Record<IntegrationType, string> = {
phpipam: "/ipam",
pbs: "/pbs",
osticket: "/osticket",
unifi: "/network/devices",
};
/** "pve.example.lan" out of "https://pve.example.lan:8006/", or the text itself when it isn't an address. */
+12 -2
View File
@@ -265,9 +265,10 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
<label className="form-label">What are you working on?</label>
<select className="form-select" required value={target} onChange={(e) => setTarget(e.target.value)}>
<option value="">Choose…</option>
{targets && targets.servers.length + targets.integrations.length + targets.dnsProviders.length > 1 && (
{targets && targets.servers.length + targets.integrations.length + targets.dnsProviders.length + targets.devices.length > 1 && (
<optgroup label="Many at once">
<option value="all:everything">Everything — every server, integration and DNS provider</option>
<option value="all:everything">Everything — every server, integration, network device and DNS provider</option>
{targets.devices.length > 1 && <option value="all:devices">All network devices ({targets.devices.length})</option>}
{targets.servers.length > 1 && <option value="all:servers">All servers ({targets.servers.length})</option>}
{targets.integrations.length > 1 && <option value="all:integrations">All integrations (the enabled ones)</option>}
{targets.dnsProviders.length > 1 && <option value="all:dns_providers">All DNS providers (the enabled ones)</option>}
@@ -291,6 +292,15 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
))}
</optgroup>
)}
{targets && targets.devices.length > 0 && (
<optgroup label="Network devices">
{targets.devices.map((d) => (
<option key={`n${d.id}`} value={`device:${d.id}`}>
{d.name} ({d.kind.replace("_", " ")})
</option>
))}
</optgroup>
)}
{targets && targets.dnsProviders.length > 0 && (
<optgroup label="DNS providers">
{targets.dnsProviders.map((p) => (
+420
View File
@@ -0,0 +1,420 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api, type CurrentUser, type NetworkDevice, type NetworkDeviceKind, type NetworkOverview, type NetworkSegment } from "../api/client";
import SortableTh from "../components/SortableTh";
import Pagination from "../components/Pagination";
import TableToolbar from "../components/TableToolbar";
import TimeAgo from "../components/TimeAgo";
import ViewTabs from "../components/ViewTabs";
import SilenceButton from "../components/SilenceButton";
import RunbookEntry from "../components/RunbookEntry";
import CopyButton from "../components/CopyButton";
import EmptyState, { EmptyRow } from "../components/EmptyState";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { useSortable } from "../hooks/useSortable";
import { useTableSearch } from "../hooks/useTableSearch";
import { usePagination } from "../hooks/usePagination";
import { downloadCsv } from "../utils/csv";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
const KIND_LABELS: Record<NetworkDeviceKind, string> = { gateway: "Gateway", switch: "Switch", access_point: "Access point", other: "Other" };
/** "12 d 3 h", "5 h 20 min", "40 min". */
export function uptimeWords(seconds: number | null): string {
if (seconds === null) return "—";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
if (hours < 48) return `${hours} h ${minutes % 60} min`;
const days = Math.floor(hours / 24);
return `${days} d ${hours % 24} h`;
}
type Row = NetworkDevice & { uplinkName: string; stateRank: number };
const STATE_RANK: Record<NetworkDevice["state"], number> = { offline: 0, updating: 1, pending: 2, other: 3, online: 4 };
function StateBadge({ d }: { d: NetworkDevice }) {
switch (d.state) {
case "online":
return <span className="badge bg-green-lt text-green">Online</span>;
case "offline":
return (
<span className="badge bg-red-lt text-red" title="The controller has not seen it online">
Offline{d.offlineSince ? <> · <TimeAgo value={d.offlineSince} /></> : null}
</span>
);
case "updating":
return <span className="badge bg-yellow-lt text-yellow">Updating</span>;
case "pending":
return <span className="badge bg-blue-lt text-blue">Being adopted</span>;
default:
return <span className="badge bg-secondary-lt text-secondary">Unknown</span>;
}
}
/**
* The switches, access points and gateways a UniFi controller knows: how each is doing, its address, how long it has been up, what it is connected through and what
* depends on it — and, on the other tab, the networks and Wi-Fi names. Read from the controller every few minutes; what is shown is what was last read.
*/
export default function NetworkDevices({ user }: { user: CurrentUser }) {
const canAct = user.role === "admin" || user.role === "operator";
const [params] = useSearchParams();
const view = params.get("view") === "wifi" ? "wifi" : "devices";
const [data, setData] = useState<NetworkOverview | null>(null);
const [error, setError] = useState<string | null>(null);
const [reading, setReading] = useState(false);
const [kind, setKind] = useState<"all" | NetworkDeviceKind>("all");
const [status, setStatus] = useState<"all" | "problem">("all");
const load = useCallback(() => {
return api.network
.overview()
.then((res) => {
setData(res);
setError(null);
})
.catch((err) => setError(readableError(err)));
}, []);
useEffect(() => {
void load();
const timer = setInterval(() => void load(), 60_000);
return () => clearInterval(timer);
}, [load]);
async function readNow() {
setReading(true);
try {
const res = await api.network.sync();
const failed = Object.values(res.statuses).filter((s) => !s.ok);
if (failed.length > 0) toast.error(`Couldn't read ${failed.length === 1 ? "a controller" : `${failed.length} controllers`}: ${failed[0].error ?? "no answer"}`);
else toast.success("Read from the controller.");
await load();
} catch (err) {
toast.error(readableError(err));
} finally {
setReading(false);
}
}
const rows: Row[] = useMemo(
() =>
(data?.devices ?? [])
.filter((d) => (kind === "all" || d.kind === kind) && (status === "all" || d.state === "offline" || d.firmwareUpdatable))
.map((d) => ({ ...d, uplinkName: d.uplink?.name ?? "", stateRank: STATE_RANK[d.state] })),
[data, kind, status],
);
const tableSearch = useTableSearch(rows);
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "stateRank", "asc", { url: true });
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
const devices = data?.devices ?? [];
const offline = devices.filter((d) => d.state === "offline").length;
const updates = devices.filter((d) => d.firmwareUpdatable).length;
const controllers = data?.integrations.filter((i) => i.enabled) ?? [];
const tabs = (
<ViewTabs
label="Network devices view"
tabs={[
{ to: "/network/devices", label: "Devices", active: view === "devices" },
{ to: "/network/devices?view=wifi", label: "Networks & Wi-Fi", active: view === "wifi" },
]}
/>
);
function exportCsv() {
downloadCsv(
"network-devices.csv",
["Name", "Kind", "Model", "State", "IP address", "MAC address", "Uptime (seconds)", "Firmware", "Update available", "Connected through", "Needed by", "Controller", "Site"],
(sorted ?? []).map((d) => [d.name, KIND_LABELS[d.kind], d.model ?? "", d.state, d.ip ?? "", d.mac ?? "", d.uptimeSeconds ?? "", d.firmware ?? "", d.firmwareUpdatable ? "yes" : "no", d.uplinkName, d.dependents, d.integrationName, d.siteName ?? ""]),
);
}
const noController = data !== null && data.integrations.length === 0;
return (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
<h2 className="page-title mb-0">Network devices</h2>
{canAct && controllers.length > 0 && (
<div className="ms-auto btn-list">
<button className="btn btn-outline-secondary" onClick={() => void readNow()} disabled={reading}>
{reading ? "Reading…" : "Read now"}
</button>
</div>
)}
</div>
{tabs}
<div className="text-secondary mb-3">
Switches, access points and gateways from your UniFi controller: whether each is up, its address, how long it has been running, and what it is connected through. The same devices take part in the
dependency map, so when one is down what hangs off it is folded under its alert.
</div>
<ErrorNotice error={error} />
{data === null && !error && <BlockSkeleton lines={4} />}
{noController && (
<div className="card">
<EmptyState
title="No UniFi controller connected"
hint="Add a UniFi integration — an API key from the controller's Integrations settings, or a read-only local account — and its switches, access points and gateways appear here."
action={user.role === "admin" ? { label: "Add a UniFi controller", to: "/integrations" } : undefined}
/>
</div>
)}
{data && data.integrations.length > 0 && (
<div className="mb-3 small">
{data.integrations.map((i) => (
<div key={i.id} className={i.status && !i.status.ok ? "text-red" : "text-secondary"}>
<strong>{i.name}</strong>
{!i.enabled ? (
" — switched off"
) : !i.status ? (
" — not read yet"
) : i.status.ok ? (
<>
{" "}
— read <TimeAgo value={i.status.at} /> · {i.status.devices} {i.status.devices === 1 ? "device" : "devices"}
{i.status.sites.length > 0 ? `, ${i.status.sites.length === 1 ? "site" : "sites"} ${i.status.sites.join(", ")}` : ""}
{i.status.mode ? ` · via ${i.status.mode === "api_key" ? "API key" : "login"}` : ""}
</>
) : (
<>
{" "}
— couldn&rsquo;t be read: {i.status.error}. Showing what was read <TimeAgo value={i.status.at} />; alerts for its devices are held until it can be read again.
</>
)}
</div>
))}
</div>
)}
{data && data.integrations.length > 0 && view === "devices" && (
<>
<div className="row row-cards mb-3">
{[
{ label: "Devices", value: devices.length, color: "" },
{ label: "Offline", value: offline, color: offline > 0 ? "text-red" : "text-green" },
{ label: "Firmware updates", value: updates, color: updates > 0 ? "text-yellow" : "" },
{ label: "Controllers", value: controllers.length, color: "" },
].map((c) => (
<div className="col-6 col-lg-3" key={c.label}>
<div className="card card-sm">
<div className="card-body">
<div className={`h2 mb-0 ${c.color}`}>{c.value}</div>
<div className="text-secondary">{c.label}</div>
</div>
</div>
</div>
))}
</div>
<div className="card">
<TableToolbar
search={tableSearch.query}
onSearch={tableSearch.setQuery}
placeholder="Search devices…"
filters={
<>
<select className="form-select form-select-sm w-auto" aria-label="Kind of device" value={kind} onChange={(e) => setKind(e.target.value as typeof kind)}>
<option value="all">Every kind</option>
{(Object.keys(KIND_LABELS) as NetworkDeviceKind[]).map((k) => (
<option key={k} value={k}>
{KIND_LABELS[k]}
</option>
))}
</select>
<select className="form-select form-select-sm w-auto" aria-label="Which devices" value={status} onChange={(e) => setStatus(e.target.value as typeof status)}>
<option value="all">All devices</option>
<option value="problem">Offline or with an update waiting</option>
</select>
</>
}
shown={sorted?.length}
total={devices.length}
onExport={exportCsv}
exportDisabled={!sorted || sorted.length === 0}
/>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<SortableTh<Row> label="Status" sortKeyName="stateRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="IP address" sortKeyName="ip" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Uptime" sortKeyName="uptimeSeconds" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Firmware" sortKeyName="firmware" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Connected through" sortKeyName="uplinkName" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Needed by" sortKeyName="dependents" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
{canAct && (
<th className="w-1">
<span className="visually-hidden">Actions</span>
</th>
)}
</tr>
</thead>
<tbody>
{(pageItems ?? []).map((d) => (
<tr key={d.id}>
<td>
<StateBadge d={d} />
{d.inMaintenance && (
<span className="badge bg-secondary-lt text-secondary ms-1" title="Under a maintenance window — its alerts are held back">
maintenance
</span>
)}
</td>
<td className="stack-wide">
<strong>{d.name}</strong>
<div className="text-secondary small">
{KIND_LABELS[d.kind]}
{d.model ? ` · ${d.model}` : ""}
{data.integrations.length > 1 ? ` · ${d.integrationName}` : ""}
{d.siteName && d.siteName !== "Default" ? ` · ${d.siteName}` : ""}
</div>
{d.mac && <div className="text-secondary small font-monospace">{d.mac}</div>}
</td>
<td className="stack-label" data-label="IP address">
{d.ip ? (
<span className="d-inline-flex align-items-center gap-2">
<span className="font-monospace">{d.ip}</span>
<CopyButton text={d.ip} />
</span>
) : (
<span className="text-secondary">—</span>
)}
</td>
<td className="stack-label text-nowrap" data-label="Uptime">
{d.state === "online" ? uptimeWords(d.uptimeSeconds) : <span className="text-secondary">—</span>}
</td>
<td className="stack-label" data-label="Firmware">
{d.firmware ?? <span className="text-secondary">—</span>}
{d.firmwareUpdatable && <span className="badge bg-yellow-lt text-yellow ms-1">update available</span>}
</td>
<td className="stack-label" data-label="Connected through">
{d.uplink ? d.uplink.name : <span className="text-secondary">{d.kind === "gateway" ? "(the internet)" : "—"}</span>}
</td>
<td className="stack-label" data-label="Needed by">
{d.dependents > 0 ? (
<Link to="/map?view=dependencies" title="Open the dependency map">
{d.dependents} {d.dependents === 1 ? "thing" : "things"}
</Link>
) : (
<span className="text-secondary">nothing</span>
)}
</td>
{canAct && (
<td className="text-nowrap stack-wide">
<div className="btn-list flex-nowrap align-items-center">
{!d.inMaintenance && <SilenceButton target={{ type: "device", id: d.id, name: d.name }} onDone={() => void load()} />}
<RunbookEntry targetType="device" targetId={d.id} targetName={d.name} canEdit={canAct} offerAdd />
</div>
</td>
)}
</tr>
))}
{(sorted ?? []).length === 0 && (
<EmptyRow
colSpan={canAct ? 8 : 7}
{...(tableSearch.active || kind !== "all" || status !== "all"
? { filtered: () => { tableSearch.setQuery(""); setKind("all"); setStatus("all"); } }
: { title: "No devices yet", hint: "The controller has not reported any, or has not been read yet. Press Read now." })}
/>
)}
</tbody>
</table>
</div>
<Pagination page={page} pageCount={pageCount} totalCount={totalCount} onPageChange={setPage} />
</div>
</>
)}
{data && data.integrations.length > 0 && view === "wifi" && <NetworksAndWifi data={data} />}
</>
);
}
function enabledBadge(on: boolean) {
return on ? <span className="badge bg-green-lt text-green">On</span> : <span className="badge bg-secondary-lt text-secondary">Off</span>;
}
function NetworksAndWifi({ data }: { data: NetworkOverview }) {
const many = data.integrations.length > 1;
const where = (s: NetworkSegment) => [many ? s.integrationName : null, s.siteName && s.siteName !== "Default" ? s.siteName : null].filter(Boolean).join(" · ");
return (
<>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Networks</h3>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<th>Name</th>
<th>VLAN</th>
<th>Address range</th>
<th>Purpose</th>
<th>State</th>
</tr>
</thead>
<tbody>
{data.networks.map((n) => (
<tr key={n.id}>
<td className="stack-wide">
<strong>{n.name}</strong>
{where(n) && <div className="text-secondary small">{where(n)}</div>}
</td>
<td className="stack-label" data-label="VLAN">{n.vlanId ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label font-monospace" data-label="Address range">{n.subnet ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="Purpose">{n.purpose ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="State">{enabledBadge(n.enabled)}</td>
</tr>
))}
{data.networks.length === 0 && <EmptyRow colSpan={5} title="No networks read" hint="The controller reported none, or the account or key may not be allowed to read them." />}
</tbody>
</table>
</div>
</div>
<div className="card">
<div className="card-header">
<h3 className="card-title">Wi-Fi names</h3>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<th>Name (SSID)</th>
<th>Security</th>
<th>Network</th>
<th>VLAN</th>
<th>State</th>
</tr>
</thead>
<tbody>
{data.ssids.map((s) => (
<tr key={s.id}>
<td className="stack-wide">
<strong>{s.name}</strong>
{where(s) && <div className="text-secondary small">{where(s)}</div>}
</td>
<td className="stack-label" data-label="Security">{s.security ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="Network">{s.networkName ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="VLAN">{s.vlanId ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="State">{enabledBadge(s.enabled)}</td>
</tr>
))}
{data.ssids.length === 0 && <EmptyRow colSpan={5} title="No Wi-Fi names read" hint="The controller reported none, or the account or key may not be allowed to read them." />}
</tbody>
</table>
</div>
<div className="card-footer text-secondary small">Passphrases are never read from the controller.</div>
</div>
</>
);
}
+1
View File
@@ -23,6 +23,7 @@ const INTEGRATION_NAMES: Record<string, string> = {
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
};
function ColorList({
@@ -82,7 +82,7 @@ const DIGEST_DAYS: { value: number; label: string }[] = [
{ value: 6, label: "Saturday" },
{ value: 0, label: "Sunday" },
];
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3 };
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3, deviceOfflineMinutes: 10 };
const DEFAULT_MONTHLY: MonthlyReportSettings = { enabled: false, day: 1, time: "08:00" };
type TestResult = { ok: boolean; message: string } | null;
@@ -735,6 +735,15 @@ export default function NotificationSettings() {
hint="From each agent server's own history, shown on the Alerts page and dashboard (not sent as a notification). Needs a few days of steady growth to say anything. 0 turns it off."
onChange={(v) => setHealthChecks((h) => ({ ...h, diskForecastDays: v }))}
/>
<NumberField
label="Alert when a network device is offline for"
value={healthChecks.deviceOfflineMinutes}
min={5}
max={1440}
unit="minutes"
hint="Switches, access points and gateways read from a UniFi controller (Network devices). The controller is read every five minutes, and what a device needs or what needs it is folded under it when it is down."
onChange={(v) => setHealthChecks((h) => ({ ...h, deviceOfflineMinutes: v }))}
/>
<label className="form-check mt-3 mb-0">
<input type="checkbox" className="form-check-input" checked={healthChecks.newPortAlerts} onChange={(e) => setHealthChecks((h) => ({ ...h, newPortAlerts: e.target.checked }))} />
<span className="form-check-label">