Initial commit - Phase 3/4

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
michael
2026-01-06 13:45:29 -08:00
parent 1da6730735
commit 4f35df1781
323 changed files with 98287 additions and 1195 deletions

View File

@@ -0,0 +1,6 @@
"""WebSocket module for real-time notifications."""
from .manager import ws_manager, ConnectionManager
from .routes import router
from . import notifications
__all__ = ["ws_manager", "ConnectionManager", "router", "notifications"]

View File

@@ -0,0 +1,71 @@
"""WebSocket connection manager for real-time notifications."""
import asyncio
import json
from datetime import datetime, timezone
from typing import Set
from fastapi import WebSocket
class ConnectionManager:
"""Manages WebSocket connections and broadcasts."""
def __init__(self):
self._connections: Set[WebSocket] = set()
self._lock = asyncio.Lock()
async def connect(self, websocket: WebSocket) -> None:
"""Accept and track a new WebSocket connection."""
await websocket.accept()
async with self._lock:
self._connections.add(websocket)
# Send initial connected event
await self._send_to_client(websocket, {
"type": "event",
"event": "connected",
"data": {"message": "Connected to Dangerous Pi event stream"},
"timestamp": datetime.now(timezone.utc).isoformat()
})
async def disconnect(self, websocket: WebSocket) -> None:
"""Remove a disconnected WebSocket."""
async with self._lock:
self._connections.discard(websocket)
async def broadcast(self, event_type: str, data: dict) -> None:
"""Broadcast an event to all connected clients."""
message = {
"type": "event",
"event": event_type,
"data": data,
"timestamp": datetime.now(timezone.utc).isoformat()
}
async with self._lock:
dead_connections: Set[WebSocket] = set()
for connection in self._connections:
try:
await asyncio.wait_for(
self._send_to_client(connection, message),
timeout=5.0
)
except asyncio.TimeoutError:
dead_connections.add(connection)
except Exception:
dead_connections.add(connection)
# Remove dead connections
self._connections -= dead_connections
async def _send_to_client(self, websocket: WebSocket, message: dict) -> None:
"""Send a message to a specific client."""
await websocket.send_json(message)
@property
def connection_count(self) -> int:
"""Return number of active connections."""
return len(self._connections)
# Global singleton instance
ws_manager = ConnectionManager()

View File

@@ -0,0 +1,168 @@
"""Helper functions for sending WebSocket notifications."""
from .manager import ws_manager
# System Stats
async def notify_system_stats(
cpu_percent: float,
cpu_per_core: list,
load_average: list,
memory_percent: float,
temperature: float | None
) -> None:
"""Notify clients of system stats update."""
await ws_manager.broadcast("system_stats", {
"cpu_percent": cpu_percent,
"cpu_per_core": cpu_per_core,
"load_average": load_average,
"memory_percent": memory_percent,
"temperature": temperature
})
# PM3 Notifications
async def notify_pm3_status(connected: bool, message: str) -> None:
"""Notify clients of PM3 status changes."""
await ws_manager.broadcast("pm3_status", {
"connected": connected,
"message": message
})
async def notify_pm3_devices(devices: list) -> None:
"""Notify clients of PM3 device list changes (connect/disconnect)."""
await ws_manager.broadcast("pm3_devices", {
"devices": devices,
"count": len(devices)
})
async def notify_pm3_flash_progress(
device_id: str,
status: str,
progress: int,
message: str
) -> None:
"""Notify clients of PM3 firmware flash progress.
Args:
device_id: The device being flashed
status: Flash status - "starting", "bootrom", "fullimage", "verifying", "complete", "error"
progress: Progress percentage 0-100
message: Human-readable status message
"""
await ws_manager.broadcast("pm3_flash_progress", {
"device_id": device_id,
"status": status,
"progress": progress,
"message": message
})
# UPS Notifications
async def notify_ups_battery(percentage: float, voltage: float) -> None:
"""Notify clients of UPS battery status."""
await ws_manager.broadcast("ups_battery", {
"percentage": percentage,
"voltage": voltage
})
async def notify_ups_warning(percentage: float, threshold: float) -> None:
"""Notify clients of low battery warning."""
await ws_manager.broadcast("ups_warning", {
"percentage": percentage,
"threshold": threshold,
"message": f"Battery low: {percentage}%"
})
async def notify_ups_critical(percentage: float) -> None:
"""Notify clients of critical battery level."""
await ws_manager.broadcast("ups_critical", {
"percentage": percentage,
"message": f"Battery critical: {percentage}%"
})
async def notify_ups_shutdown(delay: int, percentage: float) -> None:
"""Notify clients that shutdown has been initiated."""
await ws_manager.broadcast("ups_shutdown", {
"delay": delay,
"percentage": percentage,
"message": f"Shutdown initiated due to low battery ({percentage}%)"
})
async def notify_ups_config_required(model: str, message: str, hint: str) -> None:
"""Notify clients that UPS configuration is required."""
await ws_manager.broadcast("ups_config_required", {
"model": model,
"message": message,
"hint": hint
})
# Update Notifications
async def notify_update_available(version: str, url: str) -> None:
"""Notify clients that an update is available."""
await ws_manager.broadcast("update_available", {
"version": version,
"url": url
})
async def notify_update_progress(progress: float, status: str) -> None:
"""Notify clients of update download progress."""
await ws_manager.broadcast("update_downloading", {
"progress": progress,
"status": status
})
async def notify_backup_complete(backup_path: str, size_bytes: int) -> None:
"""Notify clients that backup is complete."""
await ws_manager.broadcast("backup_complete", {
"path": backup_path,
"size": size_bytes
})
# Plugin Notifications
async def notify_plugin_event(
plugin_id: str,
event_type: str,
data: dict
) -> None:
"""Notify clients of a plugin event.
Plugin events are namespaced with 'plugin.{plugin_id}.{event_type}'.
This function is called by PluginBase.broadcast_event() and should
not be called directly by plugins.
Args:
plugin_id: The ID of the plugin sending the event
event_type: Full event type (already namespaced)
data: Event data dictionary
"""
await ws_manager.broadcast(event_type, {
"plugin_id": plugin_id,
**data
})
# Widget Notifications
async def notify_widget_added(widget_id: str, severity: str, message: str) -> None:
"""Notify clients that a header widget was added."""
await ws_manager.broadcast("widget_added", {
"widget_id": widget_id,
"severity": severity,
"message": message
})
async def notify_widget_removed(widget_id: str) -> None:
"""Notify clients that a header widget was removed."""
await ws_manager.broadcast("widget_removed", {
"widget_id": widget_id
})

View File

@@ -0,0 +1,35 @@
"""WebSocket endpoint routes."""
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from .manager import ws_manager
router = APIRouter()
@router.websocket("/events")
async def websocket_endpoint(websocket: WebSocket):
"""WebSocket endpoint for real-time event streaming.
Events include:
- connected: Initial connection confirmation
- system_stats: CPU, memory, temperature updates (every 5s)
- pm3_devices: Device list on connect/disconnect
- pm3_status: PM3 connection status changes
- ups_battery: Battery level updates
- ups_warning: Low battery warning
- ups_critical: Critical battery level
- ups_shutdown: Shutdown initiated
- ups_config_required: UPS needs configuration
- update_available: New version available
- update_downloading: Download progress
"""
await ws_manager.connect(websocket)
try:
while True:
# Keep connection alive by waiting for messages or disconnect
# Client doesn't send data, but we need to detect disconnection
try:
await websocket.receive_text()
except WebSocketDisconnect:
break
finally:
await ws_manager.disconnect(websocket)