Compare commits

...
Author SHA1 Message Date
jaredandClaude Opus 5.5 4dfabce2fb Cutsheet: port names in UniFi that no longer fit, document a cable from topology
Lint / JS (eslint) (push) Successful in 23s
Lint / Python (flake8) (push) Successful in 1m10s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Lint / Python (flake8) (pull_request) Successful in 53s
Lint / JS (eslint) (pull_request) Successful in 11s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (push) Successful in 1m26s
Test / Python Tests (pytest) (push) Successful in 1m49s
Security / Python Security (bandit) (pull_request) Successful in 2m17s
Test / Python Tests (pytest) (pull_request) Successful in 2m12s
- topology.port_name_report: switch port names that no longer fit what is
  plugged in, as a checklist with suggested names: named after the wrong
  device, named after a device that moved to another port, named with nothing
  plugged in (and who was last seen there), and still "Port N" with a known
  device on it. Ports named after a device that is only off are left alone.
  Gandalf only reports; it never renames anything in UniFi.
- /api/cutsheet returns it as port_names; the cutsheet page shows it as
  "Port names in UniFi", grouped, with a summary chip.
- The topology cable panel's "not documented" gets a "document it" link that
  opens the cutsheet's new-cable form with both ends, the NIC and DAC filled
  in; /cutsheet?... now takes b_device, b_port and cable_type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:48:52 -05:00
