Compare commits

...
Author SHA1 Message Date
jared a90ce44c80 Merge pull request 'Cutsheet: port names in UniFi that no longer fit, document a cable from topology' (#44) from port-name-report into main
Lint / JS (eslint) (push) Successful in 16s
Lint / Python (flake8) (push) Successful in 2m2s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m44s
Lint / Deploy (push) Successful in 5s
Test / Python Tests (pytest) (push) Successful in 45s
2026-11-15 14:21:20 -05:00
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
jaredandClaude Opus 5.5 b9e008bc2b Topology: tap to trace on phones, name cables into a patch panel
Lint / JS (eslint) (push) Successful in 19s
Lint / Python (flake8) (push) Successful in 1m20s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Lint / JS (eslint) (pull_request) Successful in 27s
Lint / Python (flake8) (pull_request) Successful in 1m46s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m9s
Test / Python Tests (pytest) (pull_request) Successful in 1m23s
Security / Python Security (bandit) (push) Successful in 1m10s
Test / Python Tests (pytest) (push) Successful in 1m18s
- Touch screens have no hover, so the first tap on a device traces its path to
  the internet and its power feeds; a second tap opens it. Tapping empty canvas
  clears it, and the trace survives the 30 s refresh.
- A cutsheet cable now carries where its other end goes. An unknown device on a
  cable documented into a patch panel is drawn as that panel's jacks, named
  "Patch panel port N"; a named stub notes "via Patch panel port N". The cable
  panel shows the far end of the cutsheet cable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 22:16:16 -05:00
jared ab59b42bea Merge pull request 'Topology: power map, what each outlet feeds' (#40) from power-map into main
Lint / JS (eslint) (push) Successful in 26s
Security / Python Security (bandit) (push) Successful in 2m15s
Test / Python Tests (pytest) (push) Successful in 2m19s
Lint / Python (flake8) (push) Successful in 1m58s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Successful in 5s
2026-11-14 20:51:13 -05:00
jaredandClaude Opus 5.5 415d2222e7 Topology: power map, what each outlet feeds
Lint / JS (eslint) (push) Successful in 21s
Lint / Python (flake8) (push) Successful in 2m36s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Test / Python Tests (pytest) (push) Successful in 2m46s
Lint / JS (eslint) (pull_request) Successful in 15s
Lint / Python (flake8) (pull_request) Successful in 2m14s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (push) Successful in 1m33s
Security / Python Security (bandit) (pull_request) Successful in 54s
Test / Python Tests (pytest) (pull_request) Successful in 1m3s
- Each PDU, UPS and power strip card lists its outlets that feed
  something, draw power or are off, with live watts. Each device fed
  gets a power badge with what it draws. Hovering a power card or a
  device draws its feeds as dotted lines and keeps both ends lit.
- What an outlet feeds: a saved assignment, else the outlet's UniFi name
  when it names a device (or the modem), else a MAC in its name that
  belongs to a host NIC (the monitor's host_macs) or UniFi device.
- Admins click an outlet to set what it feeds, nothing, or automatic.
  Saved in a new power_feeds table (created with the cutsheet tables);
  PUT /api/topology/power/<device>/<outlet>, admin and JSON only, with
  the device, outlet and target checked. UniFi is never changed.
- An outlet that is off but feeds something is listed under "to look at".
- Power gear is shown by default again, now that it has something to say.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:28:13 -05:00
jared dcf5fdf4cc Merge pull request 'Topology: a live page drawn from the real gear' (#39) from topology into main
Lint / JS (eslint) (push) Successful in 17s
Lint / Python (flake8) (push) Successful in 1m10s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m1s
Lint / Deploy (push) Successful in 4s
Test / Python Tests (pytest) (push) Successful in 51s
2026-11-14 20:10:19 -05:00
17 changed files with 1046 additions and 43 deletions

No files matched your search

+38 -7
View File
@@ -206,21 +206,40 @@ 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.
- **Alerts**: a device with active alerts (not suppressed) gets a ring and a count in its worst
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. 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** (off by default) adds the PDU, UPS
and power strip. Traffic labels and dimming everything without an alert can be switched too. The
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
filters are remembered per browser. Refreshes every 30 seconds without moving the view.
- API: `GET /api/topology` returns `{nodes, links, warnings, updated}` (see `topology.py`).
- API: `GET /api/topology` returns `{nodes, links, power, warnings, updated}` (see `topology.py`).
### Health check (`/health`)
No login needed. Returns 200 when the database answers and the monitor has completed a check recently,
@@ -237,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,
@@ -310,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`.
@@ -332,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
@@ -825,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
+43 -5
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,
@@ -1312,7 +1315,8 @@ def api_rack():
@app.route('/topology')
@require_auth
def topology_page():
return render_template('topology.html', user=_get_user())
user = _get_user()
return render_template('topology.html', user=user, can_edit='admin' in user['groups'])
@app.route('/api/topology')
@@ -1324,14 +1328,48 @@ def api_topology():
try:
_ensure_cutsheet_schema()
sheet = db.cutsheet_load()
feeds = db.get_power_feeds()
except Exception as e:
logger.error(f'Cutsheet unavailable for topology: {e}')
sheet = {'items': [], 'cables': []}
graph = topology.build_graph(
sheet, feeds = {'items': [], 'cables': []}, []
return jsonify(_topology_graph(events, sheet, feeds))
def _topology_graph(events: list, sheet: dict, feeds: list) -> dict:
return topology.build_graph(
_state_json('network_snapshot'), _state_json('link_stats'), _state_json('modem_stats'),
events, sheet['items'], sheet['cables'], _state_json('known_uplinks'),
events, sheet['items'], sheet['cables'], _state_json('known_uplinks'), feeds,
)
return jsonify(graph)
@app.route('/api/topology/power/<path:source>/<int:outlet>', methods=['PUT'])
@require_auth
@require_admin
@_cutsheet_write
def api_topology_power(source: str, outlet: int):
"""Say what a power outlet feeds. Body: {"target": "<device>"} or "" for nothing, or
null to go back to the guess from the outlet's name."""
body = _json_body()
if 'target' not in body:
raise cutsheet.ValidationError('Send target: a device name, "" for nothing, or null for automatic')
target = body['target']
if target is not None and not isinstance(target, str):
raise cutsheet.ValidationError('target must be a device name, "" or null')
graph = _topology_graph([], {'items': [], 'cables': []}, [])
src = next((p for p in graph['power'] if p['node'] == source), None)
if src is None:
return jsonify({'error': f'No power device named "{source}"'}), 404
if not any(o['index'] == outlet for o in src['outlets']):
return jsonify({'error': f'{source} has no outlet {outlet}'}), 404
names = {n['name'] for n in graph['nodes'] if n['kind'] not in ('stub', 'internet')}
if target and target.strip() not in names:
raise cutsheet.ValidationError(f'No device named "{target}"')
target = target.strip() if target else target
user = _get_user()['username']
db.set_power_feed(source, outlet, target, user)
shown = '(automatic)' if target is None else (target or '(nothing)')
logger.info(f'{user} set {source} outlet {outlet} to feed {shown}')
return jsonify({'success': True, 'source': source, 'outlet': outlet, 'target': target})
@app.route('/api/cutsheet/racks', methods=['POST'])
+35
View File
@@ -826,9 +826,44 @@ _CUTSHEET_SCHEMA = (
updated_by VARCHAR(255) NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB""",
# What each PDU, UPS or power strip outlet feeds, set by hand on the topology page. An empty
# target means "nothing": it overrides a guess from the outlet's name. Gandalf never renames
# outlets in UniFi.
"""CREATE TABLE IF NOT EXISTS power_feeds (
source VARCHAR(255) NOT NULL,
outlet SMALLINT NOT NULL,
target VARCHAR(255) NOT NULL DEFAULT '',
updated_by VARCHAR(255) NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (source, outlet)
) ENGINE=InnoDB""",
)
def get_power_feeds() -> list:
"""Every outlet assignment: [{source, outlet, target, updated_by, updated_at}]."""
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute('SELECT source, outlet, target, updated_by, updated_at FROM power_feeds')
rows = cur.fetchall()
return [dict(r, updated_at=r['updated_at'].isoformat() + 'Z' if hasattr(r['updated_at'], 'isoformat')
else r['updated_at']) for r in rows]
def set_power_feed(source: str, outlet: int, target: Optional[str], user: str) -> None:
"""Say what an outlet feeds: a device name, '' for nothing, or None to go back to the guess."""
with get_conn() as conn:
with conn.cursor() as cur:
if target is None:
cur.execute('DELETE FROM power_feeds WHERE source=%s AND outlet=%s', (source, outlet))
return
cur.execute(
"""INSERT INTO power_feeds (source, outlet, target, updated_by) VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE target=VALUES(target), updated_by=VALUES(updated_by)""",
(source, outlet, target, user),
)
def get_device_link(name: str) -> str:
"""The device's inventory URL, or ''."""
with get_conn() as conn:
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) {
+44
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; }
@@ -1495,6 +1505,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; }
@@ -1636,3 +1652,31 @@ body.fp-marks-off .fp-svg .fp-mark { display: none; }
.tp-chip-bad { color: var(--red); border-color: var(--red); background: var(--red-dim); }
.tp-chip-warn { color: var(--amber); border-color: var(--amber); background: var(--amber-dim); }
.tp-problem-chip:hover, .tp-problem-chip:focus-visible { filter: brightness(1.25); outline: none; }
/* Power: outlet lists on power cards, badges on what they feed, feed lines on hover */
.tp-outlet-hit { fill: transparent; }
.tp-outlet-row:hover .tp-outlet-hit, .tp-outlet-row:focus-visible .tp-outlet-hit { fill: rgba(255,179,0,.12); }
.tp-outlet-row[role="button"] { cursor: pointer; outline: none; }
.tp-outlet-idx { font-family: var(--font); font-size: 24px; fill: var(--text-muted); }
.tp-outlet-target { font-family: var(--font); font-size: 26px; fill: var(--text); }
.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; }
.tp-feed path { fill: none; stroke: #ffb300; stroke-width: 6; stroke-dasharray: 2 14; stroke-linecap: round; }
.tp-feed circle { fill: #ffb300; }
.tp-feed-off path { stroke: #e0312b; }
.tp-feed-off circle { fill: #e0312b; }
.tp-feed-tag rect { stroke: #ffb300; }
.tp-pop { position: absolute; z-index: 3; width: 280px; padding: 10px 12px; font-size: .8em;
background: var(--bg-primary); border: 1px solid var(--amber); box-shadow: 0 8px 24px rgba(0,0,0,.35); cursor: auto; }
.tp-pop[hidden] { display: none; }
.tp-pop-title { font-weight: 700; color: var(--amber); }
.tp-pop-sub { color: var(--text-muted); margin: 2px 0 8px; overflow-wrap: anywhere; }
.tp-pop-label { display: block; color: var(--text-dim); margin-bottom: 3px; }
.tp-pop select { width: 100%; }
.tp-pop-hint { color: var(--text-muted); font-size: .9em; margin: 6px 0 8px; }
.tp-pop-actions { display: flex; justify-content: flex-end; gap: 6px; }
+281 -16
View File
@@ -1,5 +1,5 @@
'use strict';
/* global FACEPLATES, faceplateSvg, faceplatePortAnchor, RACK_FRONTS, SHELF_GEAR, DESK_FACEPLATES, CHASSIS_FACEPLATES, rackFrontSvg */
/* global TOPO_CAN_EDIT, FACEPLATES, faceplateSvg, faceplatePortAnchor, RACK_FRONTS, SHELF_GEAR, DESK_FACEPLATES, CHASSIS_FACEPLATES, rackFrontSvg */
// Topology page: a card per device with its real faceplate or chassis, and each cable leaving the
// exact port it is plugged into. Data comes from /api/topology (topology.build_graph).
@@ -8,7 +8,7 @@ const PER_MM = 1100 / 482.6;
const NODE_GAP = 90;
const REFRESH_MS = 30000;
const FILTER_KEY = 'gandalf.topology.filters';
const DEFAULT_FILTERS = { stubs: 'grouped', power: false, traffic: true, mgmt: false, alerts: false };
const DEFAULT_FILTERS = { stubs: 'grouped', power: true, traffic: true, mgmt: false, alerts: false };
const STUB_MODES = ['grouped', 'all', 'none'];
const state = {
@@ -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,18 @@ 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';
out.push({ kind: 'node', id: o.target, severity: down ? 'bad' : 'warn',
text: `${src.node} outlet ${o.index} is off, and it feeds ${o.target}` });
}));
data.links.forEach(l => {
const p = linkProblem(l);
if (!p) return;
@@ -123,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';
@@ -317,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 || [] };
@@ -340,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 });
@@ -352,6 +396,22 @@ function artFor(node) {
}
}
// ── Power ───────────────────────────────────────────────────────────────
function wattText(w) {
return w == null ? '' : `${w >= 100 ? Math.round(w) : (+w).toFixed(1)} W`;
}
function powerOf(name) {
return ((state.data && state.data.power) || []).find(p => p.node === name);
}
// The outlets worth listing on a power card: those feeding something, drawing power, or off
function listedOutlets(src) {
return src.outlets.filter(o => o.target || (o.power_w || 0) >= 0.5 || !o.on);
}
const ROW_H = 46;
// ── Cards ───────────────────────────────────────────────────────────────
// Every device is a card of the same height: its name and state on top, and below that its real
// faceplate (or, for a server, its front and a socket per NIC) shrunk to fit. Cables meet the card
@@ -411,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);
@@ -421,22 +482,63 @@ function cardFor(node, linksByIface) {
return a ? { x: f.ox + a.x * f.k, y: f.oy + a.y * f.k } : null;
};
}
// Power gear lists its outlets under the picture: what each feeds and what it draws
let h = CARD_H;
let rowsSvg = '';
const rows = {};
const src = node.power ? powerOf(node.name) : null;
if (src) {
const list = listedOutlets(src);
rowsSvg = list.map((o, i) => {
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'}${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 + 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 ? 'off' : o.stale ? 'stale' : esc(wattText(o.power_w))}</text>
</g>`;
}).join('');
h = CARD_H + list.length * ROW_H + (list.length ? 16 : 0);
}
// What feeds this device, as a badge by its name
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)}${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;
else sub = [node.model || node.kind, node.status !== 'up' ? node.status : ''].filter(Boolean).join(' · ');
const svg = `<rect class="tp-card" width="${w}" height="${CARD_H}" rx="18"/>
<rect class="tp-card-stripe tp-stripe-${esc(node.status)}" x="0" y="18" width="8" height="${CARD_H - 36}" rx="4"/>
else sub = [node.model || node.kind, src && src.power_w != null ? `${wattText(src.power_w)} total` : '',
node.status !== 'up' ? node.status : ''].filter(Boolean).join(' · ');
// The second line shares its space with the power badge
const subMax = Math.floor((w - (badge ? 250 : 70)) / 16.8);
if (sub.length > subMax) sub = `${sub.slice(0, subMax - 1)}…`;
const svg = `<rect class="tp-card" width="${w}" height="${h}" rx="18"/>
<rect class="tp-card-stripe tp-stripe-${esc(node.status)}" x="0" y="18" width="8" height="${h - 36}" rx="4"/>
<text class="tp-card-name" x="34" y="66">${esc(name)}</text>
<text class="tp-card-sub" x="34" y="108">${esc(sub)}</text>
<circle class="tp-dot tp-dot-${esc(node.status)}" cx="${w - 42}" cy="52" r="13"/>
<circle class="tp-dot tp-dot-${esc(node.status)}" cx="${w - 42}" cy="52" r="13"/>${badge}
<rect class="tp-band" x="20" y="${BAND_Y - 8}" width="${w - 40}" height="${BAND_H + 16}" rx="10"/>
${band}`;
return { w, h: CARD_H, svg, anchorAt };
${band}${rowsSvg}`;
return { w, h, svg, anchorAt, rows };
}
// ── Layout ──────────────────────────────────────────────────────────────
@@ -789,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)}">`);
@@ -829,7 +934,8 @@ function render() {
const cables = lay.links.map(l => renderLink(l, lay));
world.innerHTML = `<g class="tp-links">${cables.map(c => c.under).join('')}</g>
<g class="tp-nodes">${lay.nodes.map(n => renderNode(n, lay)).join('')}</g>
<g class="tp-links-over">${cables.map(c => c.over).join('')}</g>`;
<g class="tp-links-over">${cables.map(c => c.over).join('')}</g>
<g class="tp-feeds" id="tp-feeds"></g>`;
document.getElementById('tp-loading').hidden = true;
applyFilterClasses();
if (!state.fitted) {
@@ -844,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 ─────────────────────────────────────────────────────────
@@ -863,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');
@@ -885,9 +1013,12 @@ 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>');
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>`
@@ -929,14 +1060,52 @@ function upstream(id) {
return { nodes, hot };
}
// Power feeds, drawn while a power unit or a device it feeds is under the pointer: dotted lines
// from the outlet's row on the power card to the device
function drawFeeds(id) {
const lay = state.layout;
const g = document.getElementById('tp-feeds');
if (!g || !lay) return [];
const pairs = [];
((state.data && state.data.power) || []).forEach(src => {
const sp = lay.pos[src.node];
if (!sp) return;
src.outlets.forEach(o => {
if (!o.target || !lay.pos[o.target] || (id !== src.node && id !== o.target)) return;
const rowY = lay.drawings[src.node].rows[o.index];
if (rowY == null) return;
pairs.push({ o, from: { x: sp.x, y: sp.y + rowY }, to: lay.pos[o.target], toH: lay.drawings[o.target].h, target: o.target });
});
});
g.innerHTML = pairs.map(({ o, from, to, toH, target }) => {
const B = { x: to.x + to.w, y: to.y + toH / 2 };
if (to.rail) { B.x = to.x; }
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="${-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))]));
}
function highlight(id) {
const canvas = document.getElementById('tp-canvas');
document.querySelectorAll('.tp-hot').forEach(el => el.classList.remove('tp-hot'));
const feeds = document.getElementById('tp-feeds');
if (feeds) feeds.innerHTML = '';
if (!id || !state.layout) {
canvas.classList.remove('tp-tracing');
return;
}
const fed = drawFeeds(id);
const { nodes, hot } = upstream(id);
fed.forEach(n => nodes.add(n));
nodes.forEach(n => document.querySelector(`.tp-node[data-node="${CSS.escape(n)}"]`)?.classList.add('tp-hot'));
hot.forEach(l => document.querySelectorAll(`.tp-link[data-link="${CSS.escape(l)}"]`).forEach(el => el.classList.add('tp-hot')));
canvas.classList.add('tp-tracing');
@@ -1068,6 +1237,29 @@ function initPanZoom() {
function initEvents() {
const svg = document.getElementById('tp-svg');
svg.addEventListener('click', e => {
const outletRow = e.target.closest('[data-outlet]');
if (outletRow && TOPO_CAN_EDIT) {
e.preventDefault();
openOutletEditor(outletRow, e);
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();
@@ -1090,6 +1282,12 @@ function initEvents() {
});
svg.addEventListener('keydown', e => {
if (e.key !== 'Enter' && e.key !== ' ') return;
const outletRow = e.target.closest('[data-outlet]');
if (outletRow && TOPO_CAN_EDIT) {
e.preventDefault();
openOutletEditor(outletRow, null);
return;
}
const group = e.target.closest('[data-expand]');
if (group) {
e.preventDefault();
@@ -1105,14 +1303,25 @@ 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 => {
const b = e.target.closest('[data-pop]');
if (!b) return;
if (b.dataset.pop === 'save') saveOutlet();
else closeOutletEditor();
});
document.getElementById('tp-pop').addEventListener('keydown', e => {
if (e.key === 'Escape') closeOutletEditor();
});
document.getElementById('tp-summary').addEventListener('click', e => {
const chip = e.target.closest('.tp-problem-chip');
if (!chip) return;
@@ -1145,6 +1354,62 @@ function initEvents() {
});
}
// ── Outlet editor (admins) ──────────────────────────────────────────────
function closeOutletEditor() {
const pop = document.getElementById('tp-pop');
if (pop) pop.hidden = true;
}
function openOutletEditor(row, evt) {
const pop = document.getElementById('tp-pop');
const source = row.dataset.outletSource;
const index = Number(row.dataset.outlet);
const src = powerOf(source);
const o = src && src.outlets.find(x => x.index === index);
if (!o) return;
const names = state.data.nodes.filter(n => !['stub', 'internet'].includes(n.kind) && n.name !== source)
.map(n => n.name).sort((a, b) => a.localeCompare(b));
const current = o.match === 'saved' ? o.target : (o.match === 'cleared' ? '__none' : '__auto');
const opt = (v, t) => `<option value="${esc(v)}"${v === current ? ' selected' : ''}>${esc(t)}</option>`;
pop.innerHTML = `<div class="tp-pop-title">${esc(source)} outlet ${index}</div>
<div class="tp-pop-sub">${esc(o.name || 'no name in UniFi')} · ${o.on ? esc(wattText(o.power_w) || 'on') : 'off'}</div>
<label class="tp-pop-label" for="tp-pop-select">Feeds</label>
<select class="lt-select" id="tp-pop-select">
${opt('__auto', `Automatic (${o.match === 'name' || o.match === 'mac' ? o.target : 'from its name: nothing'})`)}
${opt('__none', 'Nothing')}
${names.map(n => opt(n, n)).join('')}
</select>
<p class="tp-pop-hint">Saved in Gandalf only; the outlet keeps its name in UniFi.</p>
<div class="tp-pop-actions">
<button type="button" class="lt-btn lt-btn-secondary lt-btn-sm" data-pop="cancel">Cancel</button>
<button type="button" class="lt-btn lt-btn-primary lt-btn-sm" data-pop="save">Save</button>
</div>`;
const canvas = document.getElementById('tp-canvas').getBoundingClientRect();
const r = evt ? { x: evt.clientX, y: evt.clientY } : (() => { const b = row.getBoundingClientRect(); return { x: b.left, y: b.bottom }; })();
pop.hidden = false;
const left = Math.min(Math.max(8, r.x - canvas.left - pop.offsetWidth - 12), canvas.width - pop.offsetWidth - 8);
const top = Math.min(Math.max(8, r.y - canvas.top - 20), canvas.height - pop.offsetHeight - 8);
pop.style.left = `${left}px`;
pop.style.top = `${top}px`;
pop.dataset.source = source;
pop.dataset.outlet = String(index);
document.getElementById('tp-pop-select').focus();
}
async function saveOutlet() {
const pop = document.getElementById('tp-pop');
const v = document.getElementById('tp-pop-select').value;
const target = v === '__auto' ? null : (v === '__none' ? '' : v);
try {
await lt.api.put(`/api/topology/power/${encodeURIComponent(pop.dataset.source)}/${encodeURIComponent(pop.dataset.outlet)}`, { target });
closeOutletEditor();
lt.toast.success('Outlet saved');
refresh();
} catch (e) {
lt.toast.error(`Could not save: ${e.message || e}`);
}
}
// ── Problem summary ─────────────────────────────────────────────────────
function renderSummary() {
const box = document.getElementById('tp-summary');
+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>
+3 -1
View File
@@ -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>
@@ -39,6 +39,7 @@
</svg>
<div class="link-loading tp-loading" id="tp-loading">Loading topology</div>
<aside class="tp-panel" id="tp-panel" hidden aria-live="polite" aria-label="Cable details"></aside>
<div class="tp-pop" id="tp-pop" role="dialog" aria-label="What this outlet feeds" hidden></div>
</div>
<div class="tp-legend" aria-label="Legend">
@@ -55,6 +56,7 @@
{% endblock %}
{% block scripts %}
<script>const TOPO_CAN_EDIT = {{ 'true' if can_edit else 'false' }};</script>
<script src="{{ url_for('static', filename='faceplates.js') }}"></script>
<script src="{{ url_for('static', filename='fronts.js') }}"></script>
<script src="{{ url_for('static', filename='topology.js') }}"></script>
+49
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
@@ -743,3 +744,51 @@ class TestTopology:
patch.object(gandalf.db, 'check_suppressed', return_value=True):
data = client.get('/api/topology', headers=AUTH).get_json()
assert next(n for n in data['nodes'] if n['name'] == 'large1')['alert_count'] == 0
class TestPowerFeedApi:
LINK_STATS = json.dumps({'hosts': {}, 'unifi_switches': {}, 'unifi_devices': {
'RPDU': {'outlets': [{'index': 7, 'name': 'Outlet 7', 'on': True, 'power_w': 48.0}]}}})
SNAPSHOT = json.dumps({
'hosts': {'large1': {'status': 'up', 'interfaces': {}}},
'unifi': [{'name': 'RPDU', 'type': 'usw', 'model': 'USPPDUP', 'connected': True, 'mac': '', 'ip': ''}],
})
def _put(self, client, path, body, headers=AUTH):
state = dict(STATE, link_stats=self.LINK_STATS, network_snapshot=self.SNAPSHOT)
gandalf._cutsheet_schema_ready = True
with patch.object(gandalf.db, 'get_state', side_effect=lambda k, d=None: state.get(k, d)):
return client.put(path, json=body, headers=headers)
def test_admin_assigns_an_outlet(self, client):
resp = self._put(client, '/api/topology/power/RPDU/7', {'target': 'large1'})
assert resp.status_code == 200
gandalf.db.set_power_feed.assert_called_once_with('RPDU', 7, 'large1', 'jared')
def test_empty_means_nothing_and_null_means_automatic(self, client):
assert self._put(client, '/api/topology/power/RPDU/7', {'target': ''}).status_code == 200
assert self._put(client, '/api/topology/power/RPDU/7', {'target': None}).status_code == 200
calls = [c.args for c in gandalf.db.set_power_feed.call_args_list]
assert calls == [('RPDU', 7, '', 'jared'), ('RPDU', 7, None, 'jared')]
def test_needs_admin(self, client):
resp = self._put(client, '/api/topology/power/RPDU/7', {'target': 'large1'},
headers=dict(AUTH, **{'Remote-Groups': 'users'}))
assert resp.status_code in (401, 403)
gandalf.db.set_power_feed.assert_not_called()
def test_unknown_target_source_or_outlet(self, client):
assert self._put(client, '/api/topology/power/RPDU/7', {'target': 'nope'}).status_code == 400
assert self._put(client, '/api/topology/power/NOPE/7', {'target': 'large1'}).status_code == 404
assert self._put(client, '/api/topology/power/RPDU/99', {'target': 'large1'}).status_code == 404
gandalf.db.set_power_feed.assert_not_called()
def test_body_must_say_target(self, client):
assert self._put(client, '/api/topology/power/RPDU/7', {}).status_code == 400
assert self._put(client, '/api/topology/power/RPDU/7', {'target': 5}).status_code == 400
def test_must_be_json(self, client):
gandalf._cutsheet_schema_ready = True
resp = client.put('/api/topology/power/RPDU/7', data='target=large1', headers=AUTH,
content_type='application/x-www-form-urlencoded')
assert resp.status_code == 400
+22
View File
@@ -62,3 +62,25 @@ class TestGetClearedTickets:
out = db.get_cleared_tickets(['1', '2'])
assert [r['ticket_id'] for r in out] == ['2', '1']
assert out[0]['target_name'] == 'micro1'
class TestPowerFeeds:
def test_none_goes_back_to_automatic(self):
patcher, cur = _fake_conn([])
with patcher:
db.set_power_feed('RPDU', 7, None, 'jared')
sql, args = cur.execute.call_args.args
assert sql.startswith('DELETE FROM power_feeds') and args == ('RPDU', 7)
def test_empty_target_is_saved_as_nothing(self):
patcher, cur = _fake_conn([])
with patcher:
db.set_power_feed('RPDU', 7, '', 'jared')
sql, args = cur.execute.call_args.args
assert 'INSERT INTO power_feeds' in sql and args == ('RPDU', 7, '', 'jared')
def test_rows_come_back_with_iso_times(self):
patcher, _ = _fake_conn([{'source': 'RPDU', 'outlet': 7, 'target': 'large1', 'updated_by': 'jared',
'updated_at': NOW}])
with patcher:
assert db.get_power_feeds()[0]['updated_at'] == '2026-11-14T12:00:00Z'
+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({
+151 -1
View File
@@ -326,13 +326,163 @@ 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):
g = topology.build_graph({}, {}, None, [], [], [], None)
assert [n['id'] for n in g['nodes']] == [topology.INTERNET]
assert g['links'] == [] and g['warnings']
class TestPower:
OUTLETS = [
{'index': 1, 'name': 'AT&T Modem', 'on': True, 'power_w': 9.0},
{'index': 6, 'name': 'Dream Machine Pro', 'on': True, 'power_w': 20.6},
{'index': 7, 'name': 'Outlet 7', 'on': True, 'power_w': 48.0},
{'index': 14, 'name': 'host-a', 'on': False, 'power_w': 0.0},
{'index': 16, 'name': '02:00:5e:00:0a:01', 'on': True, 'power_w': 131.7},
{'index': 17, 'name': 'USB Outlet 1', 'on': True, 'power_w': None},
]
def _graph(self, feeds=(), outlets=None):
snapshot, link_stats, modem = network()
link_stats['unifi_devices']['RPDU']['outlets'] = outlets or self.OUTLETS
link_stats['host_macs'] = {'02:00:5e:00:0a:01': ['host-c', 'nic0']}
return topology.build_graph(snapshot, link_stats, modem, [], [], [], None, list(feeds))
def _outlets(self, g, source='RPDU'):
return {o['index']: o for o in next(s for s in g['power'] if s['node'] == source)['outlets']}
def test_matched_by_name_alias_and_mac(self):
out = self._outlets(self._graph())
assert (out[1]['target'], out[1]['match']) == ('att-modem', 'name')
assert (out[6]['target'], out[6]['match']) == ('Dream Machine Pro', 'name')
assert (out[14]['target'], out[14]['on']) == ('host-a', False)
assert (out[16]['target'], out[16]['match']) == ('host-c', 'mac')
def test_generic_names_feed_nothing(self):
out = self._outlets(self._graph())
assert (out[7]['target'], out[7]['match']) == (None, 'none')
assert out[17]['target'] is None
def test_saved_assignment_wins_and_empty_means_nothing(self):
feeds = [{'source': 'RPDU', 'outlet': 7, 'target': 'host-b'},
{'source': 'RPDU', 'outlet': 6, 'target': ''}]
out = self._outlets(self._graph(feeds))
assert (out[7]['target'], out[7]['match']) == ('host-b', 'saved')
assert (out[6]['target'], out[6]['match']) == (None, 'cleared')
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,
'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) == []
+196 -9
View File
@@ -119,35 +119,200 @@ def name_mismatch(port_name: str, neighbour: str, own: str, known: Dict[str, str
"""
if not port_name or _is_generic_port_name(port_name):
return None
words = _TOKEN_RE.findall(port_name.lower())
skip = {_norm(neighbour), _norm(own)}
named = _named_device(port_name, known, {_norm(neighbour), _norm(own)})
return {'named': named, 'actual': neighbour} if named else None
def _named_device(text: str, known: Dict[str, str], skip=()) -> Optional[str]:
"""The device a free-text name refers to: the longest run of up to four of its words that
is a device name (ignoring case, spaces, dashes and underscores), or None."""
words = _TOKEN_RE.findall((text or '').lower())
for size in range(min(4, len(words)), 0, -1):
for i in range(len(words) - size + 1):
run = ''.join(words[i:i + size])
if run in known and run not in skip:
return {'named': known[run], 'actual': neighbour}
return known[run]
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)
def build_power(nodes: Dict[str, dict], link_stats: dict, feeds: List[dict]) -> List[dict]:
"""What every PDU, UPS and power strip outlet feeds.
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, 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)
macs = {str(mac).lower(): owner[0] for mac, owner in (link_stats.get('host_macs') or {}).items() if owner}
for name, info in (link_stats.get('unifi_devices') or {}).items():
if info.get('mac'):
macs.setdefault(info['mac'].lower(), name)
saved = {}
for f in feeds or []:
try:
saved[(f['source'], int(f['outlet']))] = f.get('target') or ''
except (KeyError, TypeError, ValueError):
continue
sources = []
for node in sorted((n for n in nodes.values() if n.get('power')), key=lambda n: n['name'].lower()):
rows = []
for o in node.get('outlets') or []:
idx = o.get('index')
text = str(o.get('name') or '')
target, how = None, 'none'
if (node['name'], idx) in saved:
target = saved[(node['name'], idx)] or None
how = 'saved' if target else 'cleared'
else:
target = _named_device(text, known, {_norm(node['name'])})
if not target and modem and 'modem' in _TOKEN_RE.findall(text.lower()):
target = modem
if target:
how = 'name'
else:
m = _MAC_IN_TEXT.search(text)
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'), '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,
'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 []:
@@ -167,13 +332,14 @@ def _worst(alerts: List[dict]) -> str:
def build_graph(snapshot: dict, link_stats: dict, modem: Optional[dict], events: List[dict],
cutsheet_items: List[dict], cutsheet_cables: List[dict],
known_uplinks: Optional[dict] = None) -> dict:
"""Every device and cable, as {nodes, links, warnings, updated}.
known_uplinks: Optional[dict] = None, power_feeds: Optional[List[dict]] = None) -> dict:
"""Every device and cable, as {nodes, links, power, warnings, updated}.
snapshot, link_stats, modem: the monitor's saved state.
events: active events, with is_suppressed set (suppressed ones are left out).
known_uplinks: the monitor's record of where each device was last plugged in,
drawn as "last seen" links for a device with no live link.
power_feeds: outlet assignments saved on the topology page (see build_power).
"""
snapshot = snapshot or {}
link_stats = link_stats or {}
@@ -219,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)
@@ -333,6 +500,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']:
@@ -401,11 +576,23 @@ def build_graph(snapshot: dict, link_stats: dict, modem: Optional[dict], events:
if nic['name'] == end['iface']:
nic.setdefault('links', []).append(link['id'])
# Power: what each outlet feeds, and on each device, the outlets feeding it
power = build_power({k: v for k, v in nodes.items() if v['kind'] != 'stub'}, link_stats, power_feeds or [])
for node in nodes.values():
node['power_in'] = []
for src in power:
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'],
'stale': o['stale']})
if not switches:
warnings.append('No UniFi switch data yet: the monitor has not reported any ports')
return {
'nodes': sorted(nodes.values(), key=lambda n: (99 if n['depth'] is None else n['depth'], n['name'].lower())),
'links': links,
'power': power,
'warnings': warnings,
'updated': link_stats.get('updated'),
}