Restart modem: pause Smart Power auto power-cycle until the modem is back
Lint / JS (eslint) (push) Successful in 14s
Lint / Python (flake8) (push) Successful in 1m5s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m13s
Lint / Python (flake8) (pull_request) Successful in 1m14s
Test / Python Tests (pytest) (push) Successful in 1m51s
Security / Python Security (bandit) (pull_request) Successful in 1m25s
Lint / JS (eslint) (pull_request) Successful in 19s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Test / Python Tests (pytest) (pull_request) Successful in 1m32s

UniFi Smart Power on the RPDU's modem outlet saw the internet down while
the modem rebooted and cut its power mid-boot: once during the 11-20
restart and twice after the 11-24 AT&T-app reboot. UniFi only exposes
auto power-cycle as on or off, so the button now turns it off for every
outlet that has it on, and the monitor turns it back on when the restart
ends (back, or after 30 minutes).

- UnifiClient.auto_power_cycle_outlets / set_auto_power_cycle: sends the
  device's outlet_overrides back with only cycle_enabled changed, then
  reads them again to confirm. The only UniFi setting Gandalf changes.
- A failed pause doesn't stop the restart; a failed restart turns it back
  on. A failed restore is retried every cycle and shown as broken in
  Needs attention until it works.
- The panel note and confirm text mention the pause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-24 00:13:46 -05:00
1 parent a7792063ba
commit a5d4fc3156
9 files changed
+304 -19

No files matched your search

+103 -1
View File
@@ -103,6 +103,36 @@ class PrometheusClient:
# --------------------------------------------------------------------------
# UniFi client
# --------------------------------------------------------------------------
class UnifiWriteError(Exception):
"""A UniFi setting couldn't be read or changed."""
def pause_smart_power(unifi) -> tuple:
"""Turn off auto power-cycle on every outlet that has it, before a deliberate modem
restart: otherwise Smart Power sees the internet down while the modem boots and cuts
its power mid-boot. Returns (paused outlets, error or None); outlets paused before an
error are still listed, so they get turned back on."""
paused: List[dict] = []
try:
for outlet in unifi.auto_power_cycle_outlets():
unifi.set_auto_power_cycle(outlet['device_id'], outlet['index'], False)
paused.append(outlet)
return paused, None
except UnifiWriteError as e:
return paused, str(e)
def restore_smart_power(unifi, paused: List[dict]) -> Optional[str]:
"""Turn auto power-cycle back on for *paused*. Returns an error, or None when all are on."""
errors = []
for outlet in paused or []:
try:
unifi.set_auto_power_cycle(outlet['device_id'], outlet['index'], True)
except UnifiWriteError as e:
errors.append(f'{outlet.get("device")} outlet {outlet.get("index")}: {e}')
return '; '.join(errors) or None
class UnifiClient:
# Devices whose port tables are collected: switches and the gateway/router
_PORT_DEVICE_TYPES = ('usw', 'udm', 'ugw', 'uxg')
@@ -180,6 +210,59 @@ class UnifiClient:
],
}
# ------------------------------------------------------------------
# Smart Power auto power-cycle: the one UniFi setting Gandalf ever changes
# ------------------------------------------------------------------
def _stat_devices(self) -> List[dict]:
url = f'{self.base_url}/proxy/network/api/s/{self.site_id}/stat/device'
resp = self.session.get(url, headers=self.headers, timeout=15)
resp.raise_for_status()
return resp.json().get('data', [])
def auto_power_cycle_outlets(self) -> List[dict]:
"""Outlets with Smart Power auto power-cycle on: [{'device_id', 'device', 'index', 'name'}].
In practice the modem's outlet. Raises UnifiWriteError if UniFi can't be read."""
try:
found = []
for d in self._stat_devices():
for o in d.get('outlet_overrides') or []:
if o.get('cycle_enabled') is True:
found.append({'device_id': d.get('_id'), 'device': d.get('name') or d.get('mac', ''),
'index': o.get('index'), 'name': o.get('name', '')})
return found
except Exception as e:
raise UnifiWriteError(f'reading outlets: {e}') from e
def set_auto_power_cycle(self, device_id: str, index: int, enabled: bool) -> None:
"""Turn auto power-cycle on or off for one outlet, changing nothing else.
UniFi takes the device's whole outlet_overrides list, so the current list is sent
back with only that outlet's cycle_enabled changed (relay states untouched), then
read again to confirm. Raises UnifiWriteError.
"""
try:
device = next((d for d in self._stat_devices() if d.get('_id') == device_id), None)
if device is None:
raise UnifiWriteError(f'device {device_id} not found')
overrides = [dict(o) for o in device.get('outlet_overrides') or []]
target = next((o for o in overrides if o.get('index') == index), None)
if target is None:
raise UnifiWriteError(f'outlet {index} has no override entry on {device.get("name")}')
if target.get('cycle_enabled') is enabled:
return
target['cycle_enabled'] = enabled
url = f'{self.base_url}/proxy/network/api/s/{self.site_id}/rest/device/{device_id}'
resp = self.session.put(url, headers=self.headers, timeout=15, json={'outlet_overrides': overrides})
resp.raise_for_status()
check = next((d for d in self._stat_devices() if d.get('_id') == device_id), {})
now = next((o for o in check.get('outlet_overrides') or [] if o.get('index') == index), {})
if now.get('cycle_enabled') is not enabled:
raise UnifiWriteError('UniFi accepted the change but still reports the old setting')
except UnifiWriteError:
raise
except Exception as e:
raise UnifiWriteError(f'{type(e).__name__}: {e}') from e
def get_wired_clients(self) -> List[dict]:
"""Return wired clients as {mac, sw_mac, sw_port}; empty if unavailable."""
try:
@@ -2144,7 +2227,13 @@ class NetworkMonitor:
state = json.loads(raw) if raw else None
except ValueError:
state = None
if not state or state.get('finished_at'):
if not state:
return
if state.get('finished_at'):
# Auto power-cycle must not stay off: keep retrying until it's back on
if state.get('smart_power_paused') and not state.get('smart_power_restored'):
self._restore_smart_power(state)
db.set_state('modem_restart', state)
return
now = time.time()
age = now - state.get('at', now)
@@ -2170,12 +2259,25 @@ class NetworkMonitor:
state['kuma_error'] = str(e)
if state.get('suppression_id'):
db.deactivate_suppression(state['suppression_id'])
if state.get('smart_power_paused'):
self._restore_smart_power(state)
state.update(finished_at=now, back=bool(back), rebooted=rebooted,
back_after_s=round(age) if back else None)
db.set_state('modem_restart', state)
logger.info(f'Modem restart finished: {"back" if back else "gave up waiting"} after {round(age)} s'
f'{", rebooted" if rebooted else ""}')
def _restore_smart_power(self, state: dict) -> None:
"""Turn auto power-cycle back on for the outlets the restart paused; note the result."""
err = restore_smart_power(self.unifi, state['smart_power_paused'])
if err:
logger.error(f'Smart Power auto power-cycle is still off: {err}')
state['smart_power_error'] = err
else:
logger.info(f'Smart Power auto power-cycle back on for '
f'{len(state["smart_power_paused"])} outlet(s)')
state.update(smart_power_restored=True, smart_power_error=None)
_NAT_EVERY_S = 1800 # NAT sessions and the gateway's speed test history
_FIREWALL_EVERY_S = 300 # the firewall log only holds about ten minutes
_FIREWALL_HOURS = 24