mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-01 08:48:05 +00:00
Add system diagnostics, power controls, and WiFi radio toggle to Tools tab (#389)
* Add system diagnostics, power controls, and WiFi radio toggle to Tools tab Expands the web UI Tools tab with safe, purpose-built controls so users can manage the Pi without SSHing in, instead of an arbitrary-command terminal (the web UI has no auth and CSRF is disabled, so a shell would be unsafe). - System Diagnostics card: renders the existing but previously-unused GET /api/v3/system/status endpoint (CPU, memory, temp, disk, uptime), with a manual refresh and a 10s poll. - System Power section: reboot/shutdown buttons wired to the existing reboot_system / shutdown_system actions, behind a confirm step, with a dedicated powerAction() helper that treats the dropped connection as the expected "going offline" outcome rather than an error. - Network Radio section: WiFi on/off toggle backed by new GET/POST /api/v3/wifi/radio endpoints and WiFiManager.set_wifi_radio() / get_wifi_radio_state(). Disabling WiFi is refused unless a wired connection is present (reusing the existing lockout guards), with an explicit force-off confirmation for advanced users. No new privileged commands: uses nmcli radio wifi on|off (already sudo-allowlisted) and the existing reboot/poweroff grants, so the sudoers-alignment guard test stays green. Bluetooth toggle intentionally omitted since the installer removes the BlueZ stack for LED timing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019X3he87Ggr1qt8y7mnFeuE * Harden WiFi radio endpoint and diagnostics poll (review feedback) Addresses code review feedback on the Tools tab additions: - api_v3.py: parse the `enabled` POST field with the same string-aware coercion as `force`. A plain bool() cast turned {"enabled":"false"} into True (enabling instead of disabling) for any non-UI API caller. - wifi_manager.set_wifi_radio() now returns a reason code alongside (success, message); the /wifi/radio error response includes it. The Tools UI only shows the force-off confirmation when reason == 'no_ethernet', so a genuine nmcli failure surfaces its real error instead of a misleading "no wired connection" prompt that would just retry into the same failure. - tools.html: gate the 10s diagnostics poll on panel visibility (document.hidden / offsetParent), so switching to another tab stops the recurring /api/v3/system/status calls instead of churning the Pi off-screen. The initial load and manual Refresh remain unconditional. Verified: {"enabled":"false"} now disables (refused w/ reason:no_ethernet), {"enabled":"true"} enables; inline JS passes node --check; py_compile clean. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019X3he87Ggr1qt8y7mnFeuE * Narrow WiFi-disable fallback except and add stack trace (review) Addresses a CodeRabbit nitpick: the fallback handler in set_wifi_radio()'s disable path caught bare Exception and logged without a traceback. Narrow it to (OSError, subprocess.SubprocessError) — the errors subprocess.run realistically raises — and log with exc_info=True for full context on the Pi. Anything genuinely unexpected now propagates to the endpoint's outer handler (500), matching the codebase's specific-exception convention. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019X3he87Ggr1qt8y7mnFeuE --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
+90
-1
@@ -1883,7 +1883,96 @@ class WiFiManager:
|
||||
|
||||
logger.warning(f"Failed to enable WiFi radio after {max_retries} attempts")
|
||||
return False
|
||||
|
||||
|
||||
def get_wifi_radio_state(self) -> Dict:
|
||||
"""
|
||||
Report whether the WiFi radio is currently enabled, plus whether a wired
|
||||
fallback exists. Used by the web UI's radio toggle so it can warn before
|
||||
an action that could disconnect the browser.
|
||||
|
||||
Returns:
|
||||
{
|
||||
'enabled': Optional[bool], # True/False, or None if undeterminable
|
||||
'ethernet_connected': bool, # wired fallback present
|
||||
'available': bool, # nmcli present / radio state readable
|
||||
}
|
||||
"""
|
||||
ethernet_connected = self._is_ethernet_connected()
|
||||
enabled: Optional[bool] = None
|
||||
available = False
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["nmcli", "radio", "wifi"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5
|
||||
)
|
||||
if result.returncode == 0:
|
||||
status = result.stdout.strip().lower()
|
||||
if status in ("enabled", "disabled"):
|
||||
enabled = status == "enabled"
|
||||
available = True
|
||||
except Exception as e:
|
||||
logger.debug(f"Could not read WiFi radio state: {e}")
|
||||
return {
|
||||
'enabled': enabled,
|
||||
'ethernet_connected': ethernet_connected,
|
||||
'available': available,
|
||||
}
|
||||
|
||||
def set_wifi_radio(self, enabled: bool, force: bool = False) -> Tuple[bool, str, Optional[str]]:
|
||||
"""
|
||||
Turn the WiFi radio on or off.
|
||||
|
||||
Turning the radio OFF from the web interface is dangerous: if the device
|
||||
is reachable only over WiFi, disabling it disconnects the very page that
|
||||
issued the request. To prevent that lockout, disabling is refused unless a
|
||||
wired (Ethernet) fallback is present, or the caller explicitly passes
|
||||
force=True to acknowledge the risk.
|
||||
|
||||
Enabling reuses the hardened _ensure_wifi_radio_enabled() path (handles
|
||||
rfkill soft-blocks + retries). Both directions rely only on
|
||||
`nmcli radio wifi on|off`, which is already covered by the passwordless
|
||||
sudoers allowlist (configure_wifi_permissions.sh) — no new privileged
|
||||
command is introduced.
|
||||
|
||||
Returns:
|
||||
(success, human-readable message, reason_code). reason_code is
|
||||
'no_ethernet' when a disable is refused for lockout safety, or a
|
||||
short failure code otherwise; None on success. The web UI keys on
|
||||
'no_ethernet' to decide whether to offer a force-off prompt.
|
||||
"""
|
||||
if enabled:
|
||||
if self._ensure_wifi_radio_enabled():
|
||||
return True, "WiFi radio enabled.", None
|
||||
return False, "Failed to enable WiFi radio. Check logs for details.", 'enable_failed'
|
||||
|
||||
# Disabling — guard against locking the user out of the web interface.
|
||||
if not force and not self._is_ethernet_connected():
|
||||
return False, (
|
||||
"Refusing to disable WiFi: no wired (Ethernet) connection was "
|
||||
"detected, so turning off WiFi would disconnect you from this "
|
||||
"page. Connect Ethernet first, or force it if you're sure."
|
||||
), 'no_ethernet'
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["sudo", "nmcli", "radio", "wifi", "off"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10
|
||||
)
|
||||
if result.returncode == 0:
|
||||
logger.info("WiFi radio disabled via web interface (force=%s)", force)
|
||||
return True, "WiFi radio disabled.", None
|
||||
logger.warning("Failed to disable WiFi radio: %s", result.stderr.strip())
|
||||
return False, "Failed to disable WiFi radio. Check logs for details.", 'command_failed'
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "Command timed out while disabling WiFi radio.", 'timeout'
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
logger.error("Error disabling WiFi radio: %s", e, exc_info=True)
|
||||
return False, "An error occurred while disabling WiFi radio.", 'error'
|
||||
|
||||
def enable_ap_mode(self, force: bool = False) -> Tuple[bool, str]:
|
||||
"""
|
||||
Enable access point mode
|
||||
|
||||
Reference in New Issue
Block a user