Keep every switch port and show SFP modules
Security / Python Security (bandit) (push) Successful in 1m50s
Test / Python Tests (pytest) (push) Successful in 1m52s
Lint / Python (flake8) (pull_request) Successful in 1m20s
Lint / Python (flake8) (push) Successful in 1m16s
Lint / JS (eslint) (pull_request) Successful in 10s
Lint / JS (eslint) (push) Successful in 15s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m5s
Test / Python Tests (pytest) (pull_request) Successful in 1m7s
Security / Python Security (bandit) (push) Successful in 1m50s
Test / Python Tests (pytest) (push) Successful in 1m52s
Lint / Python (flake8) (pull_request) Successful in 1m20s
Lint / Python (flake8) (push) Successful in 1m16s
Lint / JS (eslint) (pull_request) Successful in 10s
Lint / JS (eslint) (push) Successful in 15s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m5s
Test / Python Tests (pytest) (pull_request) Successful in 1m7s
Ports were keyed by their UniFi name, so when two ports shared a name the later one replaced the earlier. The 24-port switch lost port 13 this way (ports 13 and 14 are both "Office TV"). A repeated name is now kept as "<name> (Port N)". Traffic rates are now matched to the previous poll by port number rather than name. Names are re-read from UniFi every poll, so a port renamed there keeps its rates instead of losing them for a cycle. Collect what UniFi reports about each SFP cage: whether a module is present, its type (DAC or optic), part, serial, fault flags, and DOM readings when the module has them. The faceplate draws empty cages, optics, DACs and unidentified modules differently and outlines a faulted module in red. The port panel gets an SFP Module section. Both ends of a DAC report the same cable serial, so each end links to the other. Closes #7 Closes #8 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
085c488f7b
commit
7e588e5b02
6 files changed
+241
-10
No files matched your search
+77
-3
@@ -245,6 +245,68 @@ class UnifiClient:
|
||||
logger.error(f'UniFi API error: {e}')
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _sfp_detail(port: dict) -> Optional[dict]:
|
||||
"""The module in an SFP cage, or None for a port that has no cage.
|
||||
|
||||
Every cage reports whether a module is present and what it is. Optical
|
||||
readings (DOM) only come from modules that report them, such as fibre
|
||||
optics; copper DACs have none. Switches and the UDM spell the fault flags
|
||||
differently.
|
||||
"""
|
||||
if 'sfp_found' not in port:
|
||||
return None
|
||||
if not port.get('sfp_found'):
|
||||
return {'found': False}
|
||||
|
||||
def number(key: str) -> Optional[float]:
|
||||
try:
|
||||
return float(port[key])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
|
||||
part = str(port.get('sfp_part') or '').strip()
|
||||
compliance = str(port.get('sfp_compliance') or '').strip()
|
||||
if compliance.lower() == 'unknown':
|
||||
compliance = ''
|
||||
rx_power = number('sfp_rxpower')
|
||||
if 'DAC' in compliance.upper() or re.search(r'(^|[-_])CU\d', part, re.IGNORECASE):
|
||||
kind = 'dac'
|
||||
elif rx_power is not None or compliance:
|
||||
kind = 'optic'
|
||||
else:
|
||||
kind = ''
|
||||
return {
|
||||
'found': True,
|
||||
'kind': kind,
|
||||
'vendor': str(port.get('sfp_vendor') or '').strip(),
|
||||
'part': part,
|
||||
'serial': str(port.get('sfp_serial') or '').strip(),
|
||||
'compliance': compliance,
|
||||
'rx_power_dbm': rx_power,
|
||||
'tx_power_dbm': number('sfp_txpower'),
|
||||
'temperature_c': number('sfp_temperature'),
|
||||
'voltage_v': number('sfp_voltage'),
|
||||
'current_ma': number('sfp_current'),
|
||||
'rx_fault': bool(port.get('sfp_rxfault', port.get('sfp_rx_los', False))),
|
||||
'tx_fault': bool(port.get('sfp_txfault', port.get('sfp_tx_fault', False))),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _pair_dac_ends(switches: Dict[str, dict]) -> None:
|
||||
"""Link the two ends of each DAC cable: both report the cable's serial."""
|
||||
ends: Dict[str, List[tuple]] = {}
|
||||
for sw_name, sw in switches.items():
|
||||
for port in sw['ports'].values():
|
||||
sfp = port.get('sfp') or {}
|
||||
if sfp.get('kind') == 'dac' and sfp.get('serial'):
|
||||
ends.setdefault(sfp['serial'], []).append((sw_name, port))
|
||||
for pair in ends.values():
|
||||
if len(pair) != 2:
|
||||
continue # one end not seen, or a serial that isn't unique
|
||||
for (_, port), (peer_name, peer) in (pair, pair[::-1]):
|
||||
port['sfp']['cable_peer'] = {'switch': peer_name, 'port_idx': peer['port_idx']}
|
||||
|
||||
def get_switch_ports(self) -> Optional[Dict[str, dict]]:
|
||||
"""Return per-port stats for UniFi switches and routers, keyed by device name.
|
||||
|
||||
@@ -280,6 +342,11 @@ class UnifiClient:
|
||||
for port in dev.get('port_table', []):
|
||||
idx = port.get('port_idx', 0)
|
||||
pname = port.get('name') or f'Port {idx}'
|
||||
# Ports are keyed by name, and UniFi lets two ports share one
|
||||
# (e.g. a stale label copied to the next port). Without this the
|
||||
# later port silently replaced the earlier one.
|
||||
if pname in ports:
|
||||
pname = f'{pname} (Port {idx})'
|
||||
raw_poe = port.get('poe_power')
|
||||
raw_poe_max = port.get('poe_max_power')
|
||||
ports[pname] = {
|
||||
@@ -302,9 +369,11 @@ class UnifiClient:
|
||||
'rx_errors': port.get('rx_errors', 0),
|
||||
'tx_dropped': port.get('tx_dropped', 0),
|
||||
'rx_dropped': port.get('rx_dropped', 0),
|
||||
'sfp': self._sfp_detail(port),
|
||||
}
|
||||
if ports:
|
||||
result[sw_name] = {'ip': sw_ip, 'model': sw_model, 'ports': ports}
|
||||
self._pair_dac_ends(result)
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.error(f'UniFi switch port stats error: {e}')
|
||||
@@ -786,7 +855,7 @@ class LinkStatsCollector:
|
||||
dt = now - self._prev_unifi_time if self._prev_unifi_time > 0 else 0
|
||||
|
||||
def rate(new_val: int, old_val: Optional[int]) -> Optional[float]:
|
||||
# No earlier reading (first poll, or a new/renamed port) means no rate,
|
||||
# No earlier reading (first poll, or a newly reported port) means no rate,
|
||||
# not "all bytes since boot arrived in this one interval".
|
||||
if dt <= 0 or old_val is None:
|
||||
return None
|
||||
@@ -794,11 +863,16 @@ class LinkStatsCollector:
|
||||
|
||||
result: Dict[str, dict] = {}
|
||||
for sw_name, sw_data in raw.items():
|
||||
prev_ports = self._prev_unifi.get(sw_name, {}).get('ports', {})
|
||||
# Match by port number: names are re-read from UniFi every poll, so a
|
||||
# port renamed there keeps its rates instead of losing them for a cycle.
|
||||
prev_ports = {
|
||||
p.get('port_idx'): p
|
||||
for p in self._prev_unifi.get(sw_name, {}).get('ports', {}).values()
|
||||
}
|
||||
merged_ports: Dict[str, dict] = {}
|
||||
for pname, d in sw_data['ports'].items():
|
||||
entry = dict(d)
|
||||
prev = prev_ports.get(pname, {})
|
||||
prev = prev_ports.get(d.get('port_idx'), {})
|
||||
entry['tx_bytes_rate'] = rate(d['tx_bytes'], prev.get('tx_bytes'))
|
||||
entry['rx_bytes_rate'] = rate(d['rx_bytes'], prev.get('rx_bytes'))
|
||||
entry['tx_errs_rate'] = rate(d['tx_errors'], prev.get('tx_errors'))
|
||||
|
||||
Reference in new issue
Block a user