jared d6fcddb6fc Merge pull request 'README: patch panel ends, tap to trace, stale outlet watts, SmartPower Strip' (#43) from readme-power-polish into main
Lint / JS (eslint) (push) Successful in 1m26s
Lint / Python (flake8) (push) Successful in 3m9s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m40s
Lint / Deploy (push) Successful in 4s
Test / Python Tests (pytest) (push) Successful in 45s
2026-11-15 13:48:40 -05:00
jaredandClaude Opus 5.5 ce68d592c3 README: patch panel ends, tap to trace, stale outlet watts, SmartPower Strip
Lint / JS (eslint) (push) Successful in 8s
Lint / Python (flake8) (push) Successful in 1m21s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m45s
Test / Python Tests (pytest) (push) Successful in 2m24s
Lint / Python (flake8) (pull_request) Successful in 2m14s
Lint / JS (eslint) (pull_request) Successful in 9s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m56s
Test / Python Tests (pytest) (pull_request) Successful in 2m0s
Documents #41 and #42 in the Topology and Device pages sections and the
faceplate list, and refreshes the topology gallery image (patch panel end and
the new strip drawing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:24:53 -05:00
jared 3a1371e8b7 Merge pull request 'Power: flag frozen outlet watts, draw the SmartPower Strip' (#42) from stale-outlet-watts into main
Lint / JS (eslint) (push) Successful in 17s
Lint / Python (flake8) (push) Successful in 1m48s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m35s
Lint / Deploy (push) Successful in 6s
Test / Python Tests (pytest) (push) Successful in 1m3s
2026-11-15 00:24:23 -05:00
jaredandClaude Opus 5.5 60d892badb Power: flag frozen outlet watts, draw the SmartPower Strip
Lint / JS (eslint) (push) Successful in 14s
Lint / Python (flake8) (push) Successful in 1m3s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m9s
Test / Python Tests (pytest) (push) Successful in 1m29s
Lint / Python (flake8) (pull_request) Successful in 1m9s
Lint / JS (eslint) (pull_request) Successful in 14s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m26s
Test / Python Tests (pytest) (pull_request) Successful in 1m48s
UniFi can keep serving one frozen set of USP PDU Pro outlet readings for hours
while the unit's total stays live (seen on prod: every outlet at 120.661 V with
the same watts all session, summing to 321 W of a live 593 W total). The monitor
now notices when a power unit's loaded outlet readings have not changed for 15
minutes and marks them stale. The topology page shows "stale" instead of watts,
the power badge says "fed", and a "to look at" chip says since when; the device
page marks the readings too.

Adds a UP6 (USP-Strip) faceplate traced from Ubiquiti's datasheet render: three
facing pairs of US outlets, four USB-C ports (outlet 7), the LED and the cord.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 22:46:04 -05:00
jared 206175df39 Merge pull request 'Topology: tap to trace on phones, name cables into a patch panel' (#41) from topology-polish into main
Lint / JS (eslint) (push) Successful in 24s
Security / Python Security (bandit) (push) Successful in 2m56s
Test / Python Tests (pytest) (push) Successful in 2m40s
Lint / Python (flake8) (push) Successful in 1m0s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Successful in 4s
2026-11-14 22:22:45 -05:00
14 changed files with 455 additions and 25 deletions

No files matched your search

+28 -5
View File
@@ -206,7 +206,10 @@ servers along the bottom. Power gear (PDU, UPS, power strip) sits in a rail on t
- **Unknown devices**: something plugged into a switch port that Gandalf can't name is a grey stub,
labelled with the port name (or its address), linking to that port. By default each switch's unknown
devices are one block with one bundled cable ("10 unknown devices"); click it to show them one by
one, or pick "one by one" or "hidden" in the toolbar.
one, or pick "one by one" or "hidden" in the toolbar. When the cutsheet records the cable going into
a patch panel, the far end is drawn as that panel's 24 jacks with the cable on its documented port,
named "Patch panel port 1" (the device beyond the panel is unknown); a stub that already has a name
keeps it and adds "via Patch panel port 2". The cable details show where the cutsheet cable goes.
- **Port names**: a ⚠ marks a port named after one device with a different one plugged in (a port
called "Large1 Management" with the AP on it). Generic names ("Port 4", "SFP+ 2", "Uplink") and
"Downlink to X" with X on the other end never flag.
@@ -214,16 +217,24 @@ servers along the bottom. Power gear (PDU, UPS, power strip) sits in a rail on t
severity colour, and the NIC it is about is marked.
- **Power**: each PDU, UPS and power strip card lists its outlets that feed something, draw power or
are off, with live watts; each device it feeds shows a ⚡ badge with what it draws. Hover a power
card or a device to draw its feeds. An outlet that is off but feeds something is listed above the
card or a device to draw its feeds. The SmartPower Strip has no metering, so it never shows watts. An outlet that is off but feeds something is listed above the
diagram. What an outlet feeds comes from, in order: an assignment saved here, the outlet's name in
UniFi when it names a device ("storage-01", "Dream Machine Pro", "AT&T Modem" for the modem), or a
MAC in its name that belongs to a host NIC or UniFi device. Admins click an outlet to set what it
feeds, set it to nothing, or go back to automatic. Assignments are kept in Gandalf (table
`power_feeds`); Gandalf never renames outlets in UniFi. API: `PUT /api/topology/power/<device>/<outlet>`
with `{"target": "<device>"}`, `""` for nothing or `null` for automatic.
- **Stale outlet watts**: UniFi can keep serving one frozen set of USP PDU Pro outlet readings for hours
while the unit's total stays live. When a unit's loaded outlets have not changed at all for 15 minutes,
the monitor marks them stale: the outlet rows say "stale" instead of watts, ⚡ badges say "fed", and
the list above the diagram says since when (`outlets_stale_since` in `link_stats.unifi_devices`). The
marks clear on the next poll after the readings move. The 15 minutes start again when the monitor
restarts. Restarting the PDU or updating its firmware in UniFi is the usual cure.
- Click a device for its page, or a port on a faceplate for that port. Click a cable for its details:
both ends, speed, cable type and module, traffic each way and how busy it is, errors and drops, and
its cutsheet record. Hovering a device traces its path to the internet.
its cutsheet record. Hovering a device traces its path to the internet. On a touch screen, which
has no hover, the first tap on a device traces it (path and power feeds) and a second tap opens it;
tapping empty canvas clears it.
- Drag to pan, scroll or pinch to zoom, **Fit** (or `0`) to see everything, `+` and `-` to zoom. Show
unknown devices grouped, one by one or not at all. **Server 1G links** (off by default) adds each
server's slower second cable, its management link; **Power gear** shows or hides the power rail. Traffic labels and dimming everything without an alert can be switched too. The
@@ -245,7 +256,8 @@ interface and port names, and LLDP neighbors.
- **Alerts**: active and past alerts for this device
- **WAN** (routers): connection state, speed, latency, availability
- **Connected to** (hosts): switch ports that see this host over LLDP
- **Outlets** (PDUs): per-outlet state, power, and auto power-cycle setting
- **Outlets** (PDUs, UPS, power strip): per-outlet state, power, and auto power-cycle setting; readings
UniFi has frozen are marked stale (see Topology)
- **Port inspector** (switches, routers): see below
- **Interfaces / Ports**: one row each with state, speed, RX/TX rate, and neighbor, filterable.
Expanding a host's row shows duplex, auto-negotiation, carrier changes, error and drop rates,
@@ -318,6 +330,7 @@ neighbors that can't be matched show their MAC. Bonded NICs share a MAC, so only
| `USMINI` | USW Flex Mini | 5×RJ45, PoE in on port 1 |
| `USPPDUP` | USP PDU Pro | 20 outlets (4 USB-C, 16 AC), management port 21, surge pass-through ports 22-23 |
| `USPDA2B` | UPS 2U Pro | Front with touchscreen outlet tiles; rear with 8 outlets, EPO, surge and MGMT ports |
| `UP6` | SmartPower Strip | Top face: 6 AC outlets in facing pairs, 4 USB-C (switched together as outlet 7) |
Port LEDs use the colors from each model's quick start guide. Other models use plain blocks until they get an
entry in `FACEPLATES`.
@@ -340,7 +353,16 @@ can view it; only the `admin` group can edit, and every change is logged with wh
cables in one port). Runs that end at a jack are *unverified* while linked and *idle* when not.
Planned, dark and retired cables aren't checked.
- **Undocumented links**: live switch ports no cable mentions, with an Add button that pre-fills
what Gandalf knows. Each switch port panel also shows its planned cable, or links to add one.
what Gandalf knows. Each switch port panel also shows its planned cable, or links to add one. On
the topology page, a cable with no record has a **document it** link that opens this form with both
ends (and the NIC, and DAC when it is one) filled in. `/cutsheet?a_device=&a_port=&b_device=&b_port=&cable_type=`
opens it the same way.
- **Port names in UniFi**: a checklist of switch port names that no longer fit what is plugged in:
named after the wrong device, named after a device that has moved to another port, named but with
nothing plugged in (with who was last seen there), and still "Port N" with a known device on it
(folded). Each comes with a suggested name: the device, the device and NIC for a server with two
cables, "Uplink" or "Downlink to X" between switches. A port named after a device that is only
switched off is left alone. Rename them in UniFi yourself; Gandalf never changes UniFi.
- **Labels to make**: cable IDs (one per cord end) and panel-port labels not yet stuck on, sized for
typing on a handheld label maker. Tick each off once it's applied; **Print list** prints just this.
- **CSV**: export, and import that adds or updates cables by ID. A file with any invalid row imports
@@ -833,6 +855,7 @@ gandalf/
UniFi gear drawn with live ports: UDM Pro (`UDMPRO`), USW Pro 24 PoE (`US24PRO`), USW Aggregation
(`USL8A`), USW Flex (`USF5P`), USW Flex Mini (`USMINI`), USP PDU Pro (`USPPDUP`), UPS 2U Pro (`USPDA2B`),
SmartPower Strip (`UP6`, outlets only),
USW Pro Max 24 PoE (`USPM24P`, also `USPM24`) and USW Pro Max 48 PoE (`USPM48P`, also `USPM48`), plus the
UniFi NVR Pro (`UNVRPRO`), which UniFi Network doesn't report and so is picked by Front drawing. The Pro
Max switches also have Front drawing options, so a new switch draws correctly on the rack before it is
+3
View File
@@ -1032,6 +1032,9 @@ def _cutsheet_view() -> dict:
snapshot = _state_json('network_snapshot')
data['devices'] = sorted(set(switches) | set(snapshot.get('hosts') or {})
| {u['name'] for u in snapshot.get('unifi') or [] if u.get('name')}, key=str.lower)
# UniFi port names that no longer fit what is plugged in (Gandalf never renames them)
data['port_names'] = topology.port_name_report(
snapshot, link_stats, _state_json('modem_stats'), _state_json('known_uplinks'))
data['verdicts'] = cutsheet.VERDICTS
data['chassis'] = cutsheet.CHASSIS
data['options'] = {'kinds': cutsheet.ITEM_KINDS, 'passive_kinds': cutsheet.PASSIVE_KINDS,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

After

Width:  |  Height:  |  Size: 161 KiB

+27
View File
@@ -659,6 +659,32 @@ class LinkStatsCollector:
# State for UniFi rate calculation (previous snapshot + timestamp)
self._prev_unifi: Dict[str, dict] = {}
self._prev_unifi_time: float = 0.0
# Per power unit: (its outlets' last readings, when they last changed)
self._outlet_readings: Dict[str, tuple] = {}
# Live readings from a loaded outlet change every poll (watts and amps to three decimals).
# When none of them has moved for this long, UniFi is serving a frozen snapshot: the USP PDU
# Pro can keep reporting one set of outlet readings for hours while its total stays live.
OUTLET_STALE_AFTER_S = 15 * 60
def _mark_stale_outlets(self, devices: Dict[str, dict], now: float) -> None:
"""Mark each metered outlet 'stale' and set the device's 'outlets_stale_since' (UTC)
when a power unit's outlet readings have not changed for OUTLET_STALE_AFTER_S."""
for name, info in devices.items():
metered = [o for o in info.get('outlets') or [] if o.get('power_w') is not None]
if not metered:
continue
readings = tuple((o.get('index'), o.get('power_w'), o.get('current_a')) for o in metered)
prev = self._outlet_readings.get(name)
since = prev[1] if prev and prev[0] == readings else now
self._outlet_readings[name] = (readings, since)
# All-zero outlets legitimately read the same every time
loaded = any(o.get('power_w') for o in metered)
if loaded and now - since >= self.OUTLET_STALE_AFTER_S:
stamp = datetime.fromtimestamp(since, timezone.utc)
info['outlets_stale_since'] = stamp.strftime('%Y-%m-%d %H:%M:%S UTC')
for o in metered:
o['stale'] = True
# ------------------------------------------------------------------
# SSH collection (via Pulse worker)
@@ -929,6 +955,7 @@ class LinkStatsCollector:
logger.warning(f'UniFi switch port collection failed: {e}')
unifi_devices = (self.unifi.get_device_details() or {}) if self.unifi else {}
self._mark_stale_outlets(unifi_devices, time.time())
host_macs = self._resolve_neighbors(unifi_switches, unifi_devices, instance_map)
return {
+51 -1
View File
@@ -74,6 +74,7 @@ function renderSummary() {
chip(matches, 'match what Gandalf sees', 'cs-chip-ok', 'cs-cables-section'),
chip(problems, problems === 1 ? 'problem' : 'problems', problems ? 'cs-chip-bad' : '', 'cs-cables-section'),
chip(_cs.suggestions.length, 'undocumented links', _cs.suggestions.length ? 'cs-chip-warn' : '', 'cs-suggest-section'),
chip(portFixes(), 'port names to fix', portFixes() ? 'cs-chip-warn' : '', 'cs-portnames-section'),
chip(labels, 'labels to make', labels ? 'cs-chip-warn' : '', 'cs-labels-section'),
].join('');
}
@@ -153,6 +154,51 @@ function renderSuggestions() {
${_showAllSuggestions ? 'Show fewer' : `Show all ${list.length}`}</button>` : ''}`;
}
// ── Port names in UniFi ─────────────────────────────────────────────────
const PORT_NAME_GROUPS = [
['wrong', 'Named after the wrong device', 'cs-chip-bad'],
['moved', 'Named after a device that moved', 'cs-chip-warn'],
['empty', 'Named, but nothing is plugged in', ''],
['unnamed', 'Unnamed, with a known device plugged in', ''],
];
// Wrong and moved names are worth fixing; empty and unnamed ports are only worth a look
function portFixes() {
return (_cs.port_names || []).filter(r => r.kind === 'wrong' || r.kind === 'moved').length;
}
function renderPortNames() {
const rows = _cs.port_names || [];
document.getElementById('cs-portnames-count').textContent = rows.length;
const wrap = document.getElementById('cs-portnames');
if (!rows.length) {
wrap.innerHTML = emptyState('✅', 'Every port name fits what is plugged in', '');
return;
}
wrap.innerHTML = PORT_NAME_GROUPS.map(([kind, title, cls]) => {
const list = rows.filter(r => r.kind === kind);
if (!list.length) return '';
const table = `<div class="lt-table-wrap">
<table class="lt-table lt-table-sm">
<caption class="lt-sr-only">${esc(title)}</caption>
<thead><tr><th>Switch port</th><th>Name in UniFi</th><th>What Gandalf sees</th><th>Suggested name</th></tr></thead>
<tbody>${list.map(r => `
<tr>
<td>${deviceLink(r.switch)} <a class="cs-port" href="/device/${encodeURIComponent(r.switch)}#port-${esc(r.port_idx)}">port ${esc(r.port_idx)}</a></td>
<td>${esc(r.port_name)}</td>
<td>${esc(r.detail)}</td>
<td>${r.suggestion ? `<code>${esc(r.suggestion)}</code>` : '<span class="val-neutral">your call</span>'}</td>
</tr>`).join('')}
</tbody>
</table>
</div>`;
// The long, low-priority group starts folded
const open = kind !== 'unnamed' ? ' open' : '';
return `<details class="cs-portname-group"${open}>
<summary><span class="cs-chip ${cls}"><b>${list.length}</b> ${esc(title)}</span></summary>${table}</details>`;
}).join('');
}
function cableAt(name, port, side) {
return _cs.cables.find(c => c.status !== 'retired' &&
['a', 'b'].some(e => c[`${e}_device`] === name && c[`${e}_port`] === String(port) && c[`${e}_side`] === side));
@@ -331,6 +377,7 @@ function render() {
renderSummary();
renderCables();
renderSuggestions();
renderPortNames();
renderPanels();
renderLabels();
renderRack();
@@ -700,7 +747,10 @@ function printLabels() {
function openFromQuery() {
const q = new URLSearchParams(window.location.search);
if (!CS_CAN_EDIT || !q.get('a_device')) return;
openCable(null, { a_device: q.get('a_device'), a_port: q.get('a_port') || '' });
openCable(null, {
a_device: q.get('a_device'), a_port: q.get('a_port') || '',
b_device: q.get('b_device') || '', b_port: q.get('b_port') || '', cable_type: q.get('cable_type') || '',
});
history.replaceState(null, '', window.location.pathname);
}
+6 -2
View File
@@ -292,10 +292,14 @@ function renderOutlets(d) {
<td><span class="dot-${o.on ? 'up' : 'down'}"></span></td>
<td>#${esc(o.index)}</td>
<td>${esc(o.name || '-')}</td>
<td class="device-num">${o.power_w === null || o.power_w === undefined ? '-' : `${o.power_w.toFixed(1)} W`}</td>
<td class="device-num">${o.power_w === null || o.power_w === undefined ? '-' : `${o.power_w.toFixed(1)} W${o.stale ? ' <span class="lt-badge" title="UniFi has been sending this same reading for a long time">stale</span>' : ''}`}</td>
<td>${o.auto_power_cycle ? '<span class="lt-badge">auto power-cycle</span>' : ''}</td>
</tr>`).join('');
return section('Outlets', `<div class="lt-table-wrap"><table class="lt-table">
const since = d.info.outlets_stale_since;
const note = since
? `<p class="g-page-sub">The outlet readings have not changed since ${esc(since)}: UniFi is sending a frozen snapshot, so they are not live. The power draw total is live.</p>`
: '';
return section('Outlets', `${note}<div class="lt-table-wrap"><table class="lt-table">
<caption class="lt-sr-only">PDU outlets</caption>
<thead><tr><th><span class="lt-sr-only">State</span></th><th>Outlet</th><th>Name</th><th>Power</th><th></th></tr></thead>
<tbody>${rows}</tbody></table></div>`);
+45 -1
View File
@@ -147,6 +147,18 @@ function outletFaceSvg(kind, w, h, idx) {
return `<rect class="fp-usbc" width="${w}" height="${h}" rx="${w / 2}"/>
<rect class="fp-usbc-tongue" x="${cx - 1}" y="4" width="2" height="${h - 8}" rx="1"/>`;
}
if (kind === 'usbc-h') {
return `<rect class="fp-usbc" width="${w}" height="${h}" rx="${h / 2}"/>
<rect class="fp-usbc-tongue" x="4" y="${cy - 1}" width="${w - 8}" height="2" rx="1"/>`;
}
if (kind === 'us-bare') {
// A US socket moulded straight into a white body (the SmartPower Strip): no face plate,
// just a shallow recess with the two blades over the round ground
return `<rect class="fp-outlet-bare" width="${w}" height="${h}" rx="${w / 4}"/>
<rect class="fp-slot" x="${cx - 17}" y="${cy - 20}" width="5.5" height="17" rx=".8"/>
<rect class="fp-slot" x="${cx + 11.5}" y="${cy - 22}" width="5.5" height="19" rx=".8"/>
<path class="fp-slot" d="M${cx - 7} ${cy + 22} v-8 a7 7 0 0 1 14 0 v8 Z"/>`;
}
const face = `<rect class="fp-outlet-face" width="${w}" height="${h}" rx="3"/>`;
if (kind === 'horizontal') {
return `${face}
@@ -168,7 +180,7 @@ function outletTitle(o, data) {
if (data) {
if (data.name && data.name !== parts[0]) parts.push(data.name);
parts.push(data.on === false ? 'off' : 'on');
if (data.power_w != null) parts.push(`${data.power_w.toFixed(1)} W`);
if (data.power_w != null) parts.push(`${data.power_w.toFixed(1)} W${data.stale ? ' (stale reading)' : ''}`);
if (data.auto_power_cycle) parts.push('auto power-cycle');
}
return lt.escHtml(parts.join(' · '));
@@ -566,6 +578,38 @@ const FACEPLATES = {
</g>`;
},
},
// UniFi SmartPower Strip (USP-Strip), top face. Traced from the product render on Ubiquiti's
// datasheet (images.salsify.com/.../046c9c047ca057faf25eb38f48c598318c9ae699.pdf, page 1) and
// sized from its 229.5 x 111.5 mm footprint at 4 units per mm, plus the cord on the left.
// Six AC outlets in three facing pairs (1 over 2, 3 over 4, 5 over 6), and four USB-C ports
// that UniFi switches together as outlet 7, "USB Outlets".
UP6: {
width: 968, height: 446, frameClass: 'fp-desk', noBody: true,
label: 'SmartPower Strip',
legend: [['outlet-on', 'outlet on'], ['outlet-off', 'outlet off']],
ports: [],
outlets: [
...[338, 502, 664].flatMap((cx, i) => [
{ idx: 2 * i + 1, kind: 'us-bare', flip: true, x: cx - 33, y: 86, w: 66, h: 66, label: [cx - 16, 232] },
{ idx: 2 * i + 2, kind: 'us-bare', x: cx - 33, y: 294, w: 66, h: 66, label: [cx + 22, 232] },
]),
...[84, 165, 250, 335].map((y, i) => ({
idx: 7, kind: 'usbc-h', x: 852, y: y - 7, w: 40, h: 14, label: i === 3 ? [872, y + 46] : null,
})),
],
decor({ online }) {
const usbNums = [84, 165, 250, 335].map((y, i) =>
`<text class="fp-label fp-label-sm" x="836" y="${y + 5}" text-anchor="middle">${i + 1}</text>`).join('');
return `<path class="fp-cord" d="M0 223 H48"/>
<rect class="fp-cord-boot" x="26" y="203" width="26" height="40" rx="6"/>
<rect class="fp-body-white" x="48" y="2" width="918" height="442" rx="44"/>
<path class="fp-strip-logo" d="M120 206 v18 a10 10 0 0 0 20 0 v-18"/>
<rect class="fp-strip-led${online ? ' fp-strip-led-on' : ''}" x="198" y="196" width="8" height="54" rx="4"/>
<text class="fp-label fp-label-sm" x="896" y="420" text-anchor="middle">USB-C</text>
${usbNums}`;
},
},
};
function faceplateLegendSwatch(cls) {
+11
View File
@@ -1030,6 +1030,13 @@ tr.device-row.is-selected { background: var(--bg-tertiary); box-shadow: inset 3p
.fp-usbc-tongue { fill: #b9bcc2; }
.fp-outlet-is-off .fp-outlet-face { fill: #5b5c60; }
.fp-outlet-is-off .fp-usbc { fill: #66676b; }
.fp-outlet-bare { fill: #e6e6e8; stroke: #cfcfd2; stroke-width: 1; }
.fp-outlet-is-off .fp-outlet-bare { fill: #b9babe; }
.fp-cord { stroke: #d9d9db; stroke-width: 16; stroke-linecap: round; fill: none; }
.fp-cord-boot { fill: #cfcfd2; }
.fp-strip-logo { fill: none; stroke: #b9babe; stroke-width: 6; stroke-linecap: round; }
.fp-strip-led { fill: #c9cacd; }
.fp-strip-led-on { fill: #5ad7f0; filter: drop-shadow(0 0 4px #5ad7f0); }
.fp-outlet:hover .fp-hit { stroke: rgba(0,90,220,.55); }
.fp-outlet:focus-visible .fp-hit { stroke: #0058e0; fill: rgba(0,88,224,.14); }
.fp-outlet-state { fill: #8d8e93; }
@@ -1095,6 +1102,9 @@ polygon.fp-led-off { fill: #6b6c71; }
.cs-chip-bad { border-color: var(--status-critical, #e0312b); }
.cs-chip-bad b { color: var(--status-critical, #e0312b); }
.cs-chip-warn b { color: var(--accent-amber, #f0a020); }
.cs-portname-group { margin: 0 0 12px; }
.cs-portname-group > summary { cursor: pointer; list-style-position: inside; margin-bottom: 8px; }
.cs-portname-group code { white-space: nowrap; }
.cs-filters { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-bottom: 10px; }
.cs-filters .lt-input { flex: 1 1 240px; min-width: 0; }
.cs-filters .lt-select { flex: 0 1 180px; }
@@ -1652,6 +1662,7 @@ body.fp-marks-off .fp-svg .fp-mark { display: none; }
.tp-outlet-watts { font-family: var(--font); font-size: 24px; fill: #e0a400; }
.tp-outlet-free .tp-outlet-target { fill: var(--text-muted); font-style: italic; }
.tp-outlet-off .tp-outlet-watts, .tp-outlet-off .tp-outlet-target { fill: #ff6b5e; }
.tp-outlet-stale .tp-outlet-watts { fill: var(--text-muted, #8a929c); font-style: italic; }
.tp-power-badge { font-family: var(--font); font-size: 26px; font-weight: 700; fill: #e0a400; }
.tp-power-off { fill: #ff6b5e; }
.tp-feeds { pointer-events: none; }
+50 -10
View File
@@ -103,6 +103,12 @@ function problemsOf(data) {
out.push({ kind: 'node', id: n.id, severity: n.status === 'down' || n.severity === 'critical' ? 'bad' : 'warn',
text: `${n.name}: ${bits.join(', ')}` });
});
(data.power || []).forEach(src => {
if (src.stale_since) {
out.push({ kind: 'node', id: src.node, severity: 'warn',
text: `${src.node} outlet watts frozen since ${sinceText(src.stale_since)}; its total is live` });
}
});
(data.power || []).forEach(src => src.outlets.forEach(o => {
if (o.on || !o.target) return;
const down = (byId[o.target] || {}).status === 'down';
@@ -132,6 +138,17 @@ function problemsOf(data) {
return out;
}
// "2026-11-14 22:48:00 UTC" as local time: just the time today, else the date and time
function sinceText(utc) {
const d = new Date(String(utc).replace(' UTC', 'Z').replace(' ', 'T'));
if (Number.isNaN(d.getTime())) return String(utc);
const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
return d.toDateString() === new Date().toDateString() ? time : `${d.toLocaleDateString()} ${time}`;
}
const STALE_TIP = 'UniFi has been sending the same outlet readings for a long time, so these watts are not live. '
+ 'The unit\'s total is still live.';
function speedClass(mbps) {
if (mbps >= 10000) return 'tp-s-10g';
if (mbps >= 1000) return 'tp-s-1g';
@@ -370,7 +387,7 @@ function artFor(node) {
case 'stub': return node.via && node.via.kind === 'patch_panel' ? patchPanelDrawing(node) : stubDrawing();
case 'group': return groupDrawing(node);
case 'ap': return apDrawing(node);
case 'strip': return stripDrawing(node);
case 'strip': return spec ? faceplateDrawing(node, node.model, 1100) : stripDrawing(node);
default:
if (spec && DESK_FACEPLATES[node.model]) return deskFaceplate(node);
if (spec) return faceplateDrawing(node, node.model, 1100, { rack: node.kind === 'ups', crop: !node.power });
@@ -476,14 +493,15 @@ function cardFor(node, linksByIface) {
const y = CARD_H + i * ROW_H;
rows[o.index] = y + ROW_H / 2;
const what = o.target || (o.match === 'cleared' ? 'nothing' : 'unassigned');
const cls = `tp-outlet-row${o.on ? '' : ' tp-outlet-off'}${o.target ? '' : ' tp-outlet-free'}`;
const tip = `${node.name} outlet ${o.index}${o.name ? ` "${o.name}"` : ''} · ${o.on ? 'on' : 'off'}${o.power_w != null ? ` · ${wattText(o.power_w)}` : ''} · feeds ${what}${o.match === 'saved' ? ' (set here)' : o.match === 'name' ? ' (from its name)' : o.match === 'mac' ? ' (from the MAC in its name)' : ''}${TOPO_CAN_EDIT ? ' · click to change' : ''}`;
const cls = `tp-outlet-row${o.on ? '' : ' tp-outlet-off'}${o.target ? '' : ' tp-outlet-free'}${o.stale ? ' tp-outlet-stale' : ''}`;
const tip = `${node.name} outlet ${o.index}${o.name ? ` "${o.name}"` : ''} · ${o.on ? 'on' : 'off'}${o.power_w != null ? ` · ${wattText(o.power_w)}${o.stale ? ' (stale)' : ''}` : ''} · feeds ${what}${o.match === 'saved' ? ' (set here)' : o.match === 'name' ? ' (from its name)' : o.match === 'mac' ? ' (from the MAC in its name)' : ''}${TOPO_CAN_EDIT ? ' · click to change' : ''}`;
const staleTip = o.stale ? ` · ${STALE_TIP}` : '';
return `<g class="${cls}" data-outlet-source="${esc(node.name)}" data-outlet="${o.index}"${TOPO_CAN_EDIT ? ' role="button" tabindex="0"' : ''}>
<title>${esc(tip)}</title>
<title>${esc(tip + staleTip)}</title>
<rect class="tp-outlet-hit" x="16" y="${y + 4}" width="${w - 32}" height="${ROW_H - 8}" rx="8"/>
<text class="tp-outlet-idx" x="34" y="${y + 31}">${o.index}</text>
<text class="tp-outlet-target" x="96" y="${y + 31}">${esc(what.length > 22 ? `${what.slice(0, 21)}…` : what)}</text>
<text class="tp-outlet-watts" x="${w - 34}" y="${y + 31}" text-anchor="end">${o.on ? esc(wattText(o.power_w)) : 'off'}</text>
<text class="tp-outlet-watts" x="${w - 34}" y="${y + 31}" text-anchor="end">${!o.on ? 'off' : o.stale ? 'stale' : esc(wattText(o.power_w))}</text>
</g>`;
}).join('');
h = CARD_H + list.length * ROW_H + (list.length ? 16 : 0);
@@ -492,9 +510,12 @@ function cardFor(node, linksByIface) {
let badge = '';
if ((node.power_in || []).length) {
const off = node.power_in.some(f => !f.on);
const stale = node.power_in.some(f => f.stale);
const watts = node.power_in.reduce((t, f) => t + (f.power_w || 0), 0);
const tip = node.power_in.map(f => `${f.source} outlet ${f.outlet}${f.on ? '' : ' (off)'}${f.power_w != null ? ` · ${wattText(f.power_w)}` : ''}`).join('; ');
badge = `<text class="tp-power-badge${off ? ' tp-power-off' : ''}" x="${w - 34}" y="108" text-anchor="end"><title>${esc(`Fed by ${tip}`)}</title>⚡ ${off ? 'off' : esc(wattText(watts) || 'fed')}</text>`;
const tip = node.power_in.map(f => `${f.source} outlet ${f.outlet}${f.on ? '' : ' (off)'}${f.power_w != null ? ` · ${wattText(f.power_w)}${f.stale ? ' (stale)' : ''}` : ''}`).join('; ');
// A frozen reading is not shown as if it were live
const text = off ? 'off' : stale ? 'fed' : (wattText(watts) || 'fed');
badge = `<text class="tp-power-badge${off ? ' tp-power-off' : ''}" x="${w - 34}" y="108" text-anchor="end"><title>${esc(`Fed by ${tip}${stale ? `. ${STALE_TIP}` : ''}`)}</title>⚡ ${esc(text)}</text>`;
}
const maxChars = Math.floor((w - 130) / 27);
const name = node.name.length > maxChars ? `${node.name.slice(0, maxChars - 1)}…` : node.name;
@@ -953,6 +974,23 @@ function endHtml(end, byId) {
return `${name}${where ? ` · ${where}` : ''}`;
}
// A link to the cutsheet's new-cable form, filled in with both ends as Gandalf sees them
function documentLink(link, byId) {
if (!TOPO_CAN_EDIT || link.ghost || link.bundle) return '';
const sw = [link.a, link.b].find(e => e.port_idx != null && (byId[e.node] || {}).kind !== 'stub');
if (!sw) return '';
const far = sw === link.a ? link.b : link.a;
const farNode = byId[far.node] || {};
const q = new URLSearchParams({ a_device: sw.node, a_port: String(sw.port_idx) });
if (farNode.kind && farNode.kind !== 'stub') {
q.set('b_device', far.node);
if (far.port_idx != null) q.set('b_port', String(far.port_idx));
else if (far.iface) q.set('b_port', far.iface);
}
if (link.medium === 'dac') q.set('cable_type', 'DAC');
return ` · <a class="device-link" href="/cutsheet?${esc(q.toString())}">document it</a>`;
}
function showPanel(link) {
const byId = Object.fromEntries(state.data.nodes.map(n => [n.id, n]));
const panel = document.getElementById('tp-panel');
@@ -980,7 +1018,7 @@ function showPanel(link) {
? `<br><span class="tp-dim-text">into ${esc(far.device)}${far.port ? ` port ${esc(far.port)}` : ''}</span>` : '';
row('Cutsheet', `<a class="device-link" href="/cutsheet#cable-${esc(link.cable.id)}">${esc(label)}</a>${link.cable.type ? ` · ${esc(link.cable.type)}` : ''}${link.cable.color ? ` · ${esc(link.cable.color)}` : ''}${to}`);
} else if (!link.wan) {
row('Cutsheet', '<span class="tp-dim-text">not documented</span>');
row('Cutsheet', `<span class="tp-dim-text">not documented</span>${documentLink(link, byId)}`);
}
const warn = link.name_mismatch
? `<p class="tp-panel-warn">⚠ The port is named after <strong>${esc(link.name_mismatch.named)}</strong>, but <strong>${esc(link.name_mismatch.actual)}</strong> is plugged into it. Rename the port in UniFi, or check the cable.</p>`
@@ -1045,10 +1083,12 @@ function drawFeeds(id) {
const c = Math.max(160, Math.abs(from.x - B.x) * 0.4);
const d = `M${from.x} ${from.y} C${from.x - c} ${from.y} ${B.x + c} ${B.y} ${B.x} ${B.y}`;
const mx = (from.x + B.x) / 2, my = (from.y + B.y) / 2;
const text = `⚡ ${target} ${!o.on ? 'off' : o.stale ? '(watts stale)' : wattText(o.power_w)}`;
const tw = Math.max(300, text.length * 15 + 40);
return `<g class="tp-feed${o.on ? '' : ' tp-feed-off'}"><path d="${d}"/>
<circle cx="${B.x}" cy="${B.y}" r="10"/>
<g class="tp-tag tp-feed-tag" transform="translate(${mx} ${my})"><rect x="-150" y="-26" width="300" height="44" rx="22"/>
<text y="6" text-anchor="middle">⚡ ${esc(target)} ${o.on ? esc(wattText(o.power_w)) : 'off'}</text></g></g>`;
<g class="tp-tag tp-feed-tag" transform="translate(${mx} ${my})"><rect x="${-tw / 2}" y="-26" width="${tw}" height="44" rx="22"/>
<text y="6" text-anchor="middle">${esc(text)}</text></g></g>`;
}).join('');
// Everything at either end of a feed stays lit while the path is traced
return new Set(pairs.flatMap(p => [p.target, ...((state.data.power || []).filter(src => src.outlets.includes(p.o)).map(src => src.node))]));
+9
View File
@@ -47,6 +47,15 @@
<div id="cs-suggestions"></div>
</section>
<section class="g-section no-print" id="cs-portnames-section">
<div class="g-section-header">
<h2 class="g-section-title">Port names in UniFi</h2>
<span class="g-section-badge" id="cs-portnames-count">0</span>
</div>
<p class="cs-hint">Switch port names that no longer fit what is plugged in, as a checklist. Rename them in UniFi: Gandalf only reports them and never changes UniFi.</p>
<div id="cs-portnames"></div>
</section>
<section class="g-section" id="cs-panels-section">
<div class="g-section-header">
<h2 class="g-section-title">Patch panels</h2>
+1
View File
@@ -217,6 +217,7 @@ class TestCutsheetApi:
assert view['next_label'] == 'C01'
assert view['labels']['cables'][0]['text'] == 'C07'
assert any(d['name'] == 'PP1' for d in view['catalog'])
assert isinstance(view['port_names'], list)
def test_create_cable(self, cs_client):
client, db = cs_client
+46
View File
@@ -485,6 +485,52 @@ class TestWanIncident:
assert not mon.tickets.create.called and not mon.tickets.comment.called
class TestStaleOutletReadings:
@staticmethod
def _pdu(w1=20.622, w2=0.0):
return {'RPDU': {'outlets': [
{'index': 1, 'power_w': w1, 'current_a': 0.322},
{'index': 2, 'power_w': w2, 'current_a': 0.0},
{'index': 3, 'power_w': None, 'current_a': None}, # USB: never metered
]}}
def _collector(self):
c = monitor.LinkStatsCollector.__new__(monitor.LinkStatsCollector)
c._outlet_readings = {}
return c
def test_readings_frozen_past_the_limit_are_stale(self):
c = self._collector()
c._mark_stale_outlets(self._pdu(), 1000.0)
later = self._pdu()
c._mark_stale_outlets(later, 1000.0 + c.OUTLET_STALE_AFTER_S)
assert later['RPDU']['outlets_stale_since'] == '1970-01-01 00:16:40 UTC'
assert [o.get('stale') for o in later['RPDU']['outlets']] == [True, True, None]
def test_moving_readings_are_live(self):
c = self._collector()
c._mark_stale_outlets(self._pdu(), 1000.0)
c._mark_stale_outlets(self._pdu(w1=21.0), 1000.0 + c.OUTLET_STALE_AFTER_S - 1)
later = self._pdu(w1=21.0)
c._mark_stale_outlets(later, 1000.0 + c.OUTLET_STALE_AFTER_S + 60)
assert 'outlets_stale_since' not in later['RPDU']
assert not any(o.get('stale') for o in later['RPDU']['outlets'])
def test_idle_outlets_reading_zero_are_not_stale(self):
c = self._collector()
c._mark_stale_outlets(self._pdu(w1=0.0), 1000.0)
later = self._pdu(w1=0.0)
c._mark_stale_outlets(later, 1000.0 + 10 * c.OUTLET_STALE_AFTER_S)
assert 'outlets_stale_since' not in later['RPDU']
def test_unmetered_strip_is_left_alone(self):
c = self._collector()
strip = {'USP Strip': {'outlets': [{'index': 1, 'power_w': None}]}}
c._mark_stale_outlets(strip, 1000.0)
c._mark_stale_outlets(strip, 1000.0 + 10 * c.OUTLET_STALE_AFTER_S)
assert 'outlets_stale_since' not in strip['USP Strip'] and 'USP Strip' not in c._outlet_readings
class TestUnifiDeviceDetail:
def test_parses_string_stats_and_outlets(self):
d = monitor.UnifiClient._device_detail({
+75 -1
View File
@@ -403,12 +403,86 @@ class TestPower:
def test_devices_know_what_feeds_them(self):
g = self._graph()
assert node(g, 'host-c')['power_in'] == [{'source': 'RPDU', 'outlet': 16, 'on': True, 'power_w': 131.7}]
assert node(g, 'host-c')['power_in'] == [{'source': 'RPDU', 'outlet': 16, 'on': True, 'power_w': 131.7,
'stale': False}]
assert node(g, 'host-b')['power_in'] == []
def test_frozen_readings_are_passed_on_as_stale(self):
snapshot, link_stats, modem = network()
link_stats['unifi_devices']['RPDU']['outlets'] = [
dict(o, stale=True) if o.get('power_w') is not None else o for o in self.OUTLETS]
link_stats['unifi_devices']['RPDU']['outlets_stale_since'] = '2026-11-14 22:48:00 UTC'
link_stats['host_macs'] = {'02:00:5e:00:0a:01': ['host-c', 'nic0']}
g = topology.build_graph(snapshot, link_stats, modem, [], [], [], None, [])
src = next(s for s in g['power'] if s['node'] == 'RPDU')
assert src['stale_since'] == '2026-11-14 22:48:00 UTC'
assert src['outlets'][[o['index'] for o in src['outlets']].index(16)]['stale'] is True
assert node(g, 'host-c')['power_in'][0]['stale'] is True
assert next(s for s in g['power'] if s['node'] == 'UPS 2U Pro')['stale_since'] is None
def test_a_power_device_does_not_feed_itself(self):
out = self._outlets(self._graph(outlets=[{'index': 1, 'name': 'RPDU spare', 'on': True}]))
assert out[1]['target'] is None
def test_every_power_device_is_listed(self):
assert [s['node'] for s in self._graph()['power']] == ['RPDU', 'UPS 2U Pro', 'USP Strip']
class TestPortNameReport:
def _report(self, poe_port_11='Port 11', pbs_up=True, extra=(), known=None):
snapshot, link_stats, modem = network(poe_port_11, pbs_up)
link_stats['unifi_switches']['24RJ45-POE']['ports'].update(dict(extra))
return topology.port_name_report(snapshot, link_stats, modem, known)
def _row(self, rows, sw, idx):
return next((r for r in rows if r['switch'] == sw and r['port_idx'] == idx), None)
def test_named_after_the_wrong_device(self):
rows = self._report(poe_port_11='Host-A Management')
r = self._row(rows, '24RJ45-POE', 11)
assert r['kind'] == 'wrong' and r['suggestion'] == 'AP'
assert r['detail'] == ('Named after host-a, but AP is plugged in; '
'host-a is on 8SFP-AGG port 1, Dream Machine Pro port 1')
assert rows[0] is r # the most urgent kind comes first
def test_named_after_a_device_that_moved(self):
rows = self._report(extra=[port(20, 'host-c', up=False)])
r = self._row(rows, '24RJ45-POE', 20)
assert r['kind'] == 'moved' and r['suggestion'] == 'Port 20'
assert r['detail'] == 'Named after host-c, which is now on 8SFP-AGG port 8'
def test_named_but_empty_says_who_was_last_seen(self):
known = {'pbs': {'uplinks': [{'switch': '24RJ45-POE', 'port_idx': 7}], 'seen': '2026-11-01 10:00:00 UTC'}}
rows = self._report(extra=[port(7, 'Guest Bedroom', up=False)], known=known)
r = self._row(rows, '24RJ45-POE', 7)
assert r['kind'] == 'empty' and r['suggestion'] == ''
assert r['detail'] == ('Nothing plugged in; last seen here: pbs (2026-11-01 10:00:00 UTC), '
'now on 24RJ45-POE port 15')
def test_unnamed_ports_get_a_suggestion(self):
rows = self._report()
# A server with two cables gets its NIC in the name; a switch-to-switch port is a downlink
assert self._row(rows, '24RJ45-POE', 4)['suggestion'] == 'host-b enp2s0'
assert self._row(rows, '24RJ45-POE', 19)['suggestion'] == 'RPDU'
assert self._row(rows, '8SFP-AGG', 7)['suggestion'] == 'Uplink'
assert self._row(rows, '8SFP-AGG', 8)['suggestion'] == 'host-c'
assert {r['kind'] for r in rows} == {'unnamed'}
def test_good_names_and_unknown_devices_are_left_alone(self):
rows = self._report()
for sw, idx in [('24RJ45-POE', 15), # "PBS" with pbs plugged in
('24RJ45-POE', 3), # "Living Room Downlink" to the Flex
('8SFP-AGG', 5), # "Downlink to 24RJ45-POE"
('24RJ45-POE', 1), # a custom name over an unknown device
('24RJ45-POE', 8), # an IP-only target
('24RJ45-POE', 12), # "Port 12", nothing plugged in
('RPDU', 1)]: # a PDU's management port
assert self._row(rows, sw, idx) is None, (sw, idx)
def test_a_port_named_after_a_device_that_is_off_is_right(self):
rows = self._report(pbs_up=False)
for sw, idx in [('24RJ45-POE', 15)]: # "PBS" while pbs is down
assert self._row(rows, sw, idx) is None, (sw, idx)
def test_no_data(self):
assert topology.port_name_report({}, {}, None) == []
+103 -5
View File
@@ -135,6 +135,99 @@ def _named_device(text: str, known: Dict[str, str], skip=()) -> Optional[str]:
return None
# What each port-name finding means, most urgent first
PORT_NAME_KINDS = ('wrong', 'moved', 'empty', 'unnamed')
def _port_name_suggestion(neighbour: str, kind: str, port: dict, links: int) -> str:
if kind in ('router', 'switch'):
return 'Uplink' if port.get('is_uplink') else f'Downlink to {neighbour}'
iface = str((port.get('lldp') or {}).get('port_id') or '')
# A server with two cables: say which NIC, so the two ports read differently
if kind == 'host' and links > 1 and iface and not _MAC_IN_TEXT.fullmatch(iface):
return f'{neighbour} {iface}'
return neighbour
def port_name_report(snapshot: dict, link_stats: dict, modem: Optional[dict],
known_uplinks: Optional[dict] = None) -> List[dict]:
"""UniFi port names that no longer fit what is plugged in, as a checklist to fix in UniFi.
Each row is {switch, port_idx, port_name, kind, neighbour, suggestion, detail}, kind one of:
wrong: named after one device, with a different known device plugged in
moved: named after a device that is now linked on another port, with nothing known here
empty: a custom name on a port with nothing plugged in (with who was last seen there)
unnamed: still "Port N" / "SFP+ N" with a known device plugged in
Gandalf only reports these; it never renames anything in UniFi.
"""
snapshot = snapshot or {}
link_stats = link_stats or {}
switches = link_stats.get('unifi_switches') or {}
configured = set(snapshot.get('hosts') or {})
kinds = {e['name']: e['kind'] for e in devices.build_index(snapshot, link_stats, modem)
if e['kind'] != 'host' or e['name'] in configured}
known = {_norm(n): n for n in kinds}
# Where each known device is linked right now, and who was last seen on each port
live_at: Dict[str, List[str]] = {}
for sw_name, sw in sorted(switches.items()):
for p in (sw.get('ports') or {}).values():
nb = (p.get('lldp') or {}).get('system_name') or ''
if p.get('up') and nb in kinds and p.get('port_idx') is not None:
live_at.setdefault(nb, []).append(f'{sw_name} port {p["port_idx"]}')
last_seen: Dict[Tuple[str, int], Tuple[str, str]] = {}
for name, entry in (known_uplinks or {}).items():
for up in (entry or {}).get('uplinks') or []:
if up.get('switch') and up.get('port_idx') is not None:
last_seen[(up['switch'], up['port_idx'])] = (name, (entry or {}).get('seen') or '')
rows: List[dict] = []
for sw_name in sorted(switches):
if kinds.get(sw_name) in POWER_KINDS or _POWER_MODELS.get((switches[sw_name] or {}).get('model', '')):
continue # a PDU's one management port
for pname, port in (switches[sw_name].get('ports') or {}).items():
idx = port.get('port_idx')
if idx is None:
continue
nb = (port.get('lldp') or {}).get('system_name') or ''
nb = nb if nb in kinds and nb != sw_name else ''
generic = _is_generic_port_name(pname)
row = {'switch': sw_name, 'port_idx': idx, 'port_name': pname, 'neighbour': nb,
'suggestion': '', 'detail': ''}
named = None if generic else _named_device(pname, known, {_norm(sw_name)})
if nb and port.get('up'):
suggestion = _port_name_suggestion(nb, kinds[nb], port, len(live_at.get(nb, [])))
if named and named != nb and _norm(named) != _norm(nb):
elsewhere = [w for w in live_at.get(named, []) if w != f'{sw_name} port {idx}']
row.update(kind='wrong', suggestion=suggestion,
detail=f'Named after {named}, but {nb} is plugged in'
+ (f'; {named} is on {", ".join(elsewhere)}' if elsewhere else ''))
elif generic and not pname.lower().startswith(('uplink', 'downlink')):
row.update(kind='unnamed', suggestion=suggestion,
detail=f'{nb} is plugged in')
else:
continue
elif named and named in live_at:
row.update(kind='moved', suggestion=f'Port {idx}' if not port.get('up') else '',
detail=f'Named after {named}, which is now on {", ".join(live_at[named])}')
elif named:
continue # named after a known device that is just not linked now: the name is right
elif not generic and not port.get('up') and not port.get('lldp'):
seen = last_seen.get((sw_name, idx))
detail = 'Nothing plugged in'
if seen:
detail += f'; last seen here: {seen[0]}' + (f' ({seen[1]})' if seen[1] else '')
if seen[0] in live_at:
detail += f', now on {", ".join(live_at[seen[0]])}'
row.update(kind='empty', detail=detail)
else:
continue
rows.append(row)
order = {k: i for i, k in enumerate(PORT_NAME_KINDS)}
rows.sort(key=lambda r: (order[r['kind']], r['switch'].lower(), r['port_idx']))
return rows
_MAC_IN_TEXT = re.compile(r'\b([0-9a-f]{2}(?:[:-][0-9a-f]{2}){5})\b', re.IGNORECASE)
@@ -144,8 +237,9 @@ def build_power(nodes: Dict[str, dict], link_stats: dict, feeds: List[dict]) ->
In order: an assignment saved on the topology page (target '' means nothing), then the
outlet's name if it names a device ("storage-01", "Dream Machine Pro", or "AT&T Modem" for
the modem), then a MAC in its name that belongs to a host NIC or a UniFi device.
Returns [{node, power_w, outlets: [{index, name, on, power_w, auto_power_cycle, target,
match: saved|cleared|name|mac|none}]}].
Returns [{node, power_w, stale_since, outlets: [{index, name, on, power_w, stale,
auto_power_cycle, target, match: saved|cleared|name|mac|none}]}]. stale_since is set when
the monitor saw the unit's outlet readings stop changing (UniFi serving a frozen snapshot).
"""
known = {_norm(n['name']): n['name'] for n in nodes.values() if n['kind'] not in ('stub', 'internet')}
modem = next((n['name'] for n in nodes.values() if n['kind'] == 'modem'), None)
@@ -181,9 +275,11 @@ def build_power(nodes: Dict[str, dict], link_stats: dict, feeds: List[dict]) ->
target = macs.get(m.group(1).lower().replace('-', ':')) if m else None
how = 'mac' if target else 'none'
rows.append({'index': idx, 'name': text, 'on': o.get('on') is not False,
'power_w': o.get('power_w'), 'auto_power_cycle': bool(o.get('auto_power_cycle')),
'power_w': o.get('power_w'), 'stale': bool(o.get('stale')),
'auto_power_cycle': bool(o.get('auto_power_cycle')),
'target': target, 'match': how})
sources.append({'node': node['name'], 'power_w': node.get('power_w'), 'outlets': rows})
sources.append({'node': node['name'], 'power_w': node.get('power_w'), 'outlets': rows,
'stale_since': node.get('outlets_stale_since')})
return sources
@@ -289,6 +385,7 @@ def build_graph(snapshot: dict, link_stats: dict, modem: Optional[dict], events:
info = unifi_info.get(name) or {}
node['power_w'] = info.get('power_w')
node['outlets'] = info.get('outlets') or []
node['outlets_stale_since'] = info.get('outlets_stale_since')
node_alerts = alerts.get(name, [])
node['alerts'] = node_alerts[:10]
node['alert_count'] = len(node_alerts)
@@ -487,7 +584,8 @@ def build_graph(snapshot: dict, link_stats: dict, modem: Optional[dict], events:
for o in src['outlets']:
if o['target'] in nodes:
nodes[o['target']]['power_in'].append(
{'source': src['node'], 'outlet': o['index'], 'on': o['on'], 'power_w': o['power_w']})
{'source': src['node'], 'outlet': o['index'], 'on': o['on'], 'power_w': o['power_w'],
'stale': o['stale']})
if not switches:
warnings.append('No UniFi switch data yet: the monitor has not reported any ports')