Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60d892badb | ||
|
|
206175df39 | ||
|
|
b9e008bc2b | ||
|
|
ab59b42bea |
No files matched your search
+27
@@ -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 {
|
||||
|
||||
+6
-2
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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; }
|
||||
@@ -1495,6 +1502,12 @@ body.fp-marks-off .fp-svg .fp-mark { display: none; }
|
||||
.tp-stub-q { font-family: var(--font); font-size: 30px; font-weight: 700; fill: #9aa3ad; }
|
||||
.tp-st-down .tp-stub-body { stroke: #e0312b; }
|
||||
.tp-stub-jack.tp-off { opacity: .4; }
|
||||
.tp-pp-body { fill: #2b2f35; stroke: #1b1e22; stroke-width: 3; }
|
||||
.tp-pp-jack rect { fill: #121417; stroke: #4a5059; stroke-width: 2; }
|
||||
.tp-pp-jack.tp-pp-used rect { fill: #121417; stroke: #4aa3ff; stroke-width: 4; }
|
||||
.tp-pp-num { font-family: var(--font); font-size: 18px; fill: #8a929c; }
|
||||
.tp-pp-used .tp-pp-num { fill: #cfe6ff; font-weight: 700; }
|
||||
.tp-st-down .tp-pp-body { stroke: #e0312b; }
|
||||
.tp-group-body { stroke-dasharray: 10 8; stroke: #5d6670; }
|
||||
.tp-group-hint { font-family: var(--font); font-size: 20px; fill: #9aa3ad; }
|
||||
.tp-select { font-size: .95em; padding: 1px 4px; margin-left: 4px; }
|
||||
@@ -1646,6 +1659,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; }
|
||||
|
||||
+90
-14
@@ -19,7 +19,10 @@ const state = {
|
||||
filters: loadFilters(),
|
||||
expanded: new Set(), // switches whose unknown devices are shown one by one
|
||||
selected: null,
|
||||
pinned: null, // the device a touch screen tapped to trace
|
||||
};
|
||||
// Whether the last press was a mouse, pen or finger: touch has no hover, so taps trace instead
|
||||
let lastPointer = 'mouse';
|
||||
|
||||
function loadFilters() {
|
||||
try {
|
||||
@@ -100,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';
|
||||
@@ -129,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';
|
||||
@@ -323,6 +343,24 @@ function stubDrawing() {
|
||||
};
|
||||
}
|
||||
|
||||
// The far end of a cable the cutsheet says goes into a patch panel: the panel's row of jacks,
|
||||
// with the cable landing on its documented port
|
||||
function patchPanelDrawing(node) {
|
||||
const n = 24, pitch = 42, w = 80 + n * pitch, h = 130;
|
||||
const used = Number(node.via.port);
|
||||
const jacks = Array.from({ length: n }, (_, i) => {
|
||||
const x = 40 + i * pitch + 6;
|
||||
const on = i + 1 === used;
|
||||
return `<g class="tp-pp-jack${on ? ' tp-pp-used' : ''}"><rect x="${x}" y="46" width="30" height="34" rx="3"/>
|
||||
<text class="tp-pp-num" x="${x + 15}" y="108" text-anchor="middle">${i + 1}</text></g>`;
|
||||
}).join('');
|
||||
return {
|
||||
w, h,
|
||||
svg: `<rect class="tp-pp-body" x="0" y="20" width="${w}" height="${h - 20}" rx="8"/>${jacks}`,
|
||||
anchor: () => (used >= 1 && used <= n ? { x: 40 + (used - 1) * pitch + 21, y: 46, face: 'top' } : { x: w / 2, y: 20, face: 'top' }),
|
||||
};
|
||||
}
|
||||
|
||||
// A host's drawn front, from its cutsheet item's Front drawing
|
||||
function hostFront(node) {
|
||||
const ctx = { name: node.name, status: node.status, interfaces: node.interfaces || [] };
|
||||
@@ -346,10 +384,10 @@ function artFor(node) {
|
||||
switch (node.kind) {
|
||||
case 'internet': return internetDrawing();
|
||||
case 'modem': return modemDrawing(node);
|
||||
case 'stub': return stubDrawing();
|
||||
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 });
|
||||
@@ -433,7 +471,8 @@ function cardFor(node, linksByIface) {
|
||||
band = `${art}${sockets.svg}`;
|
||||
anchorAt = end => (end.iface && sockets.pos[end.iface]) || null;
|
||||
} else {
|
||||
const small = ['internet', 'modem', 'stub', 'group', 'ap', 'strip'].includes(node.kind);
|
||||
const panel = node.kind === 'stub' && node.via && node.via.kind === 'patch_panel';
|
||||
const small = !panel && ['internet', 'modem', 'stub', 'group', 'ap', 'strip'].includes(node.kind);
|
||||
w = Math.max(small ? CARD_SMALL_W : CARD_W, Math.min(node.name.length * 27 + 130, 980));
|
||||
const art = artFor(node);
|
||||
const f = fitArt(art, 28, BAND_Y, w - 56, BAND_H);
|
||||
@@ -454,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);
|
||||
@@ -470,14 +510,19 @@ 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;
|
||||
let sub;
|
||||
if (node.kind === 'group') sub = `on ${node.switch}`;
|
||||
else if (node.kind === 'stub' && node.named_by_via) sub = `${node.via.cable ? `${node.via.cable} · ` : ''}device beyond it unknown`;
|
||||
else if (node.kind === 'stub' && node.via) sub = `via ${node.via.name}`;
|
||||
else if (node.kind === 'stub') sub = node.ip ? `${node.switch} port ${node.port_idx}` : (node.mac || `${node.switch} port ${node.port_idx}`);
|
||||
else if (node.kind === 'host') sub = node.status === 'up' ? 'server' : `server · ${node.status}`;
|
||||
else if (node.kind === 'internet') sub = node.status === 'up' ? 'connected' : node.status;
|
||||
@@ -846,7 +891,10 @@ function renderNode(node, lay) {
|
||||
<g class="tp-badge tp-badge-${esc(node.severity)}" transform="translate(${d.w - 6} 6)"><circle r="30"/><text y="11" text-anchor="middle">${node.alert_count}</text></g>`
|
||||
: '';
|
||||
const alertText = (node.alerts || []).map(a => `${a.severity}: ${a.type.replace(/_/g, ' ')}${a.detail ? ` ${a.detail}` : ''}`).join('; ');
|
||||
const label = `${node.name}${node.kind === 'stub' ? ' (not identified)' : ''} · ${node.status}${alertText ? ` · ${alertText}` : ''}`;
|
||||
const what = node.kind !== 'stub' ? ''
|
||||
: node.named_by_via ? ` (${node.via.device}; what is patched in beyond it is not identified)`
|
||||
: ` (not identified${node.via ? `; via ${node.via.name}` : ''})`;
|
||||
const label = `${node.name}${what} · ${node.status}${alertText ? ` · ${alertText}` : ''}`;
|
||||
const open = node.kind === 'group'
|
||||
? `<g class="tp-node-link" tabindex="0" role="button" data-expand="${esc(node.switch)}" aria-label="${esc(`${node.name} on ${node.switch}: show them`)}">`
|
||||
: (href ? `<a class="tp-node-link" href="${esc(href)}" aria-label="${esc(label)}">` : `<g class="tp-node-link" tabindex="0" aria-label="${esc(label)}">`);
|
||||
@@ -902,6 +950,11 @@ function render() {
|
||||
if (link) showPanel(link);
|
||||
else hidePanel();
|
||||
}
|
||||
// A refresh redraws everything: keep a tapped device traced
|
||||
if (state.pinned) {
|
||||
if (lay.pos[state.pinned]) highlight(state.pinned);
|
||||
else state.pinned = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cable panel ─────────────────────────────────────────────────────────
|
||||
@@ -943,7 +996,10 @@ function showPanel(link) {
|
||||
}
|
||||
if (link.cable) {
|
||||
const label = link.cable.label || `cable #${link.cable.id}`;
|
||||
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)}` : ''}`);
|
||||
const far = link.cable.far;
|
||||
const to = far && far.device && !byId[far.device]
|
||||
? `<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>');
|
||||
}
|
||||
@@ -1010,10 +1066,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))]));
|
||||
@@ -1169,6 +1227,22 @@ function initEvents() {
|
||||
return;
|
||||
}
|
||||
if (!e.target.closest('#tp-pop')) closeOutletEditor();
|
||||
// A touch screen has no hover: the first tap on a device traces it (its path to the internet
|
||||
// and its power feeds), a second tap opens it
|
||||
const tapped = e.target.closest('.tp-node');
|
||||
if (lastPointer === 'touch') {
|
||||
const id = tapped && tapped.querySelector('a.tp-node-link') ? tapped.dataset.node : null;
|
||||
if (id && state.pinned !== id && !e.target.closest('[data-action="select-port"]')) {
|
||||
e.preventDefault();
|
||||
state.pinned = id;
|
||||
highlight(id);
|
||||
return;
|
||||
}
|
||||
if (!tapped) {
|
||||
state.pinned = null;
|
||||
highlight(null);
|
||||
}
|
||||
}
|
||||
const port = e.target.closest('[data-action="select-port"]');
|
||||
if (port) {
|
||||
e.preventDefault();
|
||||
@@ -1212,12 +1286,14 @@ function initEvents() {
|
||||
}
|
||||
});
|
||||
const trace = e => {
|
||||
if (lastPointer === 'touch') return; // taps trace in the click handler instead
|
||||
const node = e.target.closest('.tp-node');
|
||||
highlight(node ? node.dataset.node : null);
|
||||
};
|
||||
svg.addEventListener('pointerdown', e => { lastPointer = e.pointerType; }, true);
|
||||
svg.addEventListener('mouseover', trace);
|
||||
svg.addEventListener('focusin', trace);
|
||||
svg.addEventListener('mouseleave', () => highlight(null));
|
||||
svg.addEventListener('mouseleave', () => { if (lastPointer !== 'touch') highlight(null); });
|
||||
svg.addEventListener('focusout', e => { if (!svg.contains(e.relatedTarget)) highlight(null); });
|
||||
|
||||
document.getElementById('tp-pop').addEventListener('click', e => {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<div class="lt-page-header">
|
||||
<div>
|
||||
<h1 class="lt-page-title">Topology</h1>
|
||||
<p class="g-page-sub">Every device and cable as the switches see them right now. Drag to pan, scroll or pinch to zoom. Hover a device to trace its path to the internet; click a cable for its details, or a group of unknown devices to open it.</p>
|
||||
<p class="g-page-sub">Every device and cable as the switches see them right now. Drag to pan, scroll or pinch to zoom. Hover a device to trace its path to the internet and its power (on a touch screen, tap it once to trace and again to open it); click a cable for its details, or a group of unknown devices to open it.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
+41
-2
@@ -326,10 +326,35 @@ class TestCutsheetLabels:
|
||||
'b_port': '', 'status': 'retired'}]
|
||||
g = build(items=items, cables=cables)
|
||||
(stub,) = find(g, 'Dream Machine Pro', 'stub:Dream Machine Pro:8')
|
||||
assert stub['cable'] == {'id': 7, 'label': 'C07', 'type': 'Cat6', 'color': 'Black'}
|
||||
assert stub['cable'] == {'id': 7, 'label': 'C07', 'type': 'Cat6', 'color': 'Black',
|
||||
'far': {'device': 'Patch', 'port': '1', 'kind': ''}}
|
||||
# Retired cables are not on the network any more
|
||||
assert find(g, 'Dream Machine Pro', 'host-a')[0]['cable'] is None
|
||||
|
||||
def test_unknown_device_behind_a_patch_panel_is_named_after_it(self):
|
||||
items = [{'name': 'PP1', 'device': '', 'kind': 'patch_panel'},
|
||||
{'name': 'UDM-Pro', 'device': 'Dream Machine Pro'}]
|
||||
cables = [{'id': 7, 'label': 'C07', 'a_device': 'UDM-Pro', 'a_port': '8', 'b_device': 'PP1',
|
||||
'b_port': '3', 'status': 'installed'}]
|
||||
stub = node(build(items=items, cables=cables), 'stub:Dream Machine Pro:8')
|
||||
assert stub['name'] == 'Patch panel port 3' and stub['named_by_via']
|
||||
assert stub['via'] == {'device': 'PP1', 'port': '3', 'kind': 'patch_panel', 'name': 'Patch panel port 3',
|
||||
'cable': 'C07'}
|
||||
|
||||
def test_a_named_stub_keeps_its_name_and_notes_the_panel(self):
|
||||
items = [{'name': 'PP1', 'device': '', 'kind': 'patch_panel'}]
|
||||
cables = [{'id': 2, 'label': 'C02', 'a_device': '24RJ45-POE', 'a_port': '1', 'b_device': 'PP1',
|
||||
'b_port': '2', 'status': 'installed'}]
|
||||
g = build(items=items, cables=cables)
|
||||
stub = node(g, 'stub:24RJ45-POE:1')
|
||||
assert stub['name'] == 'Micro 2 Eth2' and not stub.get('named_by_via')
|
||||
assert stub['via']['name'] == 'Patch panel port 2'
|
||||
|
||||
def test_a_cable_to_a_live_device_is_not_a_via(self):
|
||||
cables = [{'id': 3, 'label': 'C03', 'a_device': 'Dream Machine Pro', 'a_port': '8',
|
||||
'b_device': '8SFP-AGG', 'b_port': '1', 'status': 'installed'}]
|
||||
assert 'via' not in node(build(cables=cables), 'stub:Dream Machine Pro:8')
|
||||
|
||||
|
||||
class TestEmpty:
|
||||
def test_no_data_yet(self):
|
||||
@@ -378,9 +403,23 @@ 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
|
||||
|
||||
+33
-9
@@ -144,8 +144,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,31 +182,44 @@ 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
|
||||
|
||||
|
||||
def _cable_labels(items: List[dict], cables: List[dict]) -> Dict[Tuple[str, str], dict]:
|
||||
"""{(device, port): cable} for cutsheet cables still in place. A cable can name the
|
||||
device itself or a cutsheet item linked to it."""
|
||||
device_of = {i['name']: (i.get('device') or i['name']) for i in items or []}
|
||||
device itself or a cutsheet item linked to it. Each entry also says where the cable's
|
||||
other end goes ('far': {device, port, kind}), so a cable into a patch panel shows as one."""
|
||||
by_name = {i['name']: i for i in items or []}
|
||||
device_of = {name: (i.get('device') or name) for name, i in by_name.items()}
|
||||
out: Dict[Tuple[str, str], dict] = {}
|
||||
for c in cables or []:
|
||||
if c.get('status') == 'retired':
|
||||
continue
|
||||
for end in ('a', 'b'):
|
||||
for end, other in (('a', 'b'), ('b', 'a')):
|
||||
dev = c.get(f'{end}_device') or ''
|
||||
if not dev:
|
||||
continue
|
||||
far_dev = c.get(f'{other}_device') or ''
|
||||
ref = {'id': c.get('id'), 'label': c.get('label') or '', 'type': c.get('cable_type') or '',
|
||||
'color': c.get('color') or ''}
|
||||
'color': c.get('color') or '',
|
||||
'far': {'device': device_of.get(far_dev, far_dev), 'port': str(c.get(f'{other}_port') or ''),
|
||||
'kind': (by_name.get(far_dev) or {}).get('kind') or ''} if far_dev else None}
|
||||
for name in {dev, device_of.get(dev, dev)}:
|
||||
out[(name, str(c.get(f'{end}_port') or ''))] = ref
|
||||
return out
|
||||
|
||||
|
||||
def _via_name(far: dict) -> str:
|
||||
"""How to name the far end of a cable that leads to cutsheet gear, not a live device."""
|
||||
where = {'patch_panel': 'Patch panel', 'wall_jack': 'Wall jack'}.get(far['kind'], far['device'])
|
||||
return f'{where} port {far["port"]}' if far['port'] else where
|
||||
|
||||
|
||||
def _alerts_by_target(events: List[dict]) -> Dict[str, List[dict]]:
|
||||
out: Dict[str, List[dict]] = {}
|
||||
for ev in events or []:
|
||||
@@ -278,6 +292,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)
|
||||
@@ -392,6 +407,14 @@ def build_graph(snapshot: dict, link_stats: dict, modem: Optional[dict], events:
|
||||
'alerts': [], 'alert_count': 0, 'severity': '', 'power': False,
|
||||
}
|
||||
link = add_link(here, _end(stub_id, iface=nodes[stub_id]['iface']), port)
|
||||
# The cutsheet says the cable goes into a patch panel (or other documented gear that
|
||||
# is not on the network): say so, and name a stub that has nothing better after it
|
||||
far = (link['cable'] or {}).get('far')
|
||||
if far and far['device'] not in nodes:
|
||||
nodes[stub_id]['via'] = dict(far, name=_via_name(far), cable=link['cable']['label'])
|
||||
if label == 'unknown device':
|
||||
nodes[stub_id]['name'] = nodes[stub_id]['via']['name']
|
||||
nodes[stub_id]['named_by_via'] = True
|
||||
# A stub labelled by its port name would always "match" it, so compare with what was seen
|
||||
link['name_mismatch'] = name_mismatch(pname, neighbour or mac or 'an unnamed device', sw_name, known_names)
|
||||
if link['name_mismatch']:
|
||||
@@ -468,7 +491,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')
|
||||
|
||||
Reference in new issue
Block a user