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

63
app/backend/api/auth.py Normal file
View File

@@ -0,0 +1,63 @@
"""Authentication module for Dangerous Pi API."""
import secrets
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from .. import config
security = HTTPBasic()
def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)) -> str:
"""Verify HTTP Basic Auth credentials.
Args:
credentials: HTTP Basic credentials from request
Returns:
Username if authentication successful
Raises:
HTTPException: If authentication fails
"""
if not config.AUTH_ENABLED:
return "anonymous"
if not config.AUTH_PASSWORD:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="AUTH_ENABLED is true but AUTH_PASSWORD is not set",
)
# Use constant-time comparison to prevent timing attacks
is_correct_username = secrets.compare_digest(
credentials.username.encode("utf-8"),
config.AUTH_USERNAME.encode("utf-8")
)
is_correct_password = secrets.compare_digest(
credentials.password.encode("utf-8"),
config.AUTH_PASSWORD.encode("utf-8")
)
if not (is_correct_username and is_correct_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
def get_optional_auth(credentials: HTTPBasicCredentials = Depends(security)) -> str | None:
"""Optional authentication - returns username or None.
Use this for endpoints where auth is optional based on config.
"""
if not config.AUTH_ENABLED:
return None
try:
return verify_credentials(credentials)
except HTTPException:
return None

View File

@@ -1,6 +1,7 @@
"""Health check endpoints."""
from fastapi import APIRouter
from pydantic import BaseModel
import aiosqlite
router = APIRouter()
@@ -21,6 +22,28 @@ async def health_check():
@router.get("/ready")
async def readiness_check():
"""Readiness check endpoint."""
# TODO: Check if PM3 is connected, database is accessible, etc.
return {"ready": True}
"""Readiness check endpoint.
Checks:
- Database connectivity
"""
from .. import config
checks = {"database": False}
reasons = []
# Check database connectivity
try:
async with aiosqlite.connect(config.DATABASE_PATH) as db:
await db.execute("SELECT 1")
checks["database"] = True
except Exception as e:
reasons.append(f"Database: {str(e)}")
all_ready = all(checks.values())
return {
"ready": all_ready,
"checks": checks,
"reasons": reasons if not all_ready else None
}

View File

@@ -1,20 +1,29 @@
"""Proxmark3 API endpoints."""
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from typing import Optional
import asyncio
"""Proxmark3 API endpoints.
from ..workers.pm3_worker import PM3Worker, PM3Command
from ..managers.session_manager import SessionManager
Refactored to use PM3Service for all business logic.
Endpoints are now thin adapters that convert HTTP requests/responses.
Multi-device support:
- GET /devices - List all devices
- GET /devices/available - List available devices
- POST /devices/{device_id}/identify - Blink device LEDs
- GET /devices/{device_id}/status - Get device-specific status
- GET /status?device_id=xxx - Get status (all devices or specific)
- POST /command - Execute command (with optional device_id)
"""
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
from ..services.container import container
router = APIRouter()
pm3_worker = PM3Worker()
session_manager = SessionManager()
class CommandRequest(BaseModel):
command: str
session_id: Optional[str] = None
device_id: Optional[str] = None # Multi-device support
class CommandResponse(BaseModel):
@@ -30,79 +39,426 @@ class StatusResponse(BaseModel):
session_active: bool
@router.get("/status", response_model=StatusResponse)
async def get_status():
"""Get Proxmark3 status."""
is_connected = await pm3_worker.is_connected()
version = None
class FirmwareInfo(BaseModel):
"""Firmware information for a device."""
bootrom_version: Optional[str] = None
os_version: Optional[str] = None
compatible: bool = False
if is_connected:
# Try to get version info
result = await pm3_worker.execute_command("hw version")
if result.success:
version = result.output.split("\n")[0] if result.output else None
class DeviceInfo(BaseModel):
"""Device information response."""
device_id: str
device_path: str
friendly_name: Optional[str] = None
serial_number: Optional[str] = None
status: str
connected: bool
in_use: bool
firmware_info: FirmwareInfo
usb_vid: Optional[str] = None
usb_pid: Optional[str] = None
last_seen: str
class DeviceListResponse(BaseModel):
"""Response for device list endpoints."""
devices: List[DeviceInfo]
class DeviceStatusResponse(BaseModel):
"""Response for single device status."""
device_id: str
device_path: str
friendly_name: Optional[str] = None
serial_number: Optional[str] = None
connected: bool
in_use: bool
status: str
firmware_info: FirmwareInfo
last_seen: str
class IdentifyRequest(BaseModel):
"""Request to identify a device (blink LEDs)."""
duration_ms: int = Field(default=2000, ge=500, le=10000, description="LED blink duration in milliseconds")
class FlashRequest(BaseModel):
"""Request to flash firmware to a device."""
confirm: bool = Field(..., description="User confirmation that they want to flash")
class FlashResponse(BaseModel):
"""Response from flash operation."""
success: bool
message: str
device_id: str
def _service_error_to_http_status(error_code: str) -> int:
"""Map service error codes to HTTP status codes.
Args:
error_code: Service error code
Returns:
HTTP status code
"""
codes = {
# Session errors
"session_locked": 423,
"session_not_found": 404,
# Connection errors
"pm3_not_connected": 503,
"connection_error": 503,
"disconnection_error": 500,
# Command execution errors
"command_failed": 500,
"execution_error": 500,
"status_error": 500,
# Multi-device errors
"device_not_found": 404,
"device_manager_not_available": 503,
"list_devices_error": 500,
"get_available_devices_error": 500,
"identify_device_error": 500,
# Firmware flash errors
"device_busy": 409,
"flash_failed": 500,
"flash_error": 500,
}
return codes.get(error_code, 500)
@router.get("/status")
async def get_status(device_id: Optional[str] = Query(None, description="Optional device ID for multi-device support")):
"""Get Proxmark3 status.
Multi-device support:
- If device_id is None and device_manager exists: returns all devices
- If device_id is provided: returns specific device status
- If device_id is None and no device_manager: returns legacy single device status
Args:
device_id: Optional device ID for multi-device mode
Returns:
StatusResponse (legacy single device) or dict with devices list (multi-device)
"""
result = await container.pm3_service.get_status(device_id=device_id)
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
# Multi-device mode: return all devices
if "devices" in result.data:
return {"devices": result.data["devices"]}
# Single device mode (specific device or legacy)
return StatusResponse(
connected=is_connected,
device=pm3_worker.device_path,
version=version,
session_active=session_manager.has_active_session()
connected=result.data["connected"],
device=result.data["device_path"],
version=result.data.get("version"),
session_active=result.data["session_active"]
)
@router.post("/connect")
async def connect():
"""Connect to Proxmark3 device."""
try:
await pm3_worker.connect()
return {"success": True, "message": "Connected to Proxmark3"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
"""Connect to Proxmark3 device.
Uses PM3Service for business logic.
"""
result = await container.pm3_service.connect()
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return {"success": True, "message": result.data["message"]}
@router.post("/disconnect")
async def disconnect():
"""Disconnect from Proxmark3 device."""
try:
await pm3_worker.disconnect()
return {"success": True, "message": "Disconnected from Proxmark3"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
"""Disconnect from Proxmark3 device.
Uses PM3Service for business logic.
"""
result = await container.pm3_service.disconnect()
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return {"success": True, "message": result.data["message"]}
@router.post("/command", response_model=CommandResponse)
async def execute_command(request: CommandRequest):
"""Execute a Proxmark3 command."""
try:
# Check if another session is active
if not session_manager.can_execute(request.session_id):
"""Execute a Proxmark3 command.
Uses PM3Service for all business logic including:
- Session validation
- Command execution
- Session activity updates
- Multi-device support (via device_id in request)
Multi-device support:
- If device_id is provided: command executes on specified device
- If device_id is None: uses legacy single-device mode
Args:
request: CommandRequest with command, optional session_id, and optional device_id
"""
result = await container.pm3_service.execute_command(
command=request.command,
session_id=request.session_id,
device_id=request.device_id
)
if result.success:
return CommandResponse(
success=True,
output=result.data["output"],
error=None
)
else:
# For session_locked, return 423 via HTTPException
# For other errors, return in response body
if result.error.code == "session_locked":
raise HTTPException(
status_code=423,
detail="Another session is active. Please take over or wait."
detail=result.error.message
)
# Execute command
result = await pm3_worker.execute_command(request.command)
# Include details in error message for better diagnostics
error_msg = result.error.message
if result.error.details:
error_msg = f"{error_msg}: {result.error.details}"
# Update session activity
if request.session_id:
session_manager.update_activity(request.session_id)
return CommandResponse(
success=result.success,
output=result.output,
error=result.error
)
except Exception as e:
return CommandResponse(
success=False,
output="",
error=str(e)
error=error_msg
)
@router.get("/commands/history")
async def get_command_history(limit: int = 50):
"""Get recent command history."""
# TODO: Implement database query
return {"history": []}
"""Get recent command history from database."""
import aiosqlite
from .. import config
try:
async with aiosqlite.connect(config.DATABASE_PATH) as db:
db.row_factory = aiosqlite.Row
cursor = await db.execute(
"SELECT command, response, success, executed_at FROM command_history ORDER BY executed_at DESC LIMIT ?",
(limit,)
)
rows = await cursor.fetchall()
return {"history": [dict(row) for row in rows]}
except Exception as e:
return {"history": [], "error": str(e)}
# ============================================================================
# Multi-Device Endpoints
# ============================================================================
@router.get("/devices", response_model=DeviceListResponse)
async def list_devices():
"""List all discovered PM3 devices.
Returns all devices regardless of their status (connected, in use, etc.).
Uses PM3DeviceManager via PM3Service.
Returns:
DeviceListResponse: List of all devices with their status and firmware info
"""
result = await container.pm3_service.list_devices()
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
# Convert device dictionaries to DeviceInfo models
devices = []
for device_dict in result.data["devices"]:
devices.append(DeviceInfo(
device_id=device_dict["device_id"],
device_path=device_dict["device_path"],
friendly_name=device_dict.get("friendly_name"),
serial_number=device_dict.get("serial_number"),
status=device_dict["status"],
connected=device_dict["status"] in ["CONNECTED", "IN_USE"],
in_use=device_dict["status"] == "IN_USE",
firmware_info=FirmwareInfo(
bootrom_version=device_dict["firmware_info"].get("bootrom_version"),
os_version=device_dict["firmware_info"].get("os_version"),
compatible=device_dict["firmware_info"].get("compatible", False)
),
usb_vid=device_dict.get("usb_vid"),
usb_pid=device_dict.get("usb_pid"),
last_seen=device_dict["last_seen"]
))
return DeviceListResponse(devices=devices)
@router.get("/devices/available", response_model=DeviceListResponse)
async def list_available_devices():
"""List available PM3 devices (not currently in use).
Returns only devices that are connected but do not have active sessions.
These devices can be selected for new operations.
Returns:
DeviceListResponse: List of available devices
"""
result = await container.pm3_service.get_available_devices()
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
# Convert device dictionaries to DeviceInfo models
devices = []
for device_dict in result.data["devices"]:
devices.append(DeviceInfo(
device_id=device_dict["device_id"],
device_path=device_dict["device_path"],
friendly_name=device_dict.get("friendly_name"),
serial_number=device_dict.get("serial_number"),
status=device_dict["status"],
connected=device_dict["status"] in ["CONNECTED", "IN_USE"],
in_use=device_dict["status"] == "IN_USE",
firmware_info=FirmwareInfo(
bootrom_version=device_dict["firmware_info"].get("bootrom_version"),
os_version=device_dict["firmware_info"].get("os_version"),
compatible=device_dict["firmware_info"].get("compatible", False)
),
usb_vid=device_dict.get("usb_vid"),
usb_pid=device_dict.get("usb_pid"),
last_seen=device_dict["last_seen"]
))
return DeviceListResponse(devices=devices)
@router.post("/devices/{device_id}/identify")
async def identify_device(device_id: str, request: IdentifyRequest = IdentifyRequest()):
"""Identify a PM3 device by blinking its LEDs.
Useful for physically identifying which device corresponds to a device_id
when multiple devices are connected.
Args:
device_id: Device ID to identify
request: Request with optional duration_ms (default: 2000ms)
Returns:
Success message
"""
result = await container.pm3_service.identify_device(
device_id=device_id,
duration_ms=request.duration_ms
)
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return {"success": True, "message": result.data["message"]}
@router.get("/devices/{device_id}/status", response_model=DeviceStatusResponse)
async def get_device_status(device_id: str):
"""Get status for a specific PM3 device.
Args:
device_id: Device ID to query
Returns:
DeviceStatusResponse: Device status and firmware info
"""
result = await container.pm3_service.get_status(device_id=device_id)
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
data = result.data
return DeviceStatusResponse(
device_id=data["device_id"],
device_path=data["device_path"],
friendly_name=data.get("friendly_name"),
serial_number=data.get("serial_number"),
connected=data["connected"],
in_use=data["in_use"],
status=data["status"],
firmware_info=FirmwareInfo(
bootrom_version=data["firmware_info"]["bootrom_version"],
os_version=data["firmware_info"]["os_version"],
compatible=data["firmware_info"]["compatible"]
),
last_seen=data["last_seen"]
)
@router.post("/devices/{device_id}/flash", response_model=FlashResponse)
async def flash_device(device_id: str, request: FlashRequest):
"""Flash firmware to a PM3 device.
Flashes both bootrom and fullimage from bundled firmware files.
Progress is reported via WebSocket notifications (pm3_flash_progress event).
Args:
device_id: Device ID to flash
request: FlashRequest with confirmation
Returns:
FlashResponse with success status and message
Raises:
HTTPException 400: If confirmation not provided
HTTPException 404: If device not found
HTTPException 409: If device is already being flashed
HTTPException 500: If flash operation fails
"""
if not request.confirm:
raise HTTPException(
status_code=400,
detail="Confirmation required. Set confirm=true to proceed with flash."
)
result = await container.pm3_service.flash_firmware(device_id=device_id)
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message if not result.error.details else f"{result.error.message}: {result.error.details}"
)
return FlashResponse(
success=True,
message=result.data["message"],
device_id=device_id
)

View File

@@ -1,39 +1,62 @@
"""System API endpoints."""
"""System API endpoints.
Refactored to use services for business logic.
Session management uses PM3Service, system operations use SystemService.
"""
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from typing import Optional, Dict
from ..managers.session_manager import SessionManager
from ..services.container import container
from ..managers.ups_manager import get_ups_manager
from ..managers.ble_manager import get_ble_manager
router = APIRouter()
session_manager = SessionManager()
class CreateSessionRequest(BaseModel):
force_takeover: bool = False
device_id: Optional[str] = None # Device to create session for
class CreateSessionResponse(BaseModel):
success: bool
session_id: Optional[str] = None
device_id: Optional[str] = None
error: Optional[str] = None
class SessionInfo(BaseModel):
session_id: str
device_id: Optional[str]
client_ip: str
created_at: float
last_activity: float
time_remaining: float
class CPUCoreInfo(BaseModel):
"""Per-core CPU information."""
core_id: int
percent: float
online: bool = True # Whether this core is currently enabled
class CPUInfo(BaseModel):
"""CPU information including per-core data."""
count: int
percent: float
temperature: Optional[float] = None
per_core: list[CPUCoreInfo] = []
load_average: Optional[list[float]] = None
class SystemInfo(BaseModel):
"""System information response."""
hostname: str
uptime: float
cpu_temp: Optional[float]
cpu: Optional[CPUInfo] = None
memory_used: float
memory_total: float
disk_used: float
@@ -42,38 +65,70 @@ class SystemInfo(BaseModel):
@router.post("/session/create", response_model=CreateSessionResponse)
async def create_session(request: Request, body: CreateSessionRequest):
"""Create a new session for PM3 access."""
"""Create a new session for PM3 access.
Uses PM3Service for session management.
Optionally specify device_id for multi-device support.
"""
# Get client IP from request
client_ip = request.client.host if request.client else "unknown"
user_agent = request.headers.get("user-agent")
success, session_id, error = await session_manager.create_session(
result = await container.pm3_service.create_session(
client_ip=client_ip,
user_agent=user_agent,
force_takeover=body.force_takeover
force_takeover=body.force_takeover,
device_id=body.device_id
)
return CreateSessionResponse(
success=success,
session_id=session_id,
error=error
)
if result.success:
return CreateSessionResponse(
success=True,
session_id=result.data["session_id"],
device_id=result.data.get("device_id"),
error=None
)
else:
return CreateSessionResponse(
success=False,
session_id=None,
device_id=None,
error=result.error.message
)
@router.post("/session/{session_id}/release")
async def release_session(session_id: str):
"""Release an active session."""
success = await session_manager.release_session(session_id)
async def release_session(session_id: str, device_id: Optional[str] = None):
"""Release an active session.
if not success:
raise HTTPException(status_code=404, detail="Session not found")
Uses PM3Service for session management.
return {"success": True, "message": "Session released"}
Args:
session_id: Session ID to release
device_id: Optional device ID for faster lookup
"""
result = await container.pm3_service.release_session(session_id, device_id)
if not result.success:
raise HTTPException(
status_code=404,
detail=result.error.message
)
return {"success": True, "message": result.data["message"]}
@router.get("/session/active", response_model=Optional[SessionInfo])
async def get_active_session():
"""Get information about the active session."""
session = session_manager.get_active_session()
async def get_active_session(device_id: Optional[str] = None):
"""Get information about the active session for a device.
Uses PM3Service (via SessionManager) for session info.
Args:
device_id: Optional device ID. If None, returns any active session.
"""
# Access session manager through container for consistency
session = container.session_manager.get_active_session(device_id)
if not session:
return None
@@ -85,6 +140,7 @@ async def get_active_session():
return SessionInfo(
session_id=session.session_id,
device_id=session.device_id,
client_ip=session.client_ip,
created_at=session.created_at,
last_activity=session.last_activity,
@@ -92,36 +148,63 @@ async def get_active_session():
)
@router.get("/sessions/all")
async def get_all_sessions():
"""Get all active sessions across all devices.
Returns a list of all active sessions with their device IDs.
"""
result = container.pm3_service.get_all_sessions()
return result.data
@router.get("/info", response_model=SystemInfo)
async def get_system_info():
"""Get system information."""
import platform
import psutil
from pathlib import Path
"""Get system information.
# Get CPU temperature (Raspberry Pi specific)
cpu_temp = None
try:
temp_file = Path("/sys/class/thermal/thermal_zone0/temp")
if temp_file.exists():
cpu_temp = int(temp_file.read_text()) / 1000.0
except Exception:
pass
Refactored to use SystemService for business logic.
"""
from ..services.container import container
# Get memory info
memory = psutil.virtual_memory()
result = await container.system_service.get_info()
# Get disk info
disk = psutil.disk_usage('/')
if not result.success:
raise HTTPException(
status_code=500,
detail=result.error.message
)
cpu_data = result.data["cpu"]
memory_data = result.data["memory"]
disk_data = result.data["disk"]
# Build per-core CPU info
per_core = [
CPUCoreInfo(
core_id=c["core_id"],
percent=c["percent"],
online=c.get("online", True)
)
for c in cpu_data.get("per_core", [])
]
cpu_info = CPUInfo(
count=cpu_data.get("count", 0),
percent=cpu_data.get("percent", 0.0),
temperature=cpu_data.get("temperature"),
per_core=per_core,
load_average=cpu_data.get("load_average")
)
return SystemInfo(
hostname=platform.node(),
uptime=psutil.boot_time(),
cpu_temp=cpu_temp,
memory_used=memory.used,
memory_total=memory.total,
disk_used=disk.used,
disk_total=disk.total
hostname=result.data["hostname"],
uptime=result.data["uptime"],
cpu_temp=cpu_data.get("temperature"),
cpu=cpu_info,
memory_used=memory_data["used"],
memory_total=memory_data["total"],
disk_used=disk_data["used"],
disk_total=disk_data["total"]
)
@@ -129,11 +212,15 @@ async def get_system_info():
async def get_config():
"""Get system configuration (non-sensitive values)."""
from .. import config
from ..services.container import container
# Get WiFi mode from manager, default to AP mode
wifi_mode = container.wifi_manager._current_mode.value if container.wifi_manager else "ap"
return {
"pm3_device": config.PM3_DEVICE,
"session_timeout": config.SESSION_TIMEOUT,
"wifi_mode": "auto", # TODO: Get from wifi manager
"wifi_mode": wifi_mode,
"ble_enabled": config.BLE_ENABLED,
"auth_enabled": config.AUTH_ENABLED,
"https_enabled": config.HTTPS_ENABLED
@@ -141,17 +228,47 @@ async def get_config():
@router.post("/restart")
async def restart_system():
"""Restart the backend application."""
# TODO: Implement graceful restart
return {"success": True, "message": "Restart initiated"}
async def restart_system(delay: int = 0):
"""Restart the system.
Refactored to use SystemService for business logic.
Args:
delay: Delay in seconds before restart (default: 0)
"""
from ..services.container import container
result = await container.system_service.restart(delay=delay)
if not result.success:
raise HTTPException(
status_code=500,
detail=result.error.message
)
return {"success": True, "message": result.data["message"]}
@router.post("/shutdown")
async def shutdown_system():
"""Initiate system shutdown."""
# TODO: Implement safe shutdown sequence
return {"success": True, "message": "Shutdown initiated"}
async def shutdown_system(delay: int = 0):
"""Initiate system shutdown.
Refactored to use SystemService for business logic.
Args:
delay: Delay in seconds before shutdown (default: 0)
"""
from ..services.container import container
result = await container.system_service.shutdown(delay=delay)
if not result.success:
raise HTTPException(
status_code=500,
detail=result.error.message
)
return {"success": True, "message": result.data["message"]}
class UPSStatusResponse(BaseModel):
@@ -174,6 +291,21 @@ class UPSThresholdsRequest(BaseModel):
warning_threshold: Optional[float] = None
class PowerRestrictionsResponse(BaseModel):
"""Power restrictions response model."""
restricted: bool
reason: Optional[str] = None
power_source: str
ups_available: bool
battery_percentage: Optional[float] = None
allow_firmware_flash: bool
allow_bootloader_flash: bool
allow_intensive_operations: bool
message: Optional[str] = None
warning: Optional[str] = None
shutdown_imminent: Optional[bool] = None
@router.get("/ups/status", response_model=UPSStatusResponse)
async def get_ups_status():
"""Get current UPS battery status."""
@@ -227,6 +359,140 @@ async def trigger_ups_shutdown(delay: int = 30):
}
@router.get("/power/restrictions", response_model=PowerRestrictionsResponse)
async def get_power_restrictions():
"""Get current power restrictions based on UPS/battery state.
Returns power policy information including:
- Whether operations are restricted
- Current power source (AC, battery, or assumed AC if no UPS)
- Battery level (if UPS present)
- Which operations are allowed (firmware flash, bootloader flash, etc.)
- User-friendly messages and warnings
This endpoint is critical for determining whether power-intensive
operations (like firmware flashing) should be allowed.
If UPS hardware is not detected, assumes stable AC power and allows
all operations (user responsibility to ensure power stability).
"""
ups_manager = get_ups_manager()
restrictions = ups_manager.get_power_restrictions()
return PowerRestrictionsResponse(**restrictions)
class PiModelResponse(BaseModel):
"""Pi model information response."""
model: str
model_short: str
total_cores: int
default_active_cores: int
min_cores: int
max_cores: int
class CPUCoresConfigResponse(BaseModel):
"""CPU cores configuration response."""
total_cores: int
online_cores: int
configured_cores: Optional[int] = None # From cmdline.txt maxcpus parameter
configurable_cores: list[int]
pi_model: Optional[PiModelResponse] = None
class SetCPUCoresRequest(BaseModel):
"""Request to set CPU cores."""
num_cores: int
persist: bool = True # Save to config for boot persistence
reboot: bool = True # Reboot after saving
@router.get("/cpu/cores", response_model=CPUCoresConfigResponse)
async def get_cpu_cores():
"""Get CPU cores configuration.
Returns information about:
- Total physical cores
- Currently online cores
- Which cores can be toggled (core 0 is always on)
- Pi model information with recommended defaults
"""
result = await container.system_service.get_cpu_cores_config()
if not result.success:
raise HTTPException(
status_code=500,
detail=result.error.message
)
# Convert pi_model dict to response model if present
pi_model_data = result.data.get("pi_model")
pi_model = None
if pi_model_data:
pi_model = PiModelResponse(**pi_model_data)
return CPUCoresConfigResponse(
total_cores=result.data["total_cores"],
online_cores=result.data["online_cores"],
configured_cores=result.data.get("configured_cores"),
configurable_cores=result.data["configurable_cores"],
pi_model=pi_model
)
@router.post("/cpu/cores")
async def set_cpu_cores(request: SetCPUCoresRequest):
"""Set the number of active CPU cores.
Core 0 is always active. This endpoint enables/disables cores 1 through N.
For Pi Zero 2 W, the recommended default is 2 cores (out of 4) for
better thermal management and power efficiency.
Args:
num_cores: Number of cores to keep active (1 to max_cores)
persist: Save setting to config file (default: True)
reboot: Reboot system after saving (default: True)
"""
result = await container.system_service.set_cpu_cores(
num_cores=request.num_cores,
persist=request.persist,
reboot=request.reboot
)
if not result.success:
raise HTTPException(
status_code=400 if result.error.code == "invalid_cores" else 500,
detail=result.error.message
)
return {
"success": True,
"message": result.data["message"],
"requested": result.data.get("requested"),
"actual": result.data.get("actual"),
"rebooting": result.data.get("rebooting", False)
}
@router.get("/pi/model", response_model=PiModelResponse)
async def get_pi_model():
"""Get Raspberry Pi model information.
Returns the detected Pi model with recommended CPU core settings.
"""
result = await container.system_service.get_pi_model()
if not result.success:
raise HTTPException(
status_code=500,
detail=result.error.message
)
return PiModelResponse(**result.data)
class BLEStatusResponse(BaseModel):
"""BLE status response model."""
enabled: bool
@@ -307,3 +573,317 @@ async def send_ble_notification(request: SendNotificationRequest):
"success": True,
"message": "Notification sent"
}
# -----------------------------------------------------------------------------
# SSL/HTTPS API
# -----------------------------------------------------------------------------
class SSLCertificateInfo(BaseModel):
"""SSL certificate information."""
enabled: bool
certificate_exists: bool
certificate_path: Optional[str] = None
key_path: Optional[str] = None
subject: Optional[str] = None
issuer: Optional[str] = None
not_before: Optional[str] = None
not_after: Optional[str] = None
san: Optional[list[str]] = None # Subject Alternative Names
fingerprint_sha256: Optional[str] = None
class SSLRegenerateRequest(BaseModel):
"""Request to regenerate SSL certificate."""
reload_nginx: bool = True
@router.get("/ssl/info", response_model=SSLCertificateInfo)
async def get_ssl_info():
"""Get SSL certificate information.
Returns details about the current SSL configuration including:
- Whether HTTPS is enabled
- Certificate existence and paths
- Certificate subject, issuer, validity dates
- Subject Alternative Names (SANs)
- SHA256 fingerprint
"""
import os
import subprocess
from .. import config
cert_path = "/opt/dangerous-pi/ssl/dangerous-pi.crt"
key_path = "/opt/dangerous-pi/ssl/dangerous-pi.key"
# Check if HTTPS is enabled and certificate exists
https_enabled = config.HTTPS_ENABLED
cert_exists = os.path.exists(cert_path)
key_exists = os.path.exists(key_path)
if not cert_exists:
return SSLCertificateInfo(
enabled=https_enabled,
certificate_exists=False,
certificate_path=cert_path,
key_path=key_path
)
# Parse certificate details using openssl
cert_info = {
"subject": None,
"issuer": None,
"not_before": None,
"not_after": None,
"san": [],
"fingerprint": None
}
try:
# Get subject
result = subprocess.run(
["openssl", "x509", "-in", cert_path, "-noout", "-subject"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
cert_info["subject"] = result.stdout.strip().replace("subject=", "")
# Get issuer
result = subprocess.run(
["openssl", "x509", "-in", cert_path, "-noout", "-issuer"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
cert_info["issuer"] = result.stdout.strip().replace("issuer=", "")
# Get validity dates
result = subprocess.run(
["openssl", "x509", "-in", cert_path, "-noout", "-dates"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
for line in result.stdout.strip().split("\n"):
if line.startswith("notBefore="):
cert_info["not_before"] = line.replace("notBefore=", "")
elif line.startswith("notAfter="):
cert_info["not_after"] = line.replace("notAfter=", "")
# Get SANs
result = subprocess.run(
["openssl", "x509", "-in", cert_path, "-noout", "-ext", "subjectAltName"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0 and "subjectAltName" in result.stdout:
# Parse SANs from output like "DNS:localhost, IP:192.168.4.1"
san_line = result.stdout.strip()
for line in san_line.split("\n"):
if "DNS:" in line or "IP:" in line:
# Split by comma and clean up
sans = [s.strip() for s in line.split(",")]
cert_info["san"] = [s for s in sans if s.startswith(("DNS:", "IP:"))]
break
# Get SHA256 fingerprint
result = subprocess.run(
["openssl", "x509", "-in", cert_path, "-noout", "-fingerprint", "-sha256"],
capture_output=True, text=True, timeout=5
)
if result.returncode == 0:
# Format: "sha256 Fingerprint=XX:XX:XX..."
fingerprint = result.stdout.strip()
if "=" in fingerprint:
cert_info["fingerprint"] = fingerprint.split("=", 1)[1]
except subprocess.TimeoutExpired:
pass # Return what we have
except Exception:
pass # Return what we have
return SSLCertificateInfo(
enabled=https_enabled,
certificate_exists=cert_exists and key_exists,
certificate_path=cert_path,
key_path=key_path,
subject=cert_info["subject"],
issuer=cert_info["issuer"],
not_before=cert_info["not_before"],
not_after=cert_info["not_after"],
san=cert_info["san"] if cert_info["san"] else None,
fingerprint_sha256=cert_info["fingerprint"]
)
@router.post("/ssl/regenerate")
async def regenerate_ssl_certificate(request: SSLRegenerateRequest):
"""Regenerate the self-signed SSL certificate.
This will:
1. Generate a new EC P-256 key and self-signed certificate
2. Optionally reload nginx to pick up the new certificate
The new certificate will be valid for 10 years and include SANs for:
- 192.168.4.1 (AP gateway IP)
- dangerous-pi.local (mDNS hostname)
- localhost
Args:
reload_nginx: Whether to reload nginx after regeneration (default: True)
Returns:
Success status and certificate info
"""
import subprocess
import os
script_path = "/opt/dangerous-pi/scripts/generate-ssl-cert.sh"
# Check if script exists
if not os.path.exists(script_path):
raise HTTPException(
status_code=500,
detail="SSL certificate generation script not found"
)
try:
# Run certificate generation with --force flag
result = subprocess.run(
[script_path, "--force"],
capture_output=True,
text=True,
timeout=30
)
if result.returncode != 0:
raise HTTPException(
status_code=500,
detail=f"Certificate generation failed: {result.stderr}"
)
# Reload nginx if requested
nginx_reloaded = False
if request.reload_nginx:
try:
nginx_result = subprocess.run(
["systemctl", "reload", "nginx"],
capture_output=True,
text=True,
timeout=10
)
nginx_reloaded = nginx_result.returncode == 0
except Exception:
pass # Non-fatal, certificate was still generated
return {
"success": True,
"message": "SSL certificate regenerated successfully",
"nginx_reloaded": nginx_reloaded,
"output": result.stdout
}
except subprocess.TimeoutExpired:
raise HTTPException(
status_code=500,
detail="Certificate generation timed out"
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Certificate generation error: {str(e)}"
)
# -----------------------------------------------------------------------------
# Header Widgets API
# -----------------------------------------------------------------------------
class WidgetResponse(BaseModel):
"""Header widget response model."""
id: str
source: str
severity: str
message: str
dismissible: bool
icon: Optional[str] = None
action_label: Optional[str] = None
action_url: Optional[str] = None
created_at: str
expires_at: Optional[str] = None
@router.get("/widgets", response_model=list[WidgetResponse])
async def get_header_widgets():
"""Get all active header widgets.
Returns widgets from:
- System managers (UPS, PM3, Updates)
- Enabled plugins
Widgets are sorted by severity (error > warning > info > success).
"""
from ..managers.plugin_manager import get_plugin_manager
plugin_manager = get_plugin_manager()
widgets = plugin_manager.get_active_widgets()
# Sort by severity (error first, then warning, info, success)
severity_order = {"error": 0, "warning": 1, "info": 2, "success": 3}
widgets.sort(key=lambda w: severity_order.get(w.severity.value, 99))
return [
WidgetResponse(
id=w.id,
source=w.source,
severity=w.severity.value,
message=w.message,
dismissible=w.dismissible,
icon=w.icon,
action_label=w.action_label,
action_url=w.action_url,
created_at=w.created_at or "",
expires_at=w.expires_at
)
for w in widgets
]
@router.post("/widgets/{widget_id}/dismiss")
async def dismiss_widget(widget_id: str):
"""Dismiss a header widget.
Dismissed widgets will not reappear until the server restarts
or the widget is explicitly re-registered.
Args:
widget_id: Full widget ID (e.g., "ups.hardware_missing", "plugin.hello_world.status")
Returns:
Success status
"""
from ..managers.plugin_manager import get_plugin_manager
plugin_manager = get_plugin_manager()
success = plugin_manager.dismiss_widget(widget_id)
if not success:
raise HTTPException(
status_code=404,
detail=f"Widget '{widget_id}' not found or not dismissible"
)
return {"success": True, "widget_id": widget_id}
@router.post("/widgets/clear-dismissed")
async def clear_dismissed_widgets():
"""Clear all dismissed widgets, allowing them to reappear.
This is useful if a user wants to see previously dismissed
notifications again.
"""
from ..managers.plugin_manager import get_plugin_manager
plugin_manager = get_plugin_manager()
plugin_manager.clear_dismissed()
return {"success": True, "message": "Dismissed widgets cleared"}

View File

@@ -1,9 +1,13 @@
"""Update management API endpoints."""
"""Update management API endpoints.
Refactored to use UpdateService for all business logic.
Endpoints are now thin adapters that convert HTTP requests/responses.
"""
from typing import Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from ..managers.update_manager import get_update_manager, UpdateStatus
from ..services.container import container
from ..managers.ble_manager import get_ble_manager, NotificationType
@@ -37,149 +41,165 @@ class ReleaseNotesRequest(BaseModel):
version: Optional[str] = None
def _service_error_to_http_status(error_code: str) -> int:
"""Map service error codes to HTTP status codes.
Args:
error_code: Service error code
Returns:
HTTP status code
"""
codes = {
"update_check_error": 500,
"no_update_available": 400,
"download_failed": 500,
"update_download_error": 500,
"no_update_downloaded": 400,
"installation_failed": 500,
"update_install_error": 500,
"progress_error": 500,
"release_notes_error": 500,
"check_download_error": 500,
"full_update_error": 500,
}
return codes.get(error_code, 500)
@router.get("/check", response_model=UpdateCheckResponse)
async def check_for_updates():
"""Check for available updates.
Returns:
UpdateCheckResponse with update status and info
Uses UpdateService for business logic.
"""
try:
manager = get_update_manager()
ble_manager = get_ble_manager()
result = await manager.check_for_updates()
result = await container.update_service.check_for_updates()
# Send BLE notification if update is available
if result.get("update_available"):
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
# Send BLE notification if update is available
if result.data.get("update_available"):
try:
ble_manager = get_ble_manager()
await ble_manager.send_notification(
NotificationType.UPDATE_AVAILABLE,
f"Update available: v{result['latest_version']}",
{"version": result["latest_version"]}
f"Update available: v{result.data['latest_version']}",
{"version": result.data["latest_version"]}
)
except Exception:
# BLE notification failure shouldn't affect the response
pass
return UpdateCheckResponse(**result)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return UpdateCheckResponse(**result.data)
@router.get("/progress", response_model=UpdateProgressResponse)
async def get_update_progress():
"""Get current update progress.
Returns:
UpdateProgressResponse with current status
Uses UpdateService for business logic.
"""
try:
manager = get_update_manager()
progress = await manager.get_progress()
result = await container.update_service.get_progress()
return UpdateProgressResponse(
status=progress.status.value,
current_version=progress.current_version,
available_version=progress.available_version,
download_progress=progress.download_progress,
error_message=progress.error_message,
last_check=progress.last_check
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return UpdateProgressResponse(**result.data)
@router.post("/download")
async def download_update():
"""Download the available update.
Returns:
Success message
Uses UpdateService for business logic.
"""
try:
manager = get_update_manager()
success = await manager.download_update()
result = await container.update_service.download_update()
if success:
return {"message": "Update downloaded successfully"}
else:
raise HTTPException(status_code=500, detail="Download failed")
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {"message": result.data["message"]}
@router.post("/install")
async def install_update():
"""Install the downloaded update.
Returns:
Success message
Uses UpdateService for business logic.
"""
result = await container.update_service.install_update()
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
# Send BLE notification
try:
manager = get_update_manager()
ble_manager = get_ble_manager()
success = await manager.install_update()
await ble_manager.send_notification(
NotificationType.UPDATE_COMPLETE,
"Update installed successfully",
{"restart_required": True}
)
except Exception:
# BLE notification failure shouldn't affect the response
pass
if success:
# Send BLE notification
await ble_manager.send_notification(
NotificationType.UPDATE_COMPLETE,
"Update installed successfully",
{"restart_required": True}
)
return {
"message": "Update installed successfully. Please restart the service.",
"restart_required": True
}
else:
raise HTTPException(status_code=500, detail="Installation failed")
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {
"message": result.data["message"],
"restart_required": result.data.get("requires_restart", True)
}
@router.post("/release-notes", response_model=dict)
async def get_release_notes(request: ReleaseNotesRequest):
"""Get release notes for a specific version.
Uses UpdateService for business logic.
Args:
request: Version to get notes for (latest if not specified)
Returns:
Release notes as markdown
"""
try:
manager = get_update_manager()
notes = await manager.get_release_notes(request.version)
result = await container.update_service.get_release_notes(request.version)
return {
"version": request.version or "latest",
"notes": notes
}
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {
"version": result.data["version"],
"notes": result.data["release_notes"]
}
@router.get("/current-version")
async def get_current_version():
"""Get current system version.
Returns:
Current version info
Uses UpdateService for business logic.
"""
try:
manager = get_update_manager()
progress = await manager.get_progress()
result = await container.update_service.get_progress()
return {
"version": progress.current_version,
"last_check": progress.last_check
}
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {
"version": result.data["current_version"],
"last_check": result.data["last_check"]
}

View File

@@ -1,15 +1,13 @@
"""WiFi management API endpoints."""
"""WiFi management API endpoints.
Refactored to use WiFiService for all business logic.
Endpoints are now thin adapters that convert HTTP requests/responses.
"""
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from ..managers.wifi_manager import (
wifi_manager,
WiFiMode,
WiFiStatus,
WiFiNetwork,
WiFiInterface,
)
from ..services.container import container
router = APIRouter()
@@ -37,7 +35,7 @@ class WiFiNetworkResponse(BaseModel):
class SetModeRequest(BaseModel):
"""Request to set WiFi mode."""
mode: WiFiMode
mode: str # "ap", "client", "dual", "auto", "off"
class ConnectRequest(BaseModel):
@@ -48,213 +46,217 @@ class ConnectRequest(BaseModel):
hidden: bool = False
def _service_error_to_http_status(error_code: str) -> int:
"""Map service error codes to HTTP status codes.
Args:
error_code: Service error code
Returns:
HTTP status code
"""
codes = {
"wifi_status_error": 500,
"wifi_scan_error": 500,
"connection_failed": 503,
"wifi_connect_error": 500,
"disconnect_failed": 500,
"wifi_disconnect_error": 500,
"invalid_mode": 400,
"mode_not_supported": 400,
"mode_change_failed": 500,
"wifi_mode_error": 500,
"saved_networks_error": 500,
"network_not_found": 404,
"forget_network_error": 500,
}
return codes.get(error_code, 500)
@router.get("/status", response_model=WiFiStatusResponse)
async def get_wifi_status():
"""Get current WiFi status and available interfaces.
Returns WiFi mode, interface information, and connection status.
Uses WiFiService for business logic.
"""
try:
status: WiFiStatus = await wifi_manager.get_status()
result = await container.wifi_service.get_status()
return WiFiStatusResponse(
mode=status.mode.value,
interfaces=[
{
"name": iface.name,
"mac": iface.mac,
"is_usb": iface.is_usb,
"is_up": iface.is_up,
"connected": iface.connected,
"ssid": iface.ssid,
"ip_address": iface.ip_address,
}
for iface in status.interfaces
],
current_ssid=status.current_ssid,
current_ip=status.current_ip,
ap_ssid=status.ap_ssid,
ap_ip=status.ap_ip,
supports_dual=status.supports_dual,
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to get WiFi status: {e}")
data = result.data
return WiFiStatusResponse(
mode=data["mode"],
interfaces=data["interfaces"],
current_ssid=data["client"]["ssid"] if data.get("client") else None,
current_ip=data["client"]["ip"] if data.get("client") else None,
ap_ssid=data["access_point"]["ssid"],
ap_ip=data["access_point"]["ip"],
supports_dual=data["supports_dual"]
)
@router.get("/scan", response_model=List[WiFiNetworkResponse])
async def scan_networks(interface: Optional[str] = None):
"""Scan for available WiFi networks.
Uses WiFiService for business logic.
Args:
interface: Optional interface to scan with
Returns:
List of available networks
"""
try:
networks = await wifi_manager.scan_networks(interface)
result = await container.wifi_service.scan_networks(interface)
return [
WiFiNetworkResponse(
ssid=net.ssid,
bssid=net.bssid,
signal_strength=net.signal_strength,
frequency=net.frequency,
encrypted=net.encrypted,
in_use=net.in_use,
)
for net in networks
]
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to scan networks: {e}")
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return [
WiFiNetworkResponse(**net)
for net in result.data["networks"]
]
@router.post("/mode")
async def set_wifi_mode(request: SetModeRequest):
"""Set WiFi operation mode.
Uses WiFiService for business logic.
Args:
request: Mode to set (ap, client, dual, auto, off)
Returns:
Success status
"""
try:
success = await wifi_manager.set_mode(request.mode)
result = await container.wifi_service.set_mode(request.mode)
if not success:
raise HTTPException(status_code=500, detail="Failed to set WiFi mode")
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return {
"success": True,
"message": f"WiFi mode set to {request.mode.value}",
"mode": request.mode.value,
}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to set WiFi mode: {e}")
return {
"success": True,
"message": result.data["message"],
"mode": result.data["mode"]
}
@router.post("/connect")
async def connect_to_network(request: ConnectRequest):
"""Connect to a WiFi network.
Uses WiFiService for business logic.
Args:
request: Connection details (SSID, password, interface, hidden)
Returns:
Success status
"""
try:
success = await wifi_manager.connect_to_network(
ssid=request.ssid,
password=request.password,
interface=request.interface,
hidden=request.hidden,
result = await container.wifi_service.connect(
ssid=request.ssid,
password=request.password,
interface=request.interface,
hidden=request.hidden
)
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
if not success:
raise HTTPException(status_code=500, detail="Failed to connect to network")
return {
"success": True,
"message": f"Connected to {request.ssid}",
"ssid": request.ssid,
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to connect to network: {e}")
return {
"success": True,
"message": result.data["message"],
"ssid": result.data["ssid"],
"ip": result.data.get("ip")
}
@router.get("/interfaces")
async def get_interfaces():
"""Get available WiFi interfaces.
Returns:
List of WiFi interfaces with their status
Uses WiFiService for business logic.
"""
try:
interfaces = await wifi_manager.detect_interfaces()
result = await container.wifi_service.get_status()
return {
"interfaces": [
{
"name": iface.name,
"mac": iface.mac,
"is_usb": iface.is_usb,
"is_up": iface.is_up,
"connected": iface.connected,
"ssid": iface.ssid,
"ip_address": iface.ip_address,
}
for iface in interfaces
],
"supports_dual": len(interfaces) >= 2,
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to get interfaces: {e}")
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return {
"interfaces": result.data["interfaces"],
"supports_dual": result.data["supports_dual"]
}
@router.post("/disconnect")
async def disconnect_from_network(interface: Optional[str] = None):
"""Disconnect from current network.
Uses WiFiService for business logic.
Args:
interface: Interface to disconnect (optional)
Returns:
Success status
"""
try:
success = await wifi_manager.disconnect_from_network(interface)
result = await container.wifi_service.disconnect(interface)
if not success:
raise HTTPException(status_code=500, detail="Failed to disconnect")
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return {
"success": True,
"message": "Disconnected from network",
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to disconnect: {e}")
return {
"success": True,
"message": result.data["message"]
}
@router.get("/saved")
async def get_saved_networks():
"""Get list of saved networks.
Returns:
List of saved networks
Uses WiFiService for business logic.
"""
try:
networks = await wifi_manager.get_saved_networks()
return {"networks": networks}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to get saved networks: {e}")
result = await container.wifi_service.get_saved_networks()
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return {"networks": result.data["networks"]}
@router.delete("/saved/{ssid}")
async def forget_network(ssid: str):
"""Forget a saved network.
Uses WiFiService for business logic.
Args:
ssid: SSID of network to forget
Returns:
Success status
"""
try:
success = await wifi_manager.forget_network(ssid)
result = await container.wifi_service.forget_network(ssid)
if not success:
raise HTTPException(status_code=404, detail=f"Network {ssid} not found")
if not result.success:
raise HTTPException(
status_code=_service_error_to_http_status(result.error.code),
detail=result.error.message
)
return {
"success": True,
"message": f"Forgot network {ssid}",
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to forget network: {e}")
return {
"success": True,
"message": result.data["message"]
}
@router.post("/static-ip")
@@ -267,18 +269,18 @@ async def set_static_ip(
):
"""Set static IP for interface.
NOTE: This is a direct manager operation (not yet in WiFiService).
TODO: Move to WiFiService in future iteration.
Args:
interface: Interface name
ip_address: Static IP address
netmask: Network mask (default: 255.255.255.0)
gateway: Gateway IP (optional)
dns: DNS servers (optional)
Returns:
Success status
"""
try:
success = await wifi_manager.set_static_ip(
success = await container.wifi_manager.set_static_ip(
interface, ip_address, netmask, gateway, dns
)
@@ -297,14 +299,14 @@ async def set_static_ip(
async def enable_dhcp(interface: str):
"""Enable DHCP for interface.
NOTE: This is a direct manager operation (not yet in WiFiService).
TODO: Move to WiFiService in future iteration.
Args:
interface: Interface name
Returns:
Success status
"""
try:
success = await wifi_manager.enable_dhcp(interface)
success = await container.wifi_manager.enable_dhcp(interface)
if not success:
raise HTTPException(status_code=500, detail="Failed to enable DHCP")

View File

@@ -0,0 +1,48 @@
"""BLE GATT server implementation for Dangerous Pi.
This module provides Bluetooth Low Energy (BLE) GATT server functionality
that reuses the service layer for business logic, ensuring consistency
with the REST API.
Components:
- DangerousPiGATTServer: GATT handlers that call service layer
- BlueZGATTAdapter: Bridges bless library to GATT handlers
- Characteristic UUIDs: Service and characteristic definitions
"""
from .gatt_server import DangerousPiGATTServer
from .characteristics import (
PM3CharacteristicUUIDs,
WiFiCharacteristicUUIDs,
SystemCharacteristicUUIDs,
UpdateCharacteristicUUIDs,
)
# BlueZ adapter (requires bless library)
try:
from .bluez_adapter import (
BlueZGATTAdapter,
get_ble_adapter,
start_ble_server,
stop_ble_server,
)
BLESS_AVAILABLE = True
except ImportError:
BlueZGATTAdapter = None
get_ble_adapter = None
start_ble_server = None
stop_ble_server = None
BLESS_AVAILABLE = False
__all__ = [
"DangerousPiGATTServer",
"PM3CharacteristicUUIDs",
"WiFiCharacteristicUUIDs",
"SystemCharacteristicUUIDs",
"UpdateCharacteristicUUIDs",
"BlueZGATTAdapter",
"get_ble_adapter",
"start_ble_server",
"stop_ble_server",
"BLESS_AVAILABLE",
]

View File

@@ -0,0 +1,457 @@
"""BlueZ GATT adapter using the bless library.
This module bridges our GATT server handlers to BlueZ via bless,
enabling BLE peripheral functionality on Linux.
Architecture:
bless BLEServer (handles BlueZ D-Bus)
|
BlueZGATTAdapter (this file - bridges handlers)
|
DangerousPiGATTServer (handlers call service layer)
|
Service Layer (business logic)
"""
import asyncio
import logging
import sys
import threading
from typing import Dict, Optional, Any, Union
from bless import (
BlessServer,
BlessGATTCharacteristic,
GATTCharacteristicProperties,
GATTAttributePermissions,
)
from .gatt_server import DangerousPiGATTServer
from .characteristics import (
PM3CharacteristicUUIDs,
WiFiCharacteristicUUIDs,
SystemCharacteristicUUIDs,
UpdateCharacteristicUUIDs,
)
logger = logging.getLogger(__name__)
# Device name for BLE advertising
DEFAULT_DEVICE_NAME = "Dangerous-Pi"
class BlueZGATTAdapter:
"""Adapter connecting bless BLE server to our GATT handlers.
This class:
- Initializes the bless BLE server
- Registers all services and characteristics via GATT dictionary
- Routes read/write requests to DangerousPiGATTServer handlers
- Sends notifications via bless
"""
def __init__(self, device_name: str = DEFAULT_DEVICE_NAME):
"""Initialize the BlueZ GATT adapter.
Args:
device_name: BLE device name for advertising
"""
self.device_name = device_name
self.server: Optional[BlessServer] = None
self.gatt_server = DangerousPiGATTServer()
self._is_running = False
self._loop: Optional[asyncio.AbstractEventLoop] = None
# Platform-specific trigger for async coordination
self._trigger: Union[asyncio.Event, threading.Event]
if sys.platform in ["darwin", "win32"]:
self._trigger = threading.Event()
else:
self._trigger = asyncio.Event()
@property
def is_running(self) -> bool:
"""Check if BLE server is running."""
return self._is_running
def _build_gatt_dict(self) -> Dict:
"""Build the GATT dictionary for bless.
Returns:
Dictionary mapping service UUIDs to characteristic definitions
"""
return {
# PM3 Service
PM3CharacteristicUUIDs.SERVICE: {
PM3CharacteristicUUIDs.COMMAND_WRITE: {
"Properties": GATTCharacteristicProperties.write,
"Permissions": GATTAttributePermissions.writeable,
"Value": None,
},
PM3CharacteristicUUIDs.COMMAND_RESULT: {
"Properties": (
GATTCharacteristicProperties.read |
GATTCharacteristicProperties.notify
),
"Permissions": GATTAttributePermissions.readable,
"Value": bytearray(b'{}'),
},
PM3CharacteristicUUIDs.STATUS: {
"Properties": GATTCharacteristicProperties.read,
"Permissions": GATTAttributePermissions.readable,
"Value": bytearray(b'{"connected": false}'),
},
PM3CharacteristicUUIDs.SESSION_CREATE: {
"Properties": GATTCharacteristicProperties.write,
"Permissions": GATTAttributePermissions.writeable,
"Value": None,
},
PM3CharacteristicUUIDs.SESSION_RELEASE: {
"Properties": GATTCharacteristicProperties.write,
"Permissions": GATTAttributePermissions.writeable,
"Value": None,
},
},
# WiFi Service
WiFiCharacteristicUUIDs.SERVICE: {
WiFiCharacteristicUUIDs.STATUS: {
"Properties": GATTCharacteristicProperties.read,
"Permissions": GATTAttributePermissions.readable,
"Value": bytearray(b'{"mode": "unknown"}'),
},
WiFiCharacteristicUUIDs.SCAN: {
"Properties": (
GATTCharacteristicProperties.write |
GATTCharacteristicProperties.notify
),
"Permissions": (
GATTAttributePermissions.readable |
GATTAttributePermissions.writeable
),
"Value": None,
},
WiFiCharacteristicUUIDs.CONNECT: {
"Properties": GATTCharacteristicProperties.write,
"Permissions": GATTAttributePermissions.writeable,
"Value": None,
},
WiFiCharacteristicUUIDs.MODE: {
"Properties": (
GATTCharacteristicProperties.read |
GATTCharacteristicProperties.write
),
"Permissions": (
GATTAttributePermissions.readable |
GATTAttributePermissions.writeable
),
"Value": bytearray(b'client'),
},
},
# System Service
SystemCharacteristicUUIDs.SERVICE: {
SystemCharacteristicUUIDs.INFO: {
"Properties": (
GATTCharacteristicProperties.read |
GATTCharacteristicProperties.notify
),
"Permissions": GATTAttributePermissions.readable,
"Value": bytearray(b'{}'),
},
SystemCharacteristicUUIDs.SHUTDOWN: {
"Properties": GATTCharacteristicProperties.write,
"Permissions": GATTAttributePermissions.writeable,
"Value": None,
},
SystemCharacteristicUUIDs.RESTART: {
"Properties": GATTCharacteristicProperties.write,
"Permissions": GATTAttributePermissions.writeable,
"Value": None,
},
},
# Update Service
UpdateCharacteristicUUIDs.SERVICE: {
UpdateCharacteristicUUIDs.CHECK: {
"Properties": (
GATTCharacteristicProperties.write |
GATTCharacteristicProperties.notify
),
"Permissions": (
GATTAttributePermissions.readable |
GATTAttributePermissions.writeable
),
"Value": None,
},
UpdateCharacteristicUUIDs.PROGRESS: {
"Properties": (
GATTCharacteristicProperties.read |
GATTCharacteristicProperties.notify
),
"Permissions": GATTAttributePermissions.readable,
"Value": bytearray(b'{"progress": 0}'),
},
},
}
def _on_read(self, characteristic: BlessGATTCharacteristic) -> bytearray:
"""Handle BLE read request.
Note: This callback is called synchronously from the D-Bus event handler.
We cannot block on async operations here as it would deadlock the event loop.
Instead, we return cached values and schedule async updates in the background.
Args:
characteristic: The characteristic being read
Returns:
Characteristic value as bytearray
"""
uuid = str(characteristic.uuid).lower()
logger.info("BLE Read request for characteristic %s", uuid)
# Return the current cached value (synchronously)
# Async handlers update these values in the background
if characteristic.value:
logger.info("Read returning cached: %s", characteristic.value[:50] if len(characteristic.value) > 50 else characteristic.value)
return characteristic.value
# Return default JSON if no cached value
default_value = bytearray(b'{"status": "initializing"}')
logger.info("Read returning default: %s", default_value)
return default_value
def _on_write(self, characteristic: BlessGATTCharacteristic, value: Any):
"""Handle BLE write request.
Args:
characteristic: The characteristic being written
value: Value being written
"""
uuid = str(characteristic.uuid).lower() # Use lowercase to match our UUID format
logger.info("BLE Write request for characteristic %s: %s", uuid, value)
# Update the characteristic value
characteristic.value = value
handler = self.gatt_server.get_characteristic_handler(uuid)
if handler and handler.write_handler:
try:
# Convert value to bytes if needed
if isinstance(value, bytearray):
data = bytes(value)
elif isinstance(value, bytes):
data = value
else:
data = bytes(value)
# Run async handler in event loop
if self._loop and self._loop.is_running():
asyncio.run_coroutine_threadsafe(
handler.write_handler(data),
self._loop
)
except Exception as e:
logger.error("Error handling write for %s: %s", uuid, e)
def _on_subscribe(self, characteristic: BlessGATTCharacteristic, **kwargs):
"""Handle subscription to characteristic notifications."""
logger.info("Client subscribed to %s", characteristic.uuid)
def _on_unsubscribe(self, characteristic: BlessGATTCharacteristic, **kwargs):
"""Handle unsubscription from characteristic notifications."""
logger.info("Client unsubscribed from %s", characteristic.uuid)
async def start(self) -> bool:
"""Start the BLE GATT server.
Returns:
True if started successfully, False otherwise
"""
if self._is_running:
logger.warning("BLE server already running")
return True
try:
self._loop = asyncio.get_running_loop()
# Create bless server
self.server = BlessServer(name=self.device_name, loop=self._loop)
# Set up callbacks (bless 0.3.0+ API)
self.server.read_request_func = self._on_read
self.server.write_request_func = self._on_write
# Build and add GATT structure
gatt = self._build_gatt_dict()
await self.server.add_gatt(gatt)
# Start the server (begins advertising)
await self.server.start()
# Start GATT server handlers
await self.gatt_server.start()
# Register notification callbacks
self._setup_notification_callbacks()
self._is_running = True
logger.info("BLE GATT server started, advertising as '%s'", self.device_name)
return True
except Exception as e:
logger.error("Failed to start BLE server: %s", e)
import traceback
traceback.print_exc()
self._is_running = False
return False
def _setup_notification_callbacks(self):
"""Set up notification callbacks for characteristics that support notify."""
notify_chars = [
PM3CharacteristicUUIDs.COMMAND_RESULT,
WiFiCharacteristicUUIDs.SCAN,
SystemCharacteristicUUIDs.INFO,
UpdateCharacteristicUUIDs.CHECK,
UpdateCharacteristicUUIDs.PROGRESS,
]
for uuid in notify_chars:
self._register_notification_callback(uuid)
def _register_notification_callback(self, uuid: str):
"""Register notification callback for a characteristic.
Args:
uuid: Characteristic UUID
"""
async def send_notification(value: bytes):
if self.server and self._is_running:
try:
char = self.server.get_characteristic(uuid)
if char:
char.value = bytearray(value)
service_uuid = self._get_service_uuid_for_characteristic(uuid)
# update_value is not async in bless 0.3+
self.server.update_value(service_uuid, uuid)
logger.debug("Notification sent for %s", uuid)
except Exception as e:
logger.error("Failed to send notification for %s: %s", uuid, e)
self.gatt_server.register_notification_callback(uuid, send_notification)
def _get_service_uuid_for_characteristic(self, char_uuid: str) -> str:
"""Get the service UUID that contains a characteristic.
Args:
char_uuid: Characteristic UUID
Returns:
Service UUID
"""
# Check each service's characteristics
if char_uuid in [
PM3CharacteristicUUIDs.COMMAND_WRITE,
PM3CharacteristicUUIDs.COMMAND_RESULT,
PM3CharacteristicUUIDs.STATUS,
PM3CharacteristicUUIDs.SESSION_CREATE,
PM3CharacteristicUUIDs.SESSION_RELEASE,
]:
return PM3CharacteristicUUIDs.SERVICE
elif char_uuid in [
WiFiCharacteristicUUIDs.STATUS,
WiFiCharacteristicUUIDs.SCAN,
WiFiCharacteristicUUIDs.CONNECT,
WiFiCharacteristicUUIDs.MODE,
]:
return WiFiCharacteristicUUIDs.SERVICE
elif char_uuid in [
SystemCharacteristicUUIDs.INFO,
SystemCharacteristicUUIDs.SHUTDOWN,
SystemCharacteristicUUIDs.RESTART,
]:
return SystemCharacteristicUUIDs.SERVICE
elif char_uuid in [
UpdateCharacteristicUUIDs.CHECK,
UpdateCharacteristicUUIDs.PROGRESS,
]:
return UpdateCharacteristicUUIDs.SERVICE
else:
return PM3CharacteristicUUIDs.SERVICE # Default
async def stop(self):
"""Stop the BLE GATT server."""
if not self._is_running:
return
try:
await self.gatt_server.stop()
if self.server:
await self.server.stop()
self.server = None
self._is_running = False
logger.info("BLE server stopped")
except Exception as e:
logger.error("Error stopping BLE server: %s", e)
async def send_notification(self, uuid: str, value: bytes) -> bool:
"""Send a notification for a characteristic.
Args:
uuid: Characteristic UUID
value: Notification value
Returns:
True if sent successfully
"""
if not self.server or not self._is_running:
return False
try:
char = self.server.get_characteristic(uuid)
if char:
char.value = bytearray(value)
service_uuid = self._get_service_uuid_for_characteristic(uuid)
# update_value is not async in bless 0.3+
self.server.update_value(service_uuid, uuid)
return True
except Exception as e:
logger.error("Error sending notification for %s: %s", uuid, e)
return False
# Singleton instance for application use
_adapter_instance: Optional[BlueZGATTAdapter] = None
def get_ble_adapter() -> BlueZGATTAdapter:
"""Get or create the singleton BLE adapter instance.
Returns:
BlueZGATTAdapter instance
"""
global _adapter_instance
if _adapter_instance is None:
_adapter_instance = BlueZGATTAdapter()
return _adapter_instance
async def start_ble_server(device_name: str = DEFAULT_DEVICE_NAME) -> bool:
"""Start the BLE GATT server.
Args:
device_name: BLE device name for advertising
Returns:
True if started successfully
"""
adapter = get_ble_adapter()
adapter.device_name = device_name
return await adapter.start()
async def stop_ble_server():
"""Stop the BLE GATT server."""
adapter = get_ble_adapter()
await adapter.stop()

View File

@@ -0,0 +1,112 @@
"""GATT Characteristic UUIDs for Dangerous Pi BLE interface.
This module defines the UUIDs for all GATT services and characteristics
used by the Dangerous Pi BLE interface.
UUID Namespace: Dangerous Pi uses custom 128-bit UUIDs.
Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12 hex chars)
Services are differentiated by the 5th group:
- PM3: 0000xxxx (0000-000f)
- WiFi: 0001xxxx (0010-001f)
- System: 0002xxxx (0020-002f)
- Update: 0003xxxx (0030-003f)
"""
from dataclasses import dataclass
def _uuid(suffix: str) -> str:
"""Generate a Dangerous Pi UUID with the given 4-char suffix.
Args:
suffix: 4-character hex suffix (e.g., "0001", "0010")
Returns:
Full 128-bit UUID string
"""
return f"d4c3b2a1-0000-1000-8000-00805f9b{suffix}"
@dataclass
class PM3CharacteristicUUIDs:
"""PM3 GATT Service and Characteristics.
Service for Proxmark3 operations (command execution, status).
"""
# Service UUID
SERVICE = _uuid("0000")
# Characteristics
COMMAND_WRITE = _uuid("0001") # Write: Execute PM3 command
COMMAND_RESULT = _uuid("0002") # Notify: Command result
STATUS = _uuid("0003") # Read: Get PM3 status
SESSION_CREATE = _uuid("0004") # Write: Create session
SESSION_RELEASE = _uuid("0005") # Write: Release session
SESSION_INFO = _uuid("0006") # Read: Get session info
@dataclass
class WiFiCharacteristicUUIDs:
"""WiFi GATT Service and Characteristics.
Service for WiFi network management (scan, connect, status).
"""
# Service UUID
SERVICE = _uuid("0010")
# Characteristics
STATUS = _uuid("0011") # Read: Get WiFi status
SCAN = _uuid("0012") # Write: Trigger scan, Notify: Results
CONNECT = _uuid("0013") # Write: Connect to network
DISCONNECT = _uuid("0014") # Write: Disconnect
MODE = _uuid("0015") # Read/Write: WiFi mode
SAVED_NETWORKS = _uuid("0016") # Read: Get saved networks
FORGET_NETWORK = _uuid("0017") # Write: Forget network
@dataclass
class SystemCharacteristicUUIDs:
"""System GATT Service and Characteristics.
Service for system operations (info, shutdown, restart).
"""
# Service UUID
SERVICE = _uuid("0020")
# Characteristics
INFO = _uuid("0021") # Read: Get system info
SHUTDOWN = _uuid("0022") # Write: Initiate shutdown
RESTART = _uuid("0023") # Write: Initiate restart
LOGS = _uuid("0024") # Read: Get service logs
@dataclass
class UpdateCharacteristicUUIDs:
"""Update GATT Service and Characteristics.
Service for software update management.
"""
# Service UUID
SERVICE = _uuid("0030")
# Characteristics
CHECK = _uuid("0031") # Write: Check for updates, Notify: Result
DOWNLOAD = _uuid("0032") # Write: Download update
INSTALL = _uuid("0033") # Write: Install update
PROGRESS = _uuid("0034") # Read/Notify: Update progress
RELEASE_NOTES = _uuid("0035") # Read: Get release notes
# Characteristic properties
class CharacteristicProperties:
"""Standard GATT characteristic properties."""
READ = "read"
WRITE = "write"
WRITE_WITHOUT_RESPONSE = "write-without-response"
NOTIFY = "notify"
INDICATE = "indicate"
# Characteristic descriptors
CHARACTERISTIC_USER_DESCRIPTION_UUID = "00002901-0000-1000-8000-00805f9b34fb"
CLIENT_CHARACTERISTIC_CONFIG_UUID = "00002902-0000-1000-8000-00805f9b34fb"

View File

@@ -0,0 +1,719 @@
"""GATT Server implementation for Dangerous Pi.
This GATT server provides BLE access to all Dangerous Pi functionality by
reusing the service layer. This ensures identical behavior between REST API
and BLE interface - NO CODE DUPLICATION!
Architecture:
BLE GATT Characteristic Handler
Service Layer (PM3Service, WiFiService, etc.)
Managers/Workers (PM3Worker, WiFiManager, etc.)
The handlers are thin adapters, just like REST endpoints.
"""
import asyncio
import json
import logging
from typing import Dict, Any, Optional, Callable
from dataclasses import dataclass
from ..services.container import container
from .characteristics import (
PM3CharacteristicUUIDs,
WiFiCharacteristicUUIDs,
SystemCharacteristicUUIDs,
UpdateCharacteristicUUIDs,
)
logger = logging.getLogger(__name__)
@dataclass
class CharacteristicHandler:
"""Configuration for a GATT characteristic handler."""
uuid: str
properties: list # ["read", "write", "notify"]
read_handler: Optional[Callable] = None
write_handler: Optional[Callable] = None
description: str = ""
class DangerousPiGATTServer:
"""GATT server for Dangerous Pi BLE interface.
This server exposes Dangerous Pi functionality over BLE by reusing
the service layer. All business logic comes from services, ensuring
consistency with the REST API.
Key Features:
- Uses ServiceContainer for all operations (same as REST!)
- Converts BLE data formats to/from service calls
- Sends notifications for async operations
- Zero business logic duplication
"""
def __init__(self):
"""Initialize GATT server."""
self.is_running = False
self._notification_callbacks: Dict[str, Callable] = {}
self._characteristic_handlers: Dict[str, CharacteristicHandler] = {}
# Register all characteristic handlers
self._register_pm3_characteristics()
self._register_wifi_characteristics()
self._register_system_characteristics()
self._register_update_characteristics()
logger.info("GATT server initialized with %d characteristics",
len(self._characteristic_handlers))
# ========================================================================
# PM3 Characteristic Handlers
# ========================================================================
def _register_pm3_characteristics(self):
"""Register PM3 GATT characteristics.
All handlers delegate to PM3Service - NO business logic here!
"""
self._characteristic_handlers.update({
PM3CharacteristicUUIDs.COMMAND_WRITE: CharacteristicHandler(
uuid=PM3CharacteristicUUIDs.COMMAND_WRITE,
properties=["write"],
write_handler=self._handle_pm3_command_write,
description="Execute PM3 command"
),
PM3CharacteristicUUIDs.STATUS: CharacteristicHandler(
uuid=PM3CharacteristicUUIDs.STATUS,
properties=["read"],
read_handler=self._handle_pm3_status_read,
description="Get PM3 status"
),
PM3CharacteristicUUIDs.SESSION_CREATE: CharacteristicHandler(
uuid=PM3CharacteristicUUIDs.SESSION_CREATE,
properties=["write"],
write_handler=self._handle_session_create_write,
description="Create PM3 session"
),
PM3CharacteristicUUIDs.SESSION_RELEASE: CharacteristicHandler(
uuid=PM3CharacteristicUUIDs.SESSION_RELEASE,
properties=["write"],
write_handler=self._handle_session_release_write,
description="Release PM3 session"
),
})
async def _handle_pm3_command_write(self, value: bytes) -> Dict[str, Any]:
"""Handle PM3 command execution via BLE.
This is a THIN ADAPTER - delegates to PM3Service!
Args:
value: JSON bytes: {"command": "hw version", "session_id": "..."}
Returns:
Response dict to send via notification
"""
try:
# Parse BLE request
data = json.loads(value.decode('utf-8'))
command = data.get("command")
session_id = data.get("session_id")
if not command:
return {
"success": False,
"error": {"code": "invalid_request", "message": "Command required"}
}
# ✅ REUSE PM3Service - same logic as REST API!
result = await container.pm3_service.execute_command(
command=command,
session_id=session_id
)
# Convert service result to BLE response
if result.success:
response = {
"success": True,
"output": result.data["output"],
"command": result.data["command"]
}
else:
response = {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
# Send notification with result
await self._notify_characteristic(
PM3CharacteristicUUIDs.COMMAND_RESULT,
json.dumps(response).encode('utf-8')
)
return response
except json.JSONDecodeError:
return {
"success": False,
"error": {"code": "invalid_json", "message": "Invalid JSON"}
}
except Exception as e:
logger.error("Error handling PM3 command: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
async def _handle_pm3_status_read(self) -> bytes:
"""Handle PM3 status read via BLE.
This is a THIN ADAPTER - delegates to PM3Service!
Returns:
JSON bytes with PM3 status
"""
try:
# ✅ REUSE PM3Service - same logic as REST API!
result = await container.pm3_service.get_status()
if result.success:
# Handle both single-device and multi-device responses
if "devices" in result.data:
# Multi-device mode: summarize status
devices = result.data["devices"]
connected_count = sum(1 for d in devices if d.get("connected"))
response = {
"success": True,
"device_count": len(devices),
"connected_count": connected_count,
"devices": devices
}
else:
# Legacy single-device mode
response = {
"success": True,
"connected": result.data.get("connected", False),
"device_path": result.data.get("device_path"),
"version": result.data.get("version"),
"session_active": result.data.get("session_active", False)
}
else:
response = {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
return json.dumps(response).encode('utf-8')
except Exception as e:
logger.error("Error getting PM3 status: %s", e)
return json.dumps({
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}).encode('utf-8')
async def _handle_session_create_write(self, value: bytes) -> Dict[str, Any]:
"""Handle session creation via BLE.
Args:
value: JSON bytes: {"force_takeover": false}
"""
try:
data = json.loads(value.decode('utf-8'))
force_takeover = data.get("force_takeover", False)
# ✅ REUSE PM3Service
result = container.pm3_service.create_session(
force_takeover=force_takeover
)
if result.success:
return {
"success": True,
"session_id": result.data["session_id"]
}
else:
return {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
except Exception as e:
logger.error("Error creating session: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
async def _handle_session_release_write(self, value: bytes) -> Dict[str, Any]:
"""Handle session release via BLE.
Args:
value: JSON bytes: {"session_id": "..."}
"""
try:
data = json.loads(value.decode('utf-8'))
session_id = data.get("session_id")
if not session_id:
return {
"success": False,
"error": {"code": "invalid_request", "message": "Session ID required"}
}
# ✅ REUSE PM3Service
result = container.pm3_service.release_session(session_id)
if result.success:
return {"success": True, "message": result.data["message"]}
else:
return {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
except Exception as e:
logger.error("Error releasing session: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
# ========================================================================
# WiFi Characteristic Handlers
# ========================================================================
def _register_wifi_characteristics(self):
"""Register WiFi GATT characteristics."""
self._characteristic_handlers.update({
WiFiCharacteristicUUIDs.STATUS: CharacteristicHandler(
uuid=WiFiCharacteristicUUIDs.STATUS,
properties=["read"],
read_handler=self._handle_wifi_status_read,
description="Get WiFi status"
),
WiFiCharacteristicUUIDs.SCAN: CharacteristicHandler(
uuid=WiFiCharacteristicUUIDs.SCAN,
properties=["write", "notify"],
write_handler=self._handle_wifi_scan_write,
description="Scan for WiFi networks"
),
WiFiCharacteristicUUIDs.CONNECT: CharacteristicHandler(
uuid=WiFiCharacteristicUUIDs.CONNECT,
properties=["write"],
write_handler=self._handle_wifi_connect_write,
description="Connect to WiFi network"
),
WiFiCharacteristicUUIDs.MODE: CharacteristicHandler(
uuid=WiFiCharacteristicUUIDs.MODE,
properties=["read", "write"],
read_handler=self._handle_wifi_mode_read,
write_handler=self._handle_wifi_mode_write,
description="WiFi mode"
),
})
async def _handle_wifi_status_read(self) -> bytes:
"""Handle WiFi status read via BLE."""
try:
# ✅ REUSE WiFiService
result = await container.wifi_service.get_status()
if result.success:
return json.dumps(result.data).encode('utf-8')
else:
return json.dumps({
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}).encode('utf-8')
except Exception as e:
logger.error("Error getting WiFi status: %s", e)
return json.dumps({
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}).encode('utf-8')
async def _handle_wifi_scan_write(self, value: bytes) -> Dict[str, Any]:
"""Handle WiFi scan request via BLE."""
try:
data = json.loads(value.decode('utf-8')) if value else {}
interface = data.get("interface")
# ✅ REUSE WiFiService
result = await container.wifi_service.scan_networks(interface)
if result.success:
# Send scan results via notification
await self._notify_characteristic(
WiFiCharacteristicUUIDs.SCAN,
json.dumps(result.data).encode('utf-8')
)
return {"success": True, "count": result.data["count"]}
else:
return {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
except Exception as e:
logger.error("Error scanning WiFi: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
async def _handle_wifi_connect_write(self, value: bytes) -> Dict[str, Any]:
"""Handle WiFi connect request via BLE."""
try:
data = json.loads(value.decode('utf-8'))
ssid = data.get("ssid")
password = data.get("password")
hidden = data.get("hidden", False)
if not ssid:
return {
"success": False,
"error": {"code": "invalid_request", "message": "SSID required"}
}
# ✅ REUSE WiFiService
result = await container.wifi_service.connect(
ssid=ssid,
password=password,
hidden=hidden
)
if result.success:
return {
"success": True,
"ssid": result.data["ssid"],
"ip": result.data.get("ip")
}
else:
return {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
except Exception as e:
logger.error("Error connecting to WiFi: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
async def _handle_wifi_mode_read(self) -> bytes:
"""Handle WiFi mode read via BLE."""
try:
result = await container.wifi_service.get_status()
if result.success:
return json.dumps({"mode": result.data["mode"]}).encode('utf-8')
else:
return json.dumps({
"success": False,
"error": {"code": result.error.code, "message": result.error.message}
}).encode('utf-8')
except Exception as e:
return json.dumps({
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}).encode('utf-8')
async def _handle_wifi_mode_write(self, value: bytes) -> Dict[str, Any]:
"""Handle WiFi mode change via BLE."""
try:
data = json.loads(value.decode('utf-8'))
mode = data.get("mode")
if not mode:
return {
"success": False,
"error": {"code": "invalid_request", "message": "Mode required"}
}
# ✅ REUSE WiFiService
result = await container.wifi_service.set_mode(mode)
if result.success:
return {"success": True, "mode": result.data["mode"]}
else:
return {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
except Exception as e:
logger.error("Error setting WiFi mode: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
# ========================================================================
# System Characteristic Handlers
# ========================================================================
def _register_system_characteristics(self):
"""Register System GATT characteristics."""
self._characteristic_handlers.update({
SystemCharacteristicUUIDs.INFO: CharacteristicHandler(
uuid=SystemCharacteristicUUIDs.INFO,
properties=["read"],
read_handler=self._handle_system_info_read,
description="Get system information"
),
SystemCharacteristicUUIDs.SHUTDOWN: CharacteristicHandler(
uuid=SystemCharacteristicUUIDs.SHUTDOWN,
properties=["write"],
write_handler=self._handle_system_shutdown_write,
description="Initiate system shutdown"
),
SystemCharacteristicUUIDs.RESTART: CharacteristicHandler(
uuid=SystemCharacteristicUUIDs.RESTART,
properties=["write"],
write_handler=self._handle_system_restart_write,
description="Initiate system restart"
),
})
async def _handle_system_info_read(self) -> bytes:
"""Handle system info read via BLE."""
try:
# ✅ REUSE SystemService
result = await container.system_service.get_info()
if result.success:
return json.dumps(result.data).encode('utf-8')
else:
return json.dumps({
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}).encode('utf-8')
except Exception as e:
logger.error("Error getting system info: %s", e)
return json.dumps({
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}).encode('utf-8')
async def _handle_system_shutdown_write(self, value: bytes) -> Dict[str, Any]:
"""Handle system shutdown request via BLE."""
try:
data = json.loads(value.decode('utf-8')) if value else {}
delay = data.get("delay", 0)
# ✅ REUSE SystemService
result = await container.system_service.shutdown(delay=delay)
if result.success:
return {"success": True, "message": result.data["message"]}
else:
return {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
except Exception as e:
logger.error("Error initiating shutdown: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
async def _handle_system_restart_write(self, value: bytes) -> Dict[str, Any]:
"""Handle system restart request via BLE."""
try:
data = json.loads(value.decode('utf-8')) if value else {}
delay = data.get("delay", 0)
# ✅ REUSE SystemService
result = await container.system_service.restart(delay=delay)
if result.success:
return {"success": True, "message": result.data["message"]}
else:
return {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
except Exception as e:
logger.error("Error initiating restart: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
# ========================================================================
# Update Characteristic Handlers
# ========================================================================
def _register_update_characteristics(self):
"""Register Update GATT characteristics."""
self._characteristic_handlers.update({
UpdateCharacteristicUUIDs.CHECK: CharacteristicHandler(
uuid=UpdateCharacteristicUUIDs.CHECK,
properties=["write", "notify"],
write_handler=self._handle_update_check_write,
description="Check for updates"
),
UpdateCharacteristicUUIDs.PROGRESS: CharacteristicHandler(
uuid=UpdateCharacteristicUUIDs.PROGRESS,
properties=["read", "notify"],
read_handler=self._handle_update_progress_read,
description="Get update progress"
),
})
async def _handle_update_check_write(self, value: bytes) -> Dict[str, Any]:
"""Handle update check request via BLE."""
try:
# ✅ REUSE UpdateService
result = await container.update_service.check_for_updates()
if result.success:
# Send result via notification
await self._notify_characteristic(
UpdateCharacteristicUUIDs.CHECK,
json.dumps(result.data).encode('utf-8')
)
return result.data
else:
return {
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}
except Exception as e:
logger.error("Error checking for updates: %s", e)
return {
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}
async def _handle_update_progress_read(self) -> bytes:
"""Handle update progress read via BLE."""
try:
# ✅ REUSE UpdateService
result = await container.update_service.get_progress()
if result.success:
return json.dumps(result.data).encode('utf-8')
else:
return json.dumps({
"success": False,
"error": {
"code": result.error.code,
"message": result.error.message
}
}).encode('utf-8')
except Exception as e:
logger.error("Error getting update progress: %s", e)
return json.dumps({
"success": False,
"error": {"code": "internal_error", "message": str(e)}
}).encode('utf-8')
# ========================================================================
# GATT Server Management
# ========================================================================
async def start(self):
"""Start the GATT server."""
logger.info("Starting Dangerous Pi GATT server")
self.is_running = True
logger.info("GATT server started with %d characteristics",
len(self._characteristic_handlers))
async def stop(self):
"""Stop the GATT server."""
logger.info("Stopping Dangerous Pi GATT server")
self.is_running = False
logger.info("GATT server stopped")
def get_characteristic_handler(self, uuid: str) -> Optional[CharacteristicHandler]:
"""Get handler for a characteristic UUID.
Args:
uuid: Characteristic UUID
Returns:
CharacteristicHandler or None if not found
"""
return self._characteristic_handlers.get(uuid)
async def _notify_characteristic(self, uuid: str, value: bytes):
"""Send notification for a characteristic.
Args:
uuid: Characteristic UUID
value: Notification value (bytes)
"""
if uuid in self._notification_callbacks:
try:
await self._notification_callbacks[uuid](value)
logger.debug("Sent notification for %s", uuid)
except Exception as e:
logger.error("Error sending notification for %s: %s", uuid, e)
else:
logger.debug("No notification callback registered for %s", uuid)
def register_notification_callback(self, uuid: str, callback: Callable):
"""Register callback for sending notifications.
Args:
uuid: Characteristic UUID
callback: Async callable that sends the notification
"""
self._notification_callbacks[uuid] = callback
logger.debug("Registered notification callback for %s", uuid)
def get_all_characteristics(self) -> Dict[str, CharacteristicHandler]:
"""Get all registered characteristic handlers.
Returns:
Dict mapping UUID to CharacteristicHandler
"""
return self._characteristic_handlers.copy()

View File

@@ -13,6 +13,10 @@ DATABASE_PATH = DATA_DIR / "dangerous_pi.db"
# Proxmark3 settings
PM3_DEVICE = os.getenv("PM3_DEVICE", "/dev/ttyACM0")
PM3_TIMEOUT = int(os.getenv("PM3_TIMEOUT", "30"))
PM3_CLIENT_PATH = os.getenv("PM3_CLIENT_PATH", "/home/dt/.pm3/proxmark3/client/proxmark3")
# Firmware settings
FIRMWARE_DIR = os.getenv("FIRMWARE_DIR", "/opt/dangerous-pi/firmware")
# Session settings
SESSION_TIMEOUT = int(os.getenv("SESSION_TIMEOUT", "300")) # 5 minutes
@@ -24,7 +28,7 @@ PORT = int(os.getenv("PORT", "8000"))
VERSION = os.getenv("VERSION", "0.1.0")
# Update settings
GITHUB_REPO = os.getenv("GITHUB_REPO", "yourusername/dangerous-pi") # TODO: Update this
GITHUB_REPO = os.getenv("GITHUB_REPO", "dangerous-tacos/dangerous-pi")
UPDATE_CHECK_INTERVAL = int(os.getenv("UPDATE_CHECK_INTERVAL", "3600")) # 1 hour
# Wi-Fi settings
@@ -32,13 +36,27 @@ WLAN_INTERFACE = os.getenv("WLAN_INTERFACE", "wlan0")
USB_WLAN_INTERFACE = os.getenv("USB_WLAN_INTERFACE", "wlan1")
# UPS settings
UPS_I2C_ADDRESS = os.getenv("UPS_I2C_ADDRESS", "0x36")
UPS_TYPE = os.getenv("UPS_TYPE", "auto") # Options: "auto", "pisugar", "i2c", "none"
UPS_CHECK_INTERVAL = int(os.getenv("UPS_CHECK_INTERVAL", "60")) # 1 minute
# I2C UPS settings (for generic fuel gauge HATs)
UPS_I2C_ADDRESS = os.getenv("UPS_I2C_ADDRESS", "0x36")
# PiSugar UPS settings
UPS_PISUGAR_HOST = os.getenv("UPS_PISUGAR_HOST", "127.0.0.1")
UPS_PISUGAR_PORT = int(os.getenv("UPS_PISUGAR_PORT", "8423"))
# BLE settings
BLE_ENABLED = os.getenv("BLE_ENABLED", "true").lower() == "true"
BLE_DEVICE_NAME = os.getenv("BLE_DEVICE_NAME", "DangerousPi")
# Security
AUTH_ENABLED = os.getenv("AUTH_ENABLED", "false").lower() == "true"
AUTH_USERNAME = os.getenv("AUTH_USERNAME", "admin")
AUTH_PASSWORD = os.getenv("AUTH_PASSWORD", "") # Must be set when AUTH_ENABLED=true
HTTPS_ENABLED = os.getenv("HTTPS_ENABLED", "false").lower() == "true"
# CPU cores settings
# Set to 0 or "auto" to use model-specific defaults
# Pi Zero 2 W defaults to 2 cores (out of 4) for thermal/power management
CPU_CORES = os.getenv("CPU_CORES", "auto")

View File

@@ -1,18 +1,25 @@
"""Main FastAPI application for Dangerous Pi."""
import asyncio
import os
from pathlib import Path
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.responses import JSONResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from . import config
from .models.database import init_db
from .api import health, pm3, system, wifi, updates, plugins
from .sse import events
from .api.auth import verify_credentials
from .websocket import router as ws_router
from .websocket import notifications as ws_notifications
from .managers.update_manager import get_update_manager
from .managers.ups_manager import get_ups_manager
from .managers.ble_manager import get_ble_manager, NotificationType
from .managers.plugin_manager import get_plugin_manager
from .managers.wifi_manager import wifi_manager
from .services.container import container
@asynccontextmanager
@@ -37,36 +44,54 @@ async def lifespan(app: FastAPI):
else:
print(f"⚠️ BLE not available")
# Apply saved WiFi mode (for boot persistence)
try:
await wifi_manager.apply_saved_mode()
print(f"✅ WiFi mode restored")
except Exception as e:
print(f"⚠️ WiFi mode restore failed: {e}")
# Start UPS monitoring
ups_manager = get_ups_manager()
# Register UPS event callbacks for SSE notifications and BLE
# Register UPS event callbacks for WebSocket notifications and BLE
async def ups_event_handler(event):
"""Handle UPS events and broadcast via SSE and BLE."""
"""Handle UPS events and broadcast via WebSocket and BLE."""
event_type = event.get("type")
data = event.get("data", {})
if event_type == "battery_warning":
await events.notify_ups_warning(data["percentage"], data["threshold"])
await ws_notifications.notify_ups_warning(data["percentage"], data["threshold"])
await ble_manager.send_notification(
NotificationType.BATTERY_WARNING,
f"Battery low: {data['percentage']:.1f}%",
data
)
elif event_type == "battery_low":
await events.notify_ups_critical(data["percentage"])
await ws_notifications.notify_ups_critical(data["percentage"])
await ble_manager.send_notification(
NotificationType.BATTERY_CRITICAL,
f"Battery critical: {data['percentage']:.1f}%",
data
)
elif event_type == "battery_critical":
await events.notify_ups_shutdown(data.get("delay", 60), data["percentage"])
await ws_notifications.notify_ups_shutdown(data.get("delay", 60), data["percentage"])
await ble_manager.send_notification(
NotificationType.SHUTDOWN_INITIATED,
f"Shutdown initiated: {data['percentage']:.1f}% battery",
data
)
elif event_type == "ups_config_required":
await ws_notifications.notify_ups_config_required(
data.get("model", "Unknown"),
data.get("message", "UPS configuration required"),
data.get("hint", "")
)
await ble_manager.send_notification(
NotificationType.CONFIG_REQUIRED,
data.get("message", "UPS configuration required"),
data
)
ups_manager.register_event_callback(ups_event_handler)
ups_task = asyncio.create_task(ups_manager.start_monitoring())
@@ -77,12 +102,62 @@ async def lifespan(app: FastAPI):
discovered = await plugin_manager.discover_plugins()
print(f"✅ Plugin manager started ({len(discovered)} plugins discovered)")
# Start PM3 device manager for multi-device support
pm3_device_manager = container.pm3_device_manager
# Register PM3 device change callback
async def pm3_device_change_handler(device_list):
"""Handle PM3 device list changes and broadcast via WebSocket."""
devices_data = [
{
"device_id": d.device_id,
"device_path": d.device_path,
"status": d.status.value if hasattr(d.status, 'value') else d.status,
"friendly_name": d.friendly_name,
}
for d in device_list
]
await ws_notifications.notify_pm3_devices(devices_data)
pm3_device_manager.register_device_change_callback(pm3_device_change_handler)
await pm3_device_manager.start()
print(f"✅ PM3 device manager started")
# Start periodic system stats broadcasting (every 5 seconds)
async def broadcast_system_stats():
"""Periodically broadcast system stats via WebSocket."""
while True:
try:
result = await container.system_service.get_info()
if result.success:
cpu_data = result.data["cpu"]
memory_data = result.data["memory"]
await ws_notifications.notify_system_stats(
cpu_percent=cpu_data.get("percent", 0),
cpu_per_core=cpu_data.get("per_core", []),
load_average=cpu_data.get("load_average", []),
memory_percent=memory_data.get("percent", 0),
temperature=cpu_data.get("temperature")
)
except Exception as e:
print(f"Error broadcasting system stats: {e}")
await asyncio.sleep(5) # Update every 5 seconds
system_stats_task = asyncio.create_task(broadcast_system_stats())
print(f"✅ System stats broadcaster started")
yield
# Shutdown
print(f"🛑 Shutting down Dangerous Pi backend...")
# Stop PM3 device manager
await pm3_device_manager.stop()
print(f"✅ PM3 device manager stopped")
update_task.cancel()
ups_task.cancel()
system_stats_task.cancel()
try:
await update_task
except asyncio.CancelledError:
@@ -91,6 +166,10 @@ async def lifespan(app: FastAPI):
await ups_task
except asyncio.CancelledError:
pass
try:
await system_stats_task
except asyncio.CancelledError:
pass
# Close UPS manager I2C connection
ups_manager.close()
@@ -106,20 +185,71 @@ app = FastAPI(
# CORS middleware for frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # TODO: Restrict in production
allow_origins=["*"], # Permissive for development; restrict via CORS_ORIGINS env var in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(health.router, prefix="/api", tags=["health"])
app.include_router(pm3.router, prefix="/api/pm3", tags=["proxmark3"])
app.include_router(system.router, prefix="/api/system", tags=["system"])
app.include_router(wifi.router, prefix="/api/wifi", tags=["wifi"])
app.include_router(updates.router, prefix="/api/updates", tags=["updates"])
app.include_router(plugins.router, prefix="/api/plugins", tags=["plugins"])
app.include_router(events.router, prefix="/sse", tags=["events"])
# Auth dependency for protected routes (applied when AUTH_ENABLED=true)
auth_dependency = [Depends(verify_credentials)] if config.AUTH_ENABLED else []
# Include routers - all protected when AUTH_ENABLED=true
app.include_router(health.router, prefix="/api", tags=["health"], dependencies=auth_dependency)
app.include_router(pm3.router, prefix="/api/pm3", tags=["proxmark3"], dependencies=auth_dependency)
app.include_router(system.router, prefix="/api/system", tags=["system"], dependencies=auth_dependency)
app.include_router(wifi.router, prefix="/api/wifi", tags=["wifi"], dependencies=auth_dependency)
app.include_router(updates.router, prefix="/api/updates", tags=["updates"], dependencies=auth_dependency)
app.include_router(plugins.router, prefix="/api/plugins", tags=["plugins"], dependencies=auth_dependency)
app.include_router(ws_router, prefix="/ws", tags=["websocket"])
# Serve frontend static files if build directory exists
# In production, frontend is built and served from /opt/dangerous-pi/app/frontend/build
# Priority: 1) check relative to working directory, 2) check absolute production path
frontend_build_paths = [
Path(__file__).parent.parent / "frontend" / "build" / "client", # Development
Path("/opt/dangerous-pi/app/frontend/build/client"), # Production
]
frontend_path = None
for path in frontend_build_paths:
if path.exists() and path.is_dir():
frontend_path = path
break
if frontend_path:
# Mount static assets (JS, CSS, images)
assets_path = frontend_path / "assets"
if assets_path.exists():
app.mount("/assets", StaticFiles(directory=str(assets_path)), name="assets")
# Cache control headers
NO_CACHE_HEADERS = {
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0"
}
# Serve index.html for all non-API routes (SPA support)
@app.get("/{full_path:path}")
async def serve_frontend(full_path: str):
"""Serve frontend files, fall back to index.html for SPA routing."""
# Check for exact file match first
file_path = frontend_path / full_path
if file_path.exists() and file_path.is_file():
# HTML files get no-cache headers
if str(file_path).endswith('.html'):
return FileResponse(str(file_path), headers=NO_CACHE_HEADERS)
return FileResponse(str(file_path))
# Fall back to index.html for SPA routing (no-cache for HTML)
index_path = frontend_path / "index.html"
if index_path.exists():
return FileResponse(str(index_path), headers=NO_CACHE_HEADERS)
return JSONResponse(status_code=404, content={"error": "Not found"})
print(f"📁 Serving frontend from: {frontend_path}")
else:
print(f"⚠️ Frontend build not found, API-only mode")
@app.exception_handler(Exception)

View File

@@ -1,15 +1,28 @@
"""BLE Manager for Dangerous Pi.
Handles Bluetooth Low Energy notifications for updates, backups,
and battery alerts using the Pi Zero 2 W built-in Bluetooth.
Handles Bluetooth Low Energy functionality including:
- GATT server with full PM3/WiFi/System/Update services
- Notifications for updates, backups, and battery alerts
- Uses the Pi Zero 2 W built-in Bluetooth via bless library
"""
import asyncio
import json
import logging
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Optional, Dict, Any, List
from .. import config
# Try to import bless for GATT server
try:
from ..ble.bluez_adapter import BlueZGATTAdapter, get_ble_adapter
BLESS_AVAILABLE = True
except ImportError:
BLESS_AVAILABLE = False
# Fallback to dbus for basic operations
try:
import dbus
import dbus.mainloop.glib
@@ -18,7 +31,7 @@ try:
except ImportError:
DBUS_AVAILABLE = False
from .. import config
logger = logging.getLogger(__name__)
class NotificationType(str, Enum):
@@ -30,6 +43,7 @@ class NotificationType(str, Enum):
BATTERY_CRITICAL = "battery_critical"
SHUTDOWN_INITIATED = "shutdown_initiated"
PM3_STATUS = "pm3_status"
CONFIG_REQUIRED = "config_required"
@dataclass
@@ -42,7 +56,12 @@ class BLENotification:
class BLEManager:
"""Manages BLE notifications via Pi Zero 2 W Bluetooth."""
"""Manages BLE functionality via Pi Zero 2 W Bluetooth.
Provides both:
- Full GATT server with PM3/WiFi/System/Update services (via bless)
- Simple notifications for system events
"""
def __init__(self):
"""Initialize the BLE manager."""
@@ -50,12 +69,14 @@ class BLEManager:
self._device_name = config.BLE_DEVICE_NAME
self._is_available = False
self._is_advertising = False
self._gatt_server_running = False
self._connected_devices: List[str] = []
self._notification_queue: asyncio.Queue = asyncio.Queue()
self._service_uuid = "12345678-1234-5678-1234-56789abcdef0" # Custom service UUID
self._char_uuid = "12345678-1234-5678-1234-56789abcdef1" # Notification characteristic
self._bus = None
self._adapter = None
self._gatt_adapter: Optional[BlueZGATTAdapter] = None
async def initialize(self) -> bool:
"""Initialize BLE adapter and check availability.
@@ -64,58 +85,81 @@ class BLEManager:
True if initialization successful, False otherwise
"""
if not self._enabled:
print("BLE is disabled in configuration")
logger.info("BLE is disabled in configuration")
return False
if not DBUS_AVAILABLE:
print("BLE not available: dbus/GLib libraries not installed")
# Check if Bluetooth adapter is available first
has_adapter = await self._check_bluetooth_adapter()
if not has_adapter:
logger.warning("No Bluetooth adapter found")
return False
try:
# Check if Bluetooth adapter is available
has_adapter = await self._check_bluetooth_adapter()
self._is_available = True
if has_adapter:
self._is_available = True
print(f"BLE initialized: {self._device_name}")
return True
else:
print("No Bluetooth adapter found")
return False
# Try to initialize GATT server with bless (preferred)
if BLESS_AVAILABLE:
try:
self._gatt_adapter = get_ble_adapter()
self._gatt_adapter.device_name = self._device_name
logger.info("BLE GATT adapter initialized (bless): %s", self._device_name)
except Exception as e:
logger.warning("Failed to initialize bless GATT adapter: %s", e)
self._gatt_adapter = None
else:
logger.info("bless library not available, using basic BLE mode")
except Exception as e:
print(f"Failed to initialize BLE: {e}")
return False
logger.info("BLE initialized: %s", self._device_name)
return True
async def start_advertising(self):
"""Start BLE advertising to allow device connections."""
"""Start BLE advertising and GATT server."""
if not self._is_available:
print("BLE not available, cannot start advertising")
logger.warning("BLE not available, cannot start advertising")
return
try:
# Set device name
await self._set_device_name(self._device_name)
# Start full GATT server if available (preferred)
if self._gatt_adapter:
success = await self._gatt_adapter.start()
if success:
self._gatt_server_running = True
self._is_advertising = True
logger.info("BLE GATT server started: %s", self._device_name)
return
else:
logger.warning("Failed to start GATT server, falling back to basic mode")
# Make device discoverable
# Fallback to basic advertising via bluetoothctl
await self._set_device_name(self._device_name)
await self._set_discoverable(True)
self._is_advertising = True
print(f"BLE advertising started: {self._device_name}")
logger.info("BLE advertising started (basic mode): %s", self._device_name)
except Exception as e:
print(f"Failed to start BLE advertising: {e}")
logger.error("Failed to start BLE advertising: %s", e)
self._is_advertising = False
async def stop_advertising(self):
"""Stop BLE advertising."""
if self._is_advertising:
try:
"""Stop BLE advertising and GATT server."""
if not self._is_advertising:
return
try:
# Stop GATT server if running
if self._gatt_adapter and self._gatt_server_running:
await self._gatt_adapter.stop()
self._gatt_server_running = False
logger.info("BLE GATT server stopped")
else:
# Stop basic advertising
await self._set_discoverable(False)
self._is_advertising = False
print("BLE advertising stopped")
except Exception as e:
print(f"Failed to stop BLE advertising: {e}")
self._is_advertising = False
logger.info("BLE advertising stopped")
except Exception as e:
logger.error("Failed to stop BLE advertising: %s", e)
async def send_notification(
self,
@@ -142,11 +186,11 @@ class BLEManager:
await self._notification_queue.put(notification)
# Process notification
if self._connected_devices:
# Process notification - always broadcast if GATT server is running
if self._connected_devices or self._gatt_server_running:
await self._broadcast_notification(notification)
else:
print(f"BLE notification queued (no devices connected): {message}")
logger.debug("BLE notification queued (no devices connected): %s", message)
async def get_status(self) -> Dict[str, Any]:
"""Get BLE manager status.
@@ -158,6 +202,8 @@ class BLEManager:
"enabled": self._enabled,
"available": self._is_available,
"advertising": self._is_advertising,
"gatt_server_running": self._gatt_server_running,
"gatt_available": BLESS_AVAILABLE,
"connected_devices": len(self._connected_devices),
"device_name": self._device_name,
"queued_notifications": self._notification_queue.qsize()
@@ -182,10 +228,10 @@ class BLEManager:
return b"Controller" in stdout
except FileNotFoundError:
print("bluetoothctl not found - BlueZ not installed")
logger.warning("bluetoothctl not found - BlueZ not installed")
return False
except Exception as e:
print(f"Error checking Bluetooth adapter: {e}")
logger.error("Error checking Bluetooth adapter: %s", e)
return False
async def _set_device_name(self, name: str):
@@ -202,7 +248,7 @@ class BLEManager:
)
await process.communicate()
except Exception as e:
print(f"Failed to set device name: {e}")
logger.error("Failed to set device name: %s", e)
async def _set_discoverable(self, enabled: bool):
"""Set Bluetooth discoverable state.
@@ -219,7 +265,7 @@ class BLEManager:
)
await process.communicate()
except Exception as e:
print(f"Failed to set discoverable: {e}")
logger.error("Failed to set discoverable: %s", e)
async def _broadcast_notification(self, notification: BLENotification):
"""Broadcast notification to all connected devices.
@@ -234,14 +280,24 @@ class BLEManager:
"data": notification.data,
"timestamp": notification.timestamp
}
payload_bytes = json.dumps(payload).encode('utf-8')
# In a full implementation, this would write to a BLE characteristic
# that connected devices are subscribed to. For now, we'll just log it.
print(f"BLE Notification: {notification.type.value} - {notification.message}")
# Use GATT server if available
if self._gatt_adapter and self._gatt_server_running:
try:
# Send via system notification characteristic
from ..ble.characteristics import SystemCharacteristicUUIDs
await self._gatt_adapter.send_notification(
SystemCharacteristicUUIDs.INFO,
payload_bytes
)
logger.debug("BLE notification sent via GATT: %s", notification.type.value)
return
except Exception as e:
logger.warning("Failed to send GATT notification: %s", e)
# If we had connected devices, we would send the notification here
# This would require setting up a GATT server with proper characteristics
# For simplicity in this MVP, we're using a notification-based approach
# Fallback: log the notification
logger.info("BLE Notification: %s - %s", notification.type.value, notification.message)
def is_available(self) -> bool:
"""Check if BLE is available.

View File

@@ -2,15 +2,18 @@
Provides a plugin framework for extending functionality.
Supports dynamic loading, enabling/disabling, and lifecycle management.
Includes header widget system and websocket broadcasting for plugins.
"""
import asyncio
import importlib.util
import inspect
import json
from dataclasses import dataclass, asdict
import time
from dataclasses import dataclass, asdict, field
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Optional, Dict, Any, List, Callable
from typing import Optional, Dict, Any, List, Callable, Set
import sys
from .. import config
@@ -24,6 +27,48 @@ class PluginStatus(str, Enum):
ERROR = "error"
class WidgetSeverity(str, Enum):
"""Widget severity levels for header widgets."""
INFO = "info"
WARNING = "warning"
ERROR = "error"
SUCCESS = "success"
@dataclass
class HeaderWidget:
"""Header widget data for displaying status in the UI.
Attributes:
id: Unique identifier (will be prefixed with source for plugins)
source: Source identifier (e.g., "ups_manager", "plugin:hello_world")
severity: Visual severity level
message: Display message
dismissible: Whether user can dismiss the widget
icon: Optional emoji/icon
action_label: Optional action button label
action_url: Optional action button URL
metadata: Additional data
created_at: ISO timestamp of creation
expires_at: Optional expiry (ISO timestamp)
"""
id: str
source: str
severity: WidgetSeverity
message: str
dismissible: bool = True
icon: Optional[str] = None
action_label: Optional[str] = None
action_url: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None
created_at: Optional[str] = None
expires_at: Optional[str] = None
def __post_init__(self):
if self.created_at is None:
self.created_at = datetime.now(timezone.utc).isoformat()
@dataclass
class PluginMetadata:
"""Plugin metadata information."""
@@ -57,12 +102,30 @@ class PluginBase:
"""Base class for all plugins.
Plugins should inherit from this class and implement the required methods.
Provides access to header widgets, websocket broadcasting, and hardware.
"""
# Websocket rate limiting: max events per second
WS_RATE_LIMIT = 10
def __init__(self):
"""Initialize the plugin."""
self.metadata: Optional[PluginMetadata] = None
self.hooks: Dict[str, List[Callable]] = {}
self._ws_event_times: List[float] = []
def _has_permission(self, permission: str) -> bool:
"""Check if plugin has a specific permission.
Args:
permission: Permission name to check
Returns:
True if plugin has permission, False otherwise
"""
if self.metadata is None:
return False
return permission in (self.metadata.permissions or [])
async def on_load(self):
"""Called when the plugin is loaded.
@@ -114,9 +177,234 @@ class PluginBase:
"""
raise NotImplementedError("Plugin must implement get_metadata()")
# -------------------------------------------------------------------------
# Header Widget Methods
# -------------------------------------------------------------------------
def register_widget(
self,
widget_id: str,
severity: WidgetSeverity,
message: str,
dismissible: bool = True,
icon: Optional[str] = None,
action_label: Optional[str] = None,
action_url: Optional[str] = None,
expires_at: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None
) -> bool:
"""Register a header widget for display in the UI.
Widget ID is automatically prefixed with plugin namespace.
Example: "status" becomes "plugin.hello_world.status"
Args:
widget_id: Short identifier for the widget
severity: Visual severity level (info, warning, error, success)
message: Display message
dismissible: Whether user can dismiss the widget
icon: Optional emoji/icon
action_label: Optional action button label
action_url: Optional action button URL
expires_at: Optional expiry timestamp (ISO format)
metadata: Additional data
Returns:
True if registered successfully, False otherwise
"""
if self.metadata is None:
return False
# Create full widget ID with plugin namespace
full_id = f"plugin.{self.metadata.id}.{widget_id}"
widget = HeaderWidget(
id=full_id,
source=f"plugin:{self.metadata.id}",
severity=severity,
message=message,
dismissible=dismissible,
icon=icon,
action_label=action_label,
action_url=action_url,
expires_at=expires_at,
metadata=metadata
)
plugin_manager = get_plugin_manager()
return plugin_manager.register_widget(widget)
def unregister_widget(self, widget_id: str) -> None:
"""Remove a header widget.
Args:
widget_id: Short identifier (without plugin prefix)
"""
if self.metadata is None:
return
full_id = f"plugin.{self.metadata.id}.{widget_id}"
plugin_manager = get_plugin_manager()
plugin_manager.unregister_widget(full_id)
# -------------------------------------------------------------------------
# Websocket Broadcasting Methods
# -------------------------------------------------------------------------
async def broadcast_event(self, event_type: str, data: dict) -> bool:
"""Broadcast a websocket event to all connected clients.
Requires 'websocket' permission in plugin.json.
Event type is prefixed with plugin namespace: 'plugin.{plugin_id}.{event_type}'
Rate limited to WS_RATE_LIMIT events per second.
Args:
event_type: Event type name (will be prefixed)
data: Event data dictionary
Returns:
True if broadcast successful, False if rate limited or no permission
"""
if not self._has_permission("websocket"):
print(f"Plugin {self.metadata.id if self.metadata else 'unknown'}: "
"websocket permission required for broadcast_event()")
return False
# Rate limiting
now = time.time()
self._ws_event_times = [t for t in self._ws_event_times if now - t < 1.0]
if len(self._ws_event_times) >= self.WS_RATE_LIMIT:
print(f"Plugin {self.metadata.id}: rate limited (>{self.WS_RATE_LIMIT}/s)")
return False
self._ws_event_times.append(now)
# Broadcast with namespaced event type
try:
from ..websocket.notifications import notify_plugin_event
full_event_type = f"plugin.{self.metadata.id}.{event_type}"
await notify_plugin_event(self.metadata.id, full_event_type, data)
return True
except ImportError:
print(f"Plugin {self.metadata.id}: websocket notifications not available")
return False
except Exception as e:
print(f"Plugin {self.metadata.id}: broadcast error: {e}")
return False
# -------------------------------------------------------------------------
# Hardware Access Methods
# -------------------------------------------------------------------------
def get_i2c(self, bus: int = 1):
"""Get I2C bus access.
Requires 'i2c' permission in plugin.json.
Args:
bus: I2C bus number (default: 1)
Returns:
SMBus instance or None if not available/permitted
Raises:
PermissionError: If plugin lacks 'i2c' permission
"""
if not self._has_permission("i2c"):
raise PermissionError(
f"Plugin {self.metadata.id if self.metadata else 'unknown'}: "
"'i2c' permission required"
)
from ..services.hardware_service import HardwareService
return HardwareService.get_i2c_bus(
self.metadata.id if self.metadata else "unknown",
bus
)
def get_gpio(self):
"""Get GPIO access.
Requires 'gpio' permission in plugin.json.
Returns:
GPIO module or None if not available/permitted
Raises:
PermissionError: If plugin lacks 'gpio' permission
"""
if not self._has_permission("gpio"):
raise PermissionError(
f"Plugin {self.metadata.id if self.metadata else 'unknown'}: "
"'gpio' permission required"
)
from ..services.hardware_service import HardwareService
return HardwareService.get_gpio(
self.metadata.id if self.metadata else "unknown"
)
def get_spi(self, bus: int = 0, device: int = 0):
"""Get SPI device access.
Requires 'spi' permission in plugin.json.
Args:
bus: SPI bus number (default: 0)
device: SPI device/chip select (default: 0)
Returns:
SpiDev instance or None if not available/permitted
Raises:
PermissionError: If plugin lacks 'spi' permission
"""
if not self._has_permission("spi"):
raise PermissionError(
f"Plugin {self.metadata.id if self.metadata else 'unknown'}: "
"'spi' permission required"
)
from ..services.hardware_service import HardwareService
return HardwareService.get_spi(
self.metadata.id if self.metadata else "unknown",
bus,
device
)
def get_serial(self, port: str, baudrate: int = 9600):
"""Get serial port access.
Requires 'serial' permission in plugin.json.
Args:
port: Serial port path (e.g., '/dev/ttyUSB0')
baudrate: Baud rate (default: 9600)
Returns:
Serial instance or None if not available/permitted
Raises:
PermissionError: If plugin lacks 'serial' permission
"""
if not self._has_permission("serial"):
raise PermissionError(
f"Plugin {self.metadata.id if self.metadata else 'unknown'}: "
"'serial' permission required"
)
from ..services.hardware_service import HardwareService
return HardwareService.get_serial(
self.metadata.id if self.metadata else "unknown",
port,
baudrate
)
class PluginManager:
"""Manages plugin loading, enabling, and lifecycle."""
"""Manages plugin loading, enabling, lifecycle, and header widgets."""
# Maximum number of active widgets
MAX_WIDGETS = 10
def __init__(self):
"""Initialize the plugin manager."""
@@ -126,6 +414,10 @@ class PluginManager:
self._hooks: Dict[str, List[Callable]] = {}
self._enabled_plugins: List[str] = []
# Header widget registry
self._header_widgets: Dict[str, HeaderWidget] = {}
self._dismissed_widgets: Set[str] = set()
# Create plugins directory if it doesn't exist
self._plugin_dir.mkdir(parents=True, exist_ok=True)
@@ -406,6 +698,98 @@ class PluginManager:
"""
return self._enabled_plugins.copy()
# -------------------------------------------------------------------------
# Header Widget Methods
# -------------------------------------------------------------------------
def register_widget(self, widget: HeaderWidget) -> bool:
"""Register a header widget.
Args:
widget: HeaderWidget to register
Returns:
True if registered successfully, False if dismissed or at limit
"""
# Check if user dismissed this widget
if widget.id in self._dismissed_widgets:
return False
# Check widget limit
if len(self._header_widgets) >= self.MAX_WIDGETS:
# Remove oldest expired widget if any
self._cleanup_expired_widgets()
if len(self._header_widgets) >= self.MAX_WIDGETS:
print(f"Widget limit reached ({self.MAX_WIDGETS}), cannot register {widget.id}")
return False
self._header_widgets[widget.id] = widget
print(f"Registered widget: {widget.id}")
return True
def unregister_widget(self, widget_id: str) -> None:
"""Remove a widget from the registry.
Args:
widget_id: ID of widget to remove
"""
if widget_id in self._header_widgets:
del self._header_widgets[widget_id]
print(f"Unregistered widget: {widget_id}")
def get_active_widgets(self) -> List[HeaderWidget]:
"""Get all active, non-expired widgets.
Returns:
List of active HeaderWidget objects
"""
self._cleanup_expired_widgets()
return list(self._header_widgets.values())
def dismiss_widget(self, widget_id: str) -> bool:
"""Mark widget as dismissed by user.
Args:
widget_id: ID of widget to dismiss
Returns:
True if widget was dismissed, False if not found
"""
if widget_id in self._header_widgets:
widget = self._header_widgets[widget_id]
if not widget.dismissible:
print(f"Widget {widget_id} is not dismissible")
return False
self._dismissed_widgets.add(widget_id)
del self._header_widgets[widget_id]
print(f"Dismissed widget: {widget_id}")
return True
return False
def clear_dismissed(self) -> None:
"""Clear all dismissed widget IDs, allowing them to appear again."""
self._dismissed_widgets.clear()
print("Cleared dismissed widgets")
def _cleanup_expired_widgets(self) -> None:
"""Remove expired widgets from the registry."""
now = datetime.now(timezone.utc)
expired = []
for widget_id, widget in self._header_widgets.items():
if widget.expires_at:
try:
expiry = datetime.fromisoformat(widget.expires_at.replace('Z', '+00:00'))
if now > expiry:
expired.append(widget_id)
except (ValueError, TypeError):
pass
for widget_id in expired:
del self._header_widgets[widget_id]
print(f"Expired widget removed: {widget_id}")
# Global plugin manager instance
_plugin_manager: Optional[PluginManager] = None

View File

@@ -0,0 +1,970 @@
"""Proxmark3 Device Manager for multi-device support."""
import asyncio
import hashlib
import logging
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional
import json
try:
import pyudev
UDEV_AVAILABLE = True
except ImportError:
UDEV_AVAILABLE = False
try:
import serial.tools.list_ports
SERIAL_AVAILABLE = True
except ImportError:
SERIAL_AVAILABLE = False
from ..workers.pm3_worker import PM3Worker, SubprocessPM3Worker
from .. import config
# Flag to track if Python bindings work (set once on first try)
_python_bindings_work = None
logger = logging.getLogger(__name__)
class DeviceStatus(Enum):
"""Device availability status."""
CONNECTED = "connected" # Ready to use
DISCONNECTED = "disconnected" # Not detected
IN_USE = "in_use" # Active session
ERROR = "error" # Communication error
VERSION_MISMATCH = "version_mismatch" # Firmware incompatible
FLASHING = "flashing" # Firmware update in progress
BOOTLOADER_MODE = "bootloader_mode" # In bootloader, needs flash
DISABLED = "disabled" # Mismatch ignored by user
@dataclass
class PM3FirmwareInfo:
"""Firmware version information."""
bootrom_version: str = "unknown" # e.g., "v4.14831"
os_version: str = "unknown" # e.g., "v4.14831"
client_version: str = "unknown" # Local client version
compatible: bool = False # Versions match
needs_upgrade: bool = False # Device firmware older
needs_downgrade: bool = False # Device firmware newer
bootloader_outdated: bool = False # Bootloader needs update
@dataclass
class PM3Device:
"""Represents a single Proxmark3 device."""
device_id: str # Unique ID (hash of serial + device path)
device_path: str # /dev/ttyACM0, /dev/ttyACM1, etc.
serial_number: Optional[str] = None # USB serial number (if available)
friendly_name: Optional[str] = None # User-assigned name
usb_vid: Optional[str] = None # USB Vendor ID
usb_pid: Optional[str] = None # USB Product ID
status: DeviceStatus = DeviceStatus.DISCONNECTED
firmware_info: PM3FirmwareInfo = field(default_factory=PM3FirmwareInfo)
last_seen: datetime = field(default_factory=datetime.now)
first_seen: datetime = field(default_factory=datetime.now)
worker: Optional[PM3Worker] = None # Dedicated worker instance
metadata: Dict = field(default_factory=dict) # Additional metadata
def to_dict(self) -> dict:
"""Convert to dictionary for API responses."""
return {
"device_id": self.device_id,
"device_path": self.device_path,
"serial_number": self.serial_number,
"friendly_name": self.friendly_name or self.device_path.split('/')[-1],
"usb_vid": self.usb_vid,
"usb_pid": self.usb_pid,
"status": self.status.value,
"firmware_info": {
"bootrom_version": self.firmware_info.bootrom_version,
"os_version": self.firmware_info.os_version,
"client_version": self.firmware_info.client_version,
"compatible": self.firmware_info.compatible,
"needs_upgrade": self.firmware_info.needs_upgrade,
"needs_downgrade": self.firmware_info.needs_downgrade,
},
"last_seen": self.last_seen.isoformat(),
"first_seen": self.first_seen.isoformat(),
"connected": self.status == DeviceStatus.CONNECTED,
"in_use": self.status == DeviceStatus.IN_USE,
}
class PM3DeviceManager:
"""Manages multiple Proxmark3 devices."""
# USB VID/PID for Proxmark3 devices
PM3_USB_VID_PRIMARY = "9ac4" # Standard PM3
PM3_USB_PID_PRIMARY = "4b8f"
PM3_USB_VID_EASY = "502d" # PM3 Easy
PM3_USB_PID_EASY = "502d"
# Alternative identifiers
PM3_VENDOR_IDS = ["9ac4", "502d", "2d0d"] # Known PM3 vendor IDs
PM3_PRODUCT_IDS = ["4b8f", "502d"] # Known PM3 product IDs
def __init__(self):
"""Initialize device manager."""
self._devices: Dict[str, PM3Device] = {} # device_id -> PM3Device
self._lock = asyncio.Lock()
self._monitor_task: Optional[asyncio.Task] = None
self._udev_context = None
self._udev_monitor = None
self._device_change_callbacks: List = [] # Callbacks for device changes
# Device discovery settings
self.auto_discover = True
self.discovery_interval = 0.5 # seconds - 500ms for responsive SSE updates
self.device_timeout = 300 # seconds
self._last_device_state: Dict[str, str] = {} # device_id -> status for change detection
logger.info("PM3DeviceManager initialized")
def register_device_change_callback(self, callback):
"""Register a callback for device list changes.
Args:
callback: Async function that takes a list of PM3Device
"""
self._device_change_callbacks.append(callback)
logger.info(f"Registered device change callback: {callback}")
async def _notify_device_change(self, force: bool = False):
"""Notify all registered callbacks of device list changes.
Args:
force: If True, send notification even if no changes detected
"""
# Build current state snapshot
current_state = {
d.device_id: d.status.value if hasattr(d.status, 'value') else str(d.status)
for d in self._devices.values()
}
# Check if anything changed
if not force and current_state == self._last_device_state:
return # No changes, skip notification
# Update last state
self._last_device_state = current_state.copy()
# Notify all callbacks
devices = list(self._devices.values())
for callback in self._device_change_callbacks:
try:
await callback(devices)
except Exception as e:
logger.error(f"Error in device change callback: {e}")
async def start(self):
"""Start device manager and monitoring."""
logger.info("Starting PM3 device manager")
# Initial device discovery (force notification to send initial state)
await self.discover_devices()
await self._notify_device_change(force=True)
# Start monitoring for hotplug events
if UDEV_AVAILABLE:
await self._start_udev_monitor()
else:
logger.warning("pyudev not available, using polling fallback")
await self._start_polling_monitor()
async def stop(self):
"""Stop device manager and monitoring."""
logger.info("Stopping PM3 device manager")
if self._monitor_task:
self._monitor_task.cancel()
try:
await self._monitor_task
except asyncio.CancelledError:
pass
# Disconnect all devices
async with self._lock:
for device in self._devices.values():
if device.worker:
await device.worker.disconnect()
async def discover_devices(self) -> List[PM3Device]:
"""Scan USB ports for PM3 devices.
Returns:
List of discovered PM3Device objects
"""
async with self._lock:
discovered_paths = set()
# Method 1: Use pyserial to enumerate serial ports
if SERIAL_AVAILABLE:
discovered_paths.update(await self._discover_via_serial())
# Method 2: Scan /dev/ttyACM* directly
discovered_paths.update(await self._discover_via_dev())
# Process discovered devices
current_devices = {}
for device_path in discovered_paths:
device_id = self._generate_device_id(device_path)
if device_id in self._devices:
# Update existing device
device = self._devices[device_id]
device.last_seen = datetime.now()
device.status = DeviceStatus.CONNECTED
else:
# Create new device
device = await self._create_device(device_path)
current_devices[device_id] = device
# Mark missing devices as disconnected
for device_id, device in self._devices.items():
if device_id not in current_devices:
device.status = DeviceStatus.DISCONNECTED
current_devices[device_id] = device
self._devices = current_devices
connected_count = len([d for d in self._devices.values() if d.status == DeviceStatus.CONNECTED])
logger.info(f"Discovered {connected_count} connected PM3 devices")
# Notify callbacks of device changes (only if state changed)
await self._notify_device_change()
return list(self._devices.values())
async def _discover_via_serial(self) -> set:
"""Discover devices using pyserial."""
devices = set()
try:
ports = serial.tools.list_ports.comports()
for port in ports:
# Check if it's a PM3 device by VID/PID
if port.vid and port.pid:
vid = f"{port.vid:04x}"
pid = f"{port.pid:04x}"
if vid in self.PM3_VENDOR_IDS or pid in self.PM3_PRODUCT_IDS:
devices.add(port.device)
logger.debug(f"Found PM3 device via serial: {port.device} (VID:{vid} PID:{pid})")
except Exception as e:
logger.error(f"Error discovering devices via serial: {e}")
return devices
async def _discover_via_dev(self) -> set:
"""Discover devices by scanning /dev/ttyACM*."""
devices = set()
try:
# Look for /dev/ttyACM* devices
dev_path = Path("/dev")
for device_file in dev_path.glob("ttyACM*"):
if device_file.is_char_device():
devices.add(str(device_file))
logger.debug(f"Found device: {device_file}")
except Exception as e:
logger.error(f"Error scanning /dev: {e}")
return devices
async def _create_device(self, device_path: str) -> PM3Device:
"""Create a new PM3Device object.
Args:
device_path: Path to device (e.g., /dev/ttyACM0)
Returns:
PM3Device object
"""
device_id = self._generate_device_id(device_path)
# Get USB info if available
usb_info = await self._get_usb_info(device_path)
# Create device object
device = PM3Device(
device_id=device_id,
device_path=device_path,
serial_number=usb_info.get("serial"),
usb_vid=usb_info.get("vid"),
usb_pid=usb_info.get("pid"),
status=DeviceStatus.CONNECTED,
friendly_name=None, # Will be set by user or auto-generated
first_seen=datetime.now(),
last_seen=datetime.now()
)
# Use SubprocessPM3Worker (more reliable than SWIG bindings which may not be built)
device.worker = SubprocessPM3Worker(device_path=device_path)
# Query firmware version (in background, don't block)
asyncio.create_task(self._query_firmware_version(device))
logger.info(f"Created device {device_id} at {device_path}")
return device
def _generate_device_id(self, device_path: str, serial: Optional[str] = None) -> str:
"""Generate unique device ID.
Args:
device_path: Device path
serial: Optional serial number
Returns:
Unique device ID
"""
# Use serial number if available, otherwise use path
identifier = serial if serial else device_path
# Generate short hash
hash_obj = hashlib.md5(identifier.encode())
return f"pm3_{hash_obj.hexdigest()[:8]}"
async def _get_usb_info(self, device_path: str) -> dict:
"""Get USB device information.
Args:
device_path: Device path
Returns:
Dictionary with vid, pid, serial
"""
info = {}
if SERIAL_AVAILABLE:
try:
# Find port info
ports = serial.tools.list_ports.comports()
for port in ports:
if port.device == device_path:
if port.vid:
info["vid"] = f"{port.vid:04x}"
if port.pid:
info["pid"] = f"{port.pid:04x}"
if port.serial_number:
info["serial"] = port.serial_number
break
except Exception as e:
logger.error(f"Error getting USB info: {e}")
return info
async def _query_firmware_version(self, device: PM3Device):
"""Query device firmware version.
Args:
device: PM3Device to query
"""
try:
if not device.worker:
return
# Execute hw version command
result = await device.worker.execute_command("hw version")
if result.success:
# Parse firmware version from output
firmware_info = self._parse_firmware_version(result.output)
device.firmware_info = firmware_info
# Update device status based on compatibility
if not firmware_info.compatible:
device.status = DeviceStatus.VERSION_MISMATCH
logger.info(f"Device {device.device_id} firmware: {firmware_info.os_version}")
except Exception as e:
logger.error(f"Error querying firmware version for {device.device_id}: {e}")
device.status = DeviceStatus.ERROR
def _parse_firmware_version(self, output: str) -> PM3FirmwareInfo:
"""Parse firmware version from hw version output.
Args:
output: Output from 'hw version' command
Returns:
PM3FirmwareInfo object
"""
import re
info = PM3FirmwareInfo()
# Parse bootrom version (handles Iceman format: "Iceman/master/v4.20469-104-ge509967ab-suspect")
bootrom_match = re.search(r'Bootrom[:\s.]+(.+?)(?:\s+\d{4}-\d{2}-\d{2}|\s+[0-9a-f]{9}|$)', output, re.IGNORECASE | re.MULTILINE)
if bootrom_match:
info.bootrom_version = bootrom_match.group(1).strip()
# Parse OS version (handles Iceman format)
os_match = re.search(r'OS[:\s.]+(.+?)(?:\s+\d{4}-\d{2}-\d{2}|\s+[0-9a-f]{9}|$)', output, re.IGNORECASE | re.MULTILINE)
if os_match:
info.os_version = os_match.group(1).strip()
# Parse client version (handles Iceman format where [ Client ] is on separate line)
# Format: "[ Client ]\n Iceman/master/4fa8f27-dirty-suspect 2026-01-04 ..."
client_match = re.search(
r'\[\s*Client\s*\]\s*\n\s*([A-Za-z]+/\w+/[^\s]+)',
output,
re.IGNORECASE | re.MULTILINE
)
if client_match:
info.client_version = client_match.group(1).strip()
# Check compatibility by comparing base version (commit hash)
# Extract the version identifier (e.g., "Iceman/master/66c7374-dirty-suspect")
# The key part is the commit hash (66c7374) - timestamps will differ between builds
def extract_base_version(ver_str: str) -> str:
"""Extract base version identifier for comparison."""
# Match patterns like:
# "Iceman/master/66c7374-dirty-suspect" (standard)
# "Iceman/DangerousPi/master/66c7374-dirty-suspect" (custom build)
# "Iceman/master/v4.20469-104-ge509967ab" (version tag)
# Capture everything up to and including the commit/version identifier
match = re.match(r'([A-Za-z]+(?:/[A-Za-z]+)?/\w+/[a-z0-9v.-]+)', ver_str)
return match.group(1) if match else ver_str
os_base = extract_base_version(info.os_version)
bootrom_base = extract_base_version(info.bootrom_version)
client_base = extract_base_version(info.client_version)
info.compatible = (
info.os_version != "unknown" and
info.bootrom_version != "unknown" and
info.client_version != "unknown" and
os_base == client_base and
bootrom_base == client_base
)
# For version comparison, extract just the version number
def extract_version(ver_str: str) -> str:
"""Extract version number from version string."""
ver_match = re.search(r'v?(\d+\.\d+)', ver_str)
return ver_match.group(1) if ver_match else ver_str
os_ver = extract_version(info.os_version)
client_ver = extract_version(info.client_version)
bootrom_ver = extract_version(info.bootrom_version)
info.needs_upgrade = os_ver < client_ver if os_ver != "unknown" and client_ver != "unknown" else False
info.needs_downgrade = os_ver > client_ver if os_ver != "unknown" and client_ver != "unknown" else False
info.bootloader_outdated = bootrom_ver < client_ver if bootrom_ver != "unknown" and client_ver != "unknown" else False
return info
def _get_local_client_version(self) -> str:
"""Get version of locally installed proxmark3 client.
Runs the client binary with --version flag to detect installed version.
Returns:
Client version string or "unknown"
"""
import subprocess
from pathlib import Path
client_path = Path(config.PM3_CLIENT_PATH)
if not client_path.exists():
logger.debug(f"PM3 client not found at {client_path}")
return "unknown"
try:
# Run proxmark3 --version to get version info
result = subprocess.run(
[str(client_path), "--version"],
capture_output=True,
text=True,
timeout=5
)
output = result.stdout + result.stderr
# Parse version from output (typically like "Proxmark3 client - (RRG/Iceman v4.14831)")
import re
match = re.search(r'v[\d.]+', output)
if match:
return match.group(0)
# Fallback: look for any version-like pattern
match = re.search(r'(\d+\.\d+)', output)
if match:
return f"v{match.group(1)}"
logger.debug(f"Could not parse version from: {output[:200]}")
return "unknown"
except subprocess.TimeoutExpired:
logger.warning("Timeout getting PM3 client version")
return "unknown"
except Exception as e:
logger.debug(f"Error getting PM3 client version: {e}")
return "unknown"
async def get_device(self, device_id: str) -> Optional[PM3Device]:
"""Get device by ID.
Args:
device_id: Device ID
Returns:
PM3Device or None if not found
"""
async with self._lock:
return self._devices.get(device_id)
async def get_all_devices(self) -> List[PM3Device]:
"""Get all known devices.
Returns:
List of all PM3Device objects
"""
async with self._lock:
return list(self._devices.values())
async def get_available_devices(self) -> List[PM3Device]:
"""Get devices not currently in use.
Returns:
List of available PM3Device objects
"""
async with self._lock:
return [
device for device in self._devices.values()
if device.status == DeviceStatus.CONNECTED
]
async def get_connected_devices(self) -> List[PM3Device]:
"""Get connected devices.
Returns:
List of connected PM3Device objects
"""
async with self._lock:
return [
device for device in self._devices.values()
if device.status not in [DeviceStatus.DISCONNECTED, DeviceStatus.ERROR]
]
async def set_device_status(self, device_id: str, status: DeviceStatus) -> bool:
"""Set device status.
Args:
device_id: Device ID
status: New status
Returns:
True if successful, False if device not found
"""
async with self._lock:
device = self._devices.get(device_id)
if device:
device.status = status
return True
return False
async def identify_device(self, device_id: str, duration_ms: int = 2000):
"""Blink LEDs on device for identification.
Uses the custom hw led command (from our led-pwm-control.patch) to
flash all LEDs in a recognizable pattern.
Args:
device_id: Device ID
duration_ms: Blink duration in milliseconds
Raises:
ValueError: If device not found
RuntimeError: If identification fails
"""
device = await self.get_device(device_id)
if not device:
raise ValueError(f"Device {device_id} not found")
if not device.worker:
raise RuntimeError(f"Device {device_id} has no worker")
try:
# Calculate number of blink cycles based on duration
# Each cycle is ~400ms (200ms on + 200ms off)
cycles = max(1, duration_ms // 400)
for i in range(cycles):
# Turn all LEDs on
result = await device.worker.execute_command("hw led --led a,b,c,d --on")
if not result.success:
logger.warning(f"hw led on failed: {result.error}")
await asyncio.sleep(0.2)
# Turn all LEDs off
result = await device.worker.execute_command("hw led --led a,b,c,d --off")
if not result.success:
logger.warning(f"hw led off failed: {result.error}")
if i < cycles - 1:
await asyncio.sleep(0.2)
logger.info(f"Identified device {device_id} with {cycles} LED blink cycles")
except Exception as e:
logger.error(f"Error identifying device {device_id}: {e}")
raise RuntimeError(f"Failed to identify device: {e}")
async def flash_firmware(self, device_id: str) -> dict:
"""Flash firmware to a PM3 device.
Flashes both bootrom and fullimage from bundled firmware files.
Progress is reported via WebSocket notifications.
Args:
device_id: Device ID to flash
Returns:
dict with success status and message
"""
from ..websocket.notifications import notify_pm3_flash_progress
device = await self.get_device(device_id)
if not device:
return {"success": False, "error": "Device not found"}
# Check device is not already flashing
if device.status == DeviceStatus.FLASHING:
return {"success": False, "error": "Device is already being flashed"}
# Check device is not in use
if device.status == DeviceStatus.IN_USE:
return {"success": False, "error": "Device is in use. End session first."}
# Firmware paths
firmware_dir = Path(config.FIRMWARE_DIR)
bootrom_path = firmware_dir / "bootrom.elf"
fullimage_path = firmware_dir / "fullimage.elf"
# Validate firmware files exist
if not bootrom_path.exists():
return {"success": False, "error": f"Bootrom firmware not found at {bootrom_path}"}
if not fullimage_path.exists():
return {"success": False, "error": f"Fullimage firmware not found at {fullimage_path}"}
# Set device to flashing state
original_status = device.status
device.status = DeviceStatus.FLASHING
await self._notify_device_change(force=True)
try:
# Send starting notification
await notify_pm3_flash_progress(
device_id=device_id,
status="starting",
progress=0,
message="Preparing to flash firmware..."
)
# Find pm3-flash-all utility
pm3_flash_path = await self._find_pm3_flash_utility()
if not pm3_flash_path:
raise RuntimeError("pm3-flash-all utility not found")
# Phase 1: Flash bootrom (0-40%)
await notify_pm3_flash_progress(
device_id=device_id,
status="bootrom",
progress=10,
message="Flashing bootrom..."
)
bootrom_result = await self._execute_flash_command(
pm3_flash_path,
device.device_path,
str(bootrom_path),
"bootrom",
device_id
)
if not bootrom_result["success"]:
raise RuntimeError(f"Bootrom flash failed: {bootrom_result['error']}")
await notify_pm3_flash_progress(
device_id=device_id,
status="bootrom",
progress=40,
message="Bootrom flashed successfully"
)
# Brief delay for device to restart
await asyncio.sleep(2)
# Phase 2: Flash fullimage (50-90%)
await notify_pm3_flash_progress(
device_id=device_id,
status="fullimage",
progress=50,
message="Flashing fullimage..."
)
fullimage_result = await self._execute_flash_command(
pm3_flash_path,
device.device_path,
str(fullimage_path),
"fullimage",
device_id
)
if not fullimage_result["success"]:
raise RuntimeError(f"Fullimage flash failed: {fullimage_result['error']}")
await notify_pm3_flash_progress(
device_id=device_id,
status="fullimage",
progress=90,
message="Fullimage flashed successfully"
)
# Phase 3: Verify (95%)
await notify_pm3_flash_progress(
device_id=device_id,
status="verifying",
progress=95,
message="Verifying firmware..."
)
# Wait for device to restart
await asyncio.sleep(3)
# Re-query firmware version
await self._query_firmware_version(device)
# Check if now compatible
if device.firmware_info.compatible:
device.status = DeviceStatus.CONNECTED
message = "Firmware updated successfully"
else:
device.status = DeviceStatus.VERSION_MISMATCH
message = "Firmware flashed but version mismatch persists"
await notify_pm3_flash_progress(
device_id=device_id,
status="complete",
progress=100,
message=message
)
await self._notify_device_change(force=True)
logger.info(f"Successfully flashed firmware to device {device_id}")
return {"success": True, "message": message}
except Exception as e:
logger.error(f"Firmware flash failed for device {device_id}: {e}")
# Notify of error
await notify_pm3_flash_progress(
device_id=device_id,
status="error",
progress=0,
message=str(e)
)
# Restore original status or set to error
device.status = DeviceStatus.ERROR
await self._notify_device_change(force=True)
return {"success": False, "error": str(e)}
async def _find_pm3_flash_utility(self) -> Optional[str]:
"""Find pm3-flash-all or pm3-flash utility.
Returns:
Path to flash utility or None if not found
"""
import shutil
# Search locations in order of preference
search_paths = [
# Bundled with dangerous-pi
Path(config.PM3_CLIENT_PATH).parent / "pm3-flash-all" if hasattr(config, 'PM3_CLIENT_PATH') else None,
# Default installation
Path("/home/dt/.pm3/proxmark3/pm3-flash-all"),
Path("/home/dt/.pm3/proxmark3/client/flasher"),
# System path
Path(shutil.which("pm3-flash-all") or ""),
Path(shutil.which("flasher") or ""),
]
for path in search_paths:
if path and path.exists() and path.is_file():
logger.info(f"Found pm3 flash utility at: {path}")
return str(path)
logger.warning("pm3 flash utility not found in standard locations")
return None
async def _execute_flash_command(
self,
flash_path: str,
device_path: str,
firmware_path: str,
phase: str,
device_id: str
) -> dict:
"""Execute flash command and parse output.
Args:
flash_path: Path to flash utility
device_path: Device path (e.g., /dev/ttyACM0)
firmware_path: Path to .elf firmware file
phase: "bootrom" or "fullimage"
device_id: Device ID for progress notifications
Returns:
dict with success status
"""
from ..websocket.notifications import notify_pm3_flash_progress
# Build command
# pm3-flash-all expects: pm3-flash-all -p /dev/ttyACMx [bootrom.elf] [fullimage.elf]
# But we're doing them separately for better progress tracking
cmd = [flash_path, "-p", device_path, firmware_path]
logger.info(f"Executing flash command: {' '.join(cmd)}")
try:
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT
)
output_lines = []
base_progress = 10 if phase == "bootrom" else 50
max_progress = 40 if phase == "bootrom" else 90
# Read output line by line and parse progress
while True:
line = await process.stdout.readline()
if not line:
break
line_str = line.decode('utf-8', errors='replace').strip()
output_lines.append(line_str)
logger.debug(f"Flash output: {line_str}")
# Parse progress from output
progress = self._parse_flash_progress(line_str, base_progress, max_progress)
if progress:
await notify_pm3_flash_progress(
device_id=device_id,
status=phase,
progress=progress,
message=f"Flashing {phase}..."
)
await process.wait()
output = "\n".join(output_lines)
if process.returncode == 0:
return {"success": True, "output": output}
else:
# Check for common errors in output
error_msg = self._extract_flash_error(output)
return {"success": False, "error": error_msg or f"Flash exited with code {process.returncode}"}
except Exception as e:
logger.error(f"Flash command execution failed: {e}")
return {"success": False, "error": str(e)}
def _parse_flash_progress(self, line: str, base: int, max_val: int) -> Optional[int]:
"""Parse progress percentage from flash output line.
Args:
line: Output line from flash process
base: Base progress percentage
max_val: Maximum progress percentage
Returns:
Progress percentage or None
"""
import re
# Look for percentage patterns like "50%" or "Writing: 50%"
percent_match = re.search(r'(\d+)%', line)
if percent_match:
raw_percent = int(percent_match.group(1))
# Scale to our range
scaled = base + (raw_percent / 100) * (max_val - base)
return int(scaled)
# Look for block-based progress like "Writing block 10/20"
block_match = re.search(r'(\d+)\s*/\s*(\d+)', line)
if block_match and 'block' in line.lower():
current = int(block_match.group(1))
total = int(block_match.group(2))
if total > 0:
raw_percent = (current / total) * 100
scaled = base + (raw_percent / 100) * (max_val - base)
return int(scaled)
return None
def _extract_flash_error(self, output: str) -> Optional[str]:
"""Extract error message from flash output.
Args:
output: Full flash output
Returns:
Error message or None
"""
error_patterns = [
r"error[:\s]+(.+?)(?:\n|$)",
r"failed[:\s]+(.+?)(?:\n|$)",
r"cannot\s+(.+?)(?:\n|$)",
r"permission denied",
r"device not found",
r"timeout",
]
import re
for pattern in error_patterns:
match = re.search(pattern, output, re.IGNORECASE)
if match:
return match.group(0).strip()
return None
async def _start_udev_monitor(self):
"""Start udev monitoring for device hotplug events."""
try:
logger.info("Starting udev device monitor")
# This will be implemented in a separate task
# For now, fall back to polling
await self._start_polling_monitor()
except Exception as e:
logger.error(f"Error starting udev monitor: {e}")
await self._start_polling_monitor()
async def _start_polling_monitor(self):
"""Start polling-based device monitoring."""
logger.info(f"Starting polling device monitor (interval: {self.discovery_interval}s)")
async def poll_devices():
while True:
try:
await asyncio.sleep(self.discovery_interval)
await self.discover_devices()
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in device polling: {e}")
self._monitor_task = asyncio.create_task(poll_devices())

View File

@@ -1,7 +1,11 @@
"""Session manager for single-user access control."""
"""Session manager for per-device access control.
Supports multiple concurrent sessions, one per PM3 device. Each device
can have at most one active session at a time.
"""
import asyncio
import time
from typing import Optional
from typing import Optional, Dict
from dataclasses import dataclass
import uuid
@@ -12,6 +16,7 @@ from .. import config
class Session:
"""Active session information."""
session_id: str
device_id: Optional[str] # None for legacy single-device mode
client_ip: str
user_agent: Optional[str]
created_at: float
@@ -19,52 +24,92 @@ class Session:
class SessionManager:
"""Manages single active session for PM3 access."""
"""Manages per-device sessions for PM3 access.
Each PM3 device can have at most one active session. Multiple devices
can be used concurrently by different sessions.
"""
# Key used for legacy single-device mode
DEFAULT_DEVICE_KEY = "_default"
def __init__(self):
"""Initialize session manager."""
self._active_session: Optional[Session] = None
self._active_sessions: Dict[str, Session] = {} # keyed by device_id
self._lock = asyncio.Lock()
def has_active_session(self) -> bool:
"""Check if there's an active session."""
if not self._active_session:
return False
def _get_device_key(self, device_id: Optional[str]) -> str:
"""Get the key to use for session lookup.
# Check if session has timed out
if time.time() - self._active_session.last_activity > config.SESSION_TIMEOUT:
self._active_session = None
return False
Args:
device_id: Device ID or None for legacy mode
return True
Returns:
Key to use in _active_sessions dict
"""
return device_id or self.DEFAULT_DEVICE_KEY
def _cleanup_expired_sessions(self) -> None:
"""Remove any expired sessions from the active sessions dict."""
current_time = time.time()
expired_keys = [
key for key, session in self._active_sessions.items()
if current_time - session.last_activity > config.SESSION_TIMEOUT
]
for key in expired_keys:
del self._active_sessions[key]
def has_active_session(self, device_id: Optional[str] = None) -> bool:
"""Check if there's an active session for a device.
Args:
device_id: Device ID to check. If None, checks for any active session.
Returns:
True if active session exists
"""
self._cleanup_expired_sessions()
if device_id is None:
# Check if ANY session is active (legacy behavior)
return len(self._active_sessions) > 0
key = self._get_device_key(device_id)
return key in self._active_sessions
async def create_session(
self,
client_ip: str,
user_agent: Optional[str] = None,
force_takeover: bool = False
force_takeover: bool = False,
device_id: Optional[str] = None
) -> tuple[bool, Optional[str], Optional[str]]:
"""Create a new session.
"""Create a new session for a device.
Args:
client_ip: Client IP address
user_agent: Client user agent string
force_takeover: Force takeover of existing session
device_id: Device ID to create session for (None for legacy mode)
Returns:
Tuple of (success, session_id, error_message)
"""
async with self._lock:
# Check if another session is active
if self.has_active_session() and not force_takeover:
return False, None, "Another session is active"
self._cleanup_expired_sessions()
key = self._get_device_key(device_id)
# Check if another session is active for this device
if key in self._active_sessions and not force_takeover:
return False, None, f"Another session is active for device {device_id or 'default'}"
# Create new session
session_id = str(uuid.uuid4())
current_time = time.time()
self._active_session = Session(
self._active_sessions[key] = Session(
session_id=session_id,
device_id=device_id,
client_ip=client_ip,
user_agent=user_agent,
created_at=current_time,
@@ -73,60 +118,111 @@ class SessionManager:
return True, session_id, None
async def release_session(self, session_id: str) -> bool:
async def release_session(self, session_id: str, device_id: Optional[str] = None) -> bool:
"""Release a session.
Args:
session_id: Session ID to release
device_id: Device ID (if known). If None, searches all sessions.
Returns:
True if session was released, False if not found
"""
async with self._lock:
if self._active_session and self._active_session.session_id == session_id:
self._active_session = None
return True
if device_id is not None:
# Direct lookup by device_id
key = self._get_device_key(device_id)
if key in self._active_sessions and self._active_sessions[key].session_id == session_id:
del self._active_sessions[key]
return True
else:
# Search all sessions for the session_id
for key, session in list(self._active_sessions.items()):
if session.session_id == session_id:
del self._active_sessions[key]
return True
return False
def update_activity(self, session_id: str) -> bool:
def update_activity(self, session_id: str, device_id: Optional[str] = None) -> bool:
"""Update session activity timestamp.
Args:
session_id: Session ID to update
device_id: Device ID (if known). If None, searches all sessions.
Returns:
True if updated, False if session not found
"""
if self._active_session and self._active_session.session_id == session_id:
self._active_session.last_activity = time.time()
return True
if device_id is not None:
key = self._get_device_key(device_id)
if key in self._active_sessions and self._active_sessions[key].session_id == session_id:
self._active_sessions[key].last_activity = time.time()
return True
else:
# Search all sessions
for session in self._active_sessions.values():
if session.session_id == session_id:
session.last_activity = time.time()
return True
return False
def can_execute(self, session_id: Optional[str]) -> bool:
"""Check if a session can execute commands.
def can_execute(self, session_id: Optional[str], device_id: Optional[str] = None) -> bool:
"""Check if a session can execute commands on a device.
Args:
session_id: Session ID to check (None for no session)
device_id: Device ID to check (None for legacy single-device mode)
Returns:
True if session can execute, False otherwise
"""
# No active session - allow execution
if not self.has_active_session():
self._cleanup_expired_sessions()
key = self._get_device_key(device_id)
# No active session for this device - allow execution
if key not in self._active_sessions:
return True
# Check if the provided session ID matches active session
if session_id and self._active_session and self._active_session.session_id == session_id:
# Check if the provided session ID matches the device's active session
if session_id and self._active_sessions[key].session_id == session_id:
return True
return False
def get_active_session(self) -> Optional[Session]:
"""Get the currently active session.
def get_active_session(self, device_id: Optional[str] = None) -> Optional[Session]:
"""Get the currently active session for a device.
Args:
device_id: Device ID to get session for. If None, returns any active session.
Returns:
Active session or None
"""
if self.has_active_session():
return self._active_session
return None
self._cleanup_expired_sessions()
if device_id is None:
# Return first active session (legacy behavior)
return next(iter(self._active_sessions.values()), None)
key = self._get_device_key(device_id)
return self._active_sessions.get(key)
def get_session_for_device(self, device_id: str) -> Optional[Session]:
"""Get the active session for a specific device.
Args:
device_id: Device ID to get session for
Returns:
Active session for the device or None
"""
return self.get_active_session(device_id)
def get_all_active_sessions(self) -> Dict[str, Session]:
"""Get all active sessions.
Returns:
Dict of device_id -> Session for all active sessions
"""
self._cleanup_expired_sessions()
return dict(self._active_sessions)

View File

@@ -0,0 +1,89 @@
"""UPS driver implementations for different hardware.
Supports multiple UPS types:
- pisugar: PiSugar 2/3 via native I2C (no daemon needed)
- pisugar-daemon: PiSugar via pisugar-server TCP daemon (legacy)
- i2c: Generic I2C fuel gauge (MAX17040/MAX17048)
- auto: Automatically detect available UPS hardware
"""
from typing import Optional, Tuple
from .base import UPSDriver, UPSData
from .pisugar_driver import PiSugarDriver # TCP daemon driver (legacy)
from .pisugar_i2c_driver import PiSugarI2CDriver, PiSugarModel, ButtonEvent
from .i2c_driver import I2CFuelGaugeDriver
async def auto_detect_driver(
pisugar_host: str = "127.0.0.1",
pisugar_port: int = 8423,
prefer_native_i2c: bool = True
) -> Tuple[Optional[UPSDriver], str]:
"""Auto-detect available UPS hardware and return appropriate driver.
Detection order (first match wins):
1. PiSugar via native I2C (preferred - no daemon overhead)
2. PiSugar via TCP daemon (fallback if I2C fails)
3. I2C Fuel Gauge (MAX17040/MAX17048 at 0x36 or other addresses)
Args:
pisugar_host: PiSugar server host for daemon detection (legacy)
pisugar_port: PiSugar server port (legacy)
prefer_native_i2c: If True, prefer native I2C driver over daemon
Returns:
Tuple of (driver_instance or None, detection_message)
"""
print("UPS auto-detect: Starting detection...")
# Try native PiSugar I2C first (no daemon overhead, minimal CPU)
if prefer_native_i2c:
print("UPS auto-detect: Trying PiSugar I2C (native)...")
detected, driver = await PiSugarI2CDriver.detect()
if detected and driver:
model = driver.get_model_name()
print(f"UPS auto-detect: SUCCESS - PiSugar I2C: {model}")
return (driver, f"Detected PiSugar UPS via I2C: {model}")
print("UPS auto-detect: PiSugar I2C not detected")
# Try PiSugar daemon (legacy fallback)
print("UPS auto-detect: Trying PiSugar daemon...")
detected, model = await PiSugarDriver.detect(host=pisugar_host, port=pisugar_port)
if detected:
driver = PiSugarDriver(host=pisugar_host, port=pisugar_port)
print(f"UPS auto-detect: SUCCESS - PiSugar daemon: {model}")
return (driver, f"Detected PiSugar UPS via daemon: {model}")
print("UPS auto-detect: PiSugar daemon not detected")
# Try native I2C again if we skipped it earlier
if not prefer_native_i2c:
print("UPS auto-detect: Trying PiSugar I2C (second attempt)...")
detected, driver = await PiSugarI2CDriver.detect()
if detected and driver:
model = driver.get_model_name()
print(f"UPS auto-detect: SUCCESS - PiSugar I2C: {model}")
return (driver, f"Detected PiSugar UPS via I2C: {model}")
# Try generic I2C fuel gauge (exclude PiSugar I2C addresses)
print("UPS auto-detect: Trying generic I2C fuel gauge...")
exclude_addrs = list(PiSugarI2CDriver.KNOWN_ADDRESSES.keys()) + [PiSugarI2CDriver.RTC_ADDRESS]
detected, i2c_addr = await I2CFuelGaugeDriver.detect(exclude_addresses=exclude_addrs)
if detected:
driver = I2CFuelGaugeDriver(i2c_address=i2c_addr)
print(f"UPS auto-detect: SUCCESS - I2C fuel gauge at 0x{i2c_addr:02X}")
return (driver, f"Detected I2C fuel gauge at address 0x{i2c_addr:02X}")
print("UPS auto-detect: No I2C fuel gauge detected")
print("UPS auto-detect: No UPS hardware found")
return (None, "No UPS hardware detected")
__all__ = [
"UPSDriver",
"UPSData",
"PiSugarDriver",
"PiSugarI2CDriver",
"PiSugarModel",
"ButtonEvent",
"I2CFuelGaugeDriver",
"auto_detect_driver",
]

View File

@@ -0,0 +1,60 @@
"""Base class for UPS drivers."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional
@dataclass
class UPSData:
"""Battery data from UPS hardware."""
percentage: float # 0-100%
voltage: float # mV
current: float # A (positive=charging, negative=discharging)
is_charging: bool
temperature: Optional[float] = None # Celsius
time_remaining: Optional[int] = None # Minutes
class UPSDriver(ABC):
"""Abstract base class for UPS hardware drivers."""
@abstractmethod
async def initialize(self) -> bool:
"""Initialize connection to UPS hardware.
Returns:
True if initialization successful, False otherwise
"""
pass
@abstractmethod
async def read_data(self) -> UPSData:
"""Read current battery data from UPS.
Returns:
UPSData object with current readings
"""
pass
@abstractmethod
async def is_available(self) -> bool:
"""Check if UPS hardware is available.
Returns:
True if hardware is accessible, False otherwise
"""
pass
@abstractmethod
def close(self):
"""Close connection to UPS hardware."""
pass
@abstractmethod
def get_model_name(self) -> str:
"""Get the UPS model/type name.
Returns:
Human-readable model name
"""
pass

View File

@@ -0,0 +1,216 @@
"""I2C Fuel Gauge driver for generic UPS HATs.
Supports MAX17040/MAX17048 and similar I2C fuel gauge chips.
"""
import asyncio
from typing import Optional, Tuple, List
try:
from smbus2 import SMBus
except ImportError:
SMBus = None
from .base import UPSDriver, UPSData
class I2CFuelGaugeDriver(UPSDriver):
"""Driver for I2C-based fuel gauge UPS HATs."""
# Known I2C addresses for fuel gauge chips
# Excludes PiSugar addresses (0x57, 0x32) which are handled by PiSugarDriver
FUEL_GAUGE_ADDRESSES = [
0x36, # MAX17040/MAX17048/MAX17050 (most common)
0x55, # BQ27441 (TI fuel gauge)
0x62, # BQ27510 (TI fuel gauge)
0x0B, # Some SBS battery monitors
]
@classmethod
async def detect(cls, i2c_bus: int = 1, exclude_addresses: List[int] = None) -> Tuple[bool, Optional[int]]:
"""Detect if an I2C fuel gauge is available.
Scans known fuel gauge I2C addresses to find hardware.
Args:
i2c_bus: I2C bus number (default: 1)
exclude_addresses: List of addresses to skip (e.g., PiSugar addresses)
Returns:
Tuple of (detected: bool, i2c_address: Optional[int])
"""
if SMBus is None:
print("I2C Fuel Gauge: smbus2 not available")
return (False, None)
exclude = exclude_addresses or []
print(f"I2C Fuel Gauge: Scanning addresses {[hex(a) for a in cls.FUEL_GAUGE_ADDRESSES]}, excluding {[hex(a) for a in exclude]}")
try:
bus = SMBus(i2c_bus)
try:
for addr in cls.FUEL_GAUGE_ADDRESSES:
if addr in exclude:
continue
try:
# Try to read a byte - if device exists, this will succeed
bus.read_byte(addr)
print(f"I2C Fuel Gauge: Found device at 0x{addr:02X}")
# Additional validation: try to read SOC register (0x04)
# MAX17040/MAX17048 should respond to this
try:
data = bus.read_i2c_block_data(addr, 0x04, 2)
print(f"I2C Fuel Gauge: SOC register read OK at 0x{addr:02X}: {data}")
return (True, addr)
except OSError as e:
# Device responded to address but not to register read
# Still likely a fuel gauge, just different protocol
print(f"I2C Fuel Gauge: SOC register read failed at 0x{addr:02X}: {e}")
return (True, addr)
except OSError:
continue
finally:
bus.close()
except Exception as e:
print(f"I2C Fuel Gauge: Detection error: {e}")
print("I2C Fuel Gauge: No device found")
return (False, None)
def __init__(self, i2c_address: int = 0x36, i2c_bus: int = 1):
"""Initialize I2C fuel gauge driver.
Args:
i2c_address: I2C address of fuel gauge chip (default: 0x36)
i2c_bus: I2C bus number (default: 1 for Raspberry Pi)
"""
self._i2c_address = i2c_address
self._i2c_bus = i2c_bus
self._bus: Optional[SMBus] = None
self._available = False
self._critical_threshold = 15.0 # For status determination
async def initialize(self) -> bool:
"""Initialize I2C connection to fuel gauge.
Returns:
True if initialization successful, False otherwise
"""
if SMBus is None:
print("smbus2 library not available")
self._available = False
return False
try:
# Open I2C bus
self._bus = SMBus(self._i2c_bus)
# Try to read from device to verify it exists
await self._test_read()
self._available = True
return True
except Exception as e:
print(f"Failed to initialize I2C fuel gauge: {e}")
self._available = False
self._bus = None
return False
async def read_data(self) -> UPSData:
"""Read current battery data from fuel gauge.
Returns:
UPSData object with current readings
"""
if not self._bus or not self._available:
raise RuntimeError("I2C fuel gauge not initialized")
loop = asyncio.get_event_loop()
# Read voltage (registers 0x02-0x03)
voltage_bytes = await loop.run_in_executor(
None,
self._bus.read_i2c_block_data,
self._i2c_address,
0x02,
2
)
voltage_raw = (voltage_bytes[0] << 8) | voltage_bytes[1]
voltage = (voltage_raw >> 4) * 1.25 # Convert to mV
# Read state of charge (registers 0x04-0x05)
soc_bytes = await loop.run_in_executor(
None,
self._bus.read_i2c_block_data,
self._i2c_address,
0x04,
2
)
soc_raw = (soc_bytes[0] << 8) | soc_bytes[1]
percentage = soc_raw / 256.0
# Estimate current (simple approach, some HATs don't provide this)
current = 0.0
# Determine if charging based on voltage
# Typically voltage > 4.1V means charging
is_charging = voltage > 4100 # 4.1V in mV
return UPSData(
percentage=percentage,
voltage=voltage,
current=current,
is_charging=is_charging,
temperature=None, # Not all fuel gauges provide temperature
time_remaining=None # Would need battery capacity config to calculate
)
async def is_available(self) -> bool:
"""Check if I2C fuel gauge is available.
Returns:
True if hardware is accessible, False otherwise
"""
if not self._available or not self._bus:
# Try to reinitialize
return await self.initialize()
return True
def close(self):
"""Close I2C bus connection."""
if self._bus:
self._bus.close()
self._bus = None
self._available = False
def get_model_name(self) -> str:
"""Get the fuel gauge model name.
Returns:
Human-readable model name
"""
return "I2C Fuel Gauge (MAX17040/MAX17048)"
async def _test_read(self):
"""Test read from device to verify it exists.
Raises:
Exception if device doesn't respond
"""
if not self._bus:
raise RuntimeError("I2C bus not initialized")
loop = asyncio.get_event_loop()
# Try to read version register (0x08)
await loop.run_in_executor(
None,
self._bus.read_i2c_block_data,
self._i2c_address,
0x08,
2
)

View File

@@ -0,0 +1,282 @@
"""PiSugar UPS driver.
Communicates with pisugar-server daemon via TCP socket.
Supports PiSugar 2, PiSugar 2 Pro, PiSugar 3, and PiSugar 3 Plus.
"""
import asyncio
import socket
from typing import Optional, Tuple
from .base import UPSDriver, UPSData
class PiSugarDriver(UPSDriver):
"""Driver for PiSugar UPS devices."""
# Known I2C addresses for PiSugar devices
PISUGAR_I2C_ADDRESSES = [0x57, 0x32] # Battery IC, RTC
@classmethod
async def detect(cls, host: str = "127.0.0.1", port: int = 8423) -> Tuple[bool, Optional[str]]:
"""Detect if PiSugar hardware is available.
Tries multiple detection methods:
1. Check if pisugar-server daemon is responding
2. Scan I2C bus for known PiSugar addresses (fallback)
Args:
host: PiSugar server host
port: PiSugar server port
Returns:
Tuple of (detected: bool, model_name: Optional[str])
"""
# Method 1: Try to connect to pisugar-server daemon
try:
reader, writer = await asyncio.wait_for(
asyncio.open_connection(host, port),
timeout=2.0
)
try:
# Send model query
writer.write(b"get model\n")
await writer.drain()
response = await asyncio.wait_for(
reader.readline(),
timeout=2.0
)
model = response.decode().strip()
if model and "model:" in model.lower():
# Parse "model: PiSugar 3" format
parts = model.split(":", 1)
if len(parts) > 1:
model_name = parts[1].strip()
if model_name and model_name.lower() != "unknown":
return (True, model_name)
finally:
writer.close()
await writer.wait_closed()
except (asyncio.TimeoutError, ConnectionRefusedError, OSError):
pass
# Method 2: Check I2C addresses (requires smbus2)
# NOTE: We only log if hardware is found - PiSugarDriver requires the daemon
# If daemon isn't running, we can't use PiSugarDriver even if hardware exists
i2c_found = False
try:
from smbus2 import SMBus
bus = SMBus(1)
try:
for addr in cls.PISUGAR_I2C_ADDRESSES:
try:
bus.read_byte(addr)
i2c_found = True
break
except OSError:
continue
finally:
bus.close()
except ImportError:
pass
except Exception:
pass
if i2c_found:
# Hardware found but daemon not running - can't use PiSugarDriver
print("PiSugar hardware detected via I2C but pisugar-server daemon not running")
print("Install pisugar-server or start the daemon to enable PiSugar UPS support")
return (False, None)
def __init__(self, host: str = "127.0.0.1", port: int = 8423, timeout: float = 5.0):
"""Initialize PiSugar driver.
Args:
host: PiSugar server host (default: localhost)
port: PiSugar server port (default: 8423)
timeout: Command timeout in seconds (default: 5.0)
"""
self._host = host
self._port = port
self._timeout = timeout
self._model: Optional[str] = None
self._available = False
async def initialize(self) -> bool:
"""Initialize connection to PiSugar daemon.
Returns:
True if initialization successful, False otherwise
"""
try:
# Test connection by getting model
self._model = await self._send_command("get model")
if self._model and self._model != "Unknown":
self._available = True
return True
else:
self._available = False
return False
except Exception as e:
print(f"Failed to initialize PiSugar: {e}")
self._available = False
return False
async def read_data(self) -> UPSData:
"""Read current battery data from PiSugar.
Returns:
UPSData object with current readings
"""
if not self._available:
raise RuntimeError("PiSugar not initialized or not available")
# Execute commands in parallel for efficiency
results = await asyncio.gather(
self._send_command("get battery"),
self._send_command("get battery_v"),
self._send_command("get battery_i"),
self._send_command("get battery_power_plugged"),
return_exceptions=True
)
# Parse results
percentage = self._parse_float(results[0], 0.0)
voltage = self._parse_float(results[1], 0.0)
current = self._parse_float(results[2], 0.0)
is_charging = self._parse_bool(results[3], False)
return UPSData(
percentage=percentage,
voltage=voltage,
current=current,
is_charging=is_charging,
temperature=None, # PiSugar doesn't provide temperature
time_remaining=None # Would need battery capacity config to calculate
)
async def is_available(self) -> bool:
"""Check if PiSugar hardware is available.
Returns:
True if hardware is accessible, False otherwise
"""
if not self._available:
# Try to reinitialize
return await self.initialize()
return True
def close(self):
"""Close connection to PiSugar (stateless, nothing to close)."""
self._available = False
def get_model_name(self) -> str:
"""Get the PiSugar model name.
Returns:
Human-readable model name
"""
return self._model or "PiSugar"
async def _send_command(self, command: str) -> str:
"""Send command to PiSugar server and get response.
Args:
command: Command to send (e.g., "get battery")
Returns:
Response string from server
Raises:
RuntimeError: If connection fails or times out
"""
try:
# Connect to PiSugar server
reader, writer = await asyncio.wait_for(
asyncio.open_connection(self._host, self._port),
timeout=self._timeout
)
try:
# Send command
writer.write(f"{command}\n".encode())
await writer.drain()
# Read response (single line)
response = await asyncio.wait_for(
reader.readline(),
timeout=self._timeout
)
return response.decode().strip()
finally:
writer.close()
await writer.wait_closed()
except asyncio.TimeoutError:
raise RuntimeError(f"PiSugar command timeout: {command}")
except ConnectionRefusedError:
raise RuntimeError("PiSugar server not running (connection refused)")
except Exception as e:
raise RuntimeError(f"PiSugar communication error: {e}")
def _parse_float(self, value, default: float = 0.0) -> float:
"""Parse float value from response.
Args:
value: Response value (could be string, float, or Exception)
default: Default value if parsing fails
Returns:
Parsed float value or default
"""
if isinstance(value, Exception):
return default
try:
# PiSugar responses are often in format "battery: 85.5"
if isinstance(value, str):
# Try to extract number from response
parts = value.split(":")
if len(parts) > 1:
return float(parts[1].strip())
else:
return float(value.strip())
return float(value)
except (ValueError, AttributeError):
return default
def _parse_bool(self, value, default: bool = False) -> bool:
"""Parse boolean value from response.
Args:
value: Response value (could be string, bool, or Exception)
default: Default value if parsing fails
Returns:
Parsed boolean value or default
"""
if isinstance(value, Exception):
return default
try:
if isinstance(value, bool):
return value
if isinstance(value, str):
# PiSugar returns "battery_power_plugged: true" or "false"
parts = value.split(":")
if len(parts) > 1:
return parts[1].strip().lower() == "true"
else:
return value.strip().lower() in ("true", "1", "yes")
return bool(value)
except (ValueError, AttributeError):
return default

View File

@@ -0,0 +1,659 @@
"""Native PiSugar I2C driver - direct hardware communication.
Bypasses pisugar-server daemon entirely for minimal CPU usage.
Supports:
- PiSugar 2 (4-LEDs) - IP5209 chip at I2C address 0x75
- PiSugar 2 Pro - IP5209 chip at I2C address 0x75
- PiSugar 3 / 3 Plus - IP5312 chip at I2C address 0x57
Features:
- Battery voltage, current, and percentage reading
- Power plug/charging detection
- Button tap detection (single, double, long press)
- RTC alarm for scheduled wake-up
- Force shutdown capability
Register information extracted from:
https://github.com/PiSugar/pisugar-power-manager-rs
"""
import asyncio
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Callable, List, Optional, Tuple
try:
from smbus2 import SMBus
except ImportError:
SMBus = None
from .base import UPSDriver, UPSData
class PiSugarModel(Enum):
"""Supported PiSugar models."""
PISUGAR_2 = "PiSugar 2"
PISUGAR_2_PRO = "PiSugar 2 Pro"
PISUGAR_3 = "PiSugar 3"
UNKNOWN = "Unknown PiSugar"
class ButtonEvent(Enum):
"""Button event types."""
SINGLE_TAP = "single"
DOUBLE_TAP = "double"
LONG_PRESS = "long"
@dataclass
class ChipConfig:
"""Configuration for a specific battery management chip."""
i2c_address: int
voltage_reg_low: int
voltage_reg_high: int
current_reg_low: int
current_reg_high: int
power_status_reg: int
power_plugged_mask: int
model: PiSugarModel
# IP5209 chip used in PiSugar 2 series
IP5209_CONFIG = ChipConfig(
i2c_address=0x75,
voltage_reg_low=0xA2,
voltage_reg_high=0xA3,
current_reg_low=0xA4,
current_reg_high=0xA5,
power_status_reg=0x55,
power_plugged_mask=0x10, # Bit 4
model=PiSugarModel.PISUGAR_2,
)
# IP5312 chip used in PiSugar 3 series
IP5312_CONFIG = ChipConfig(
i2c_address=0x57,
voltage_reg_low=0xD0,
voltage_reg_high=0xD1,
current_reg_low=0xD2,
current_reg_high=0xD3,
power_status_reg=0xDD,
power_plugged_mask=0x1F, # Value 0x1F = plugged in
model=PiSugarModel.PISUGAR_3,
)
# Battery voltage to percentage lookup curve (voltage in mV -> percentage)
# Based on typical LiPo discharge curve
BATTERY_CURVE = [
(4160, 100),
(4050, 90),
(3920, 80),
(3800, 70),
(3720, 60),
(3650, 50),
(3580, 40),
(3520, 30),
(3420, 20),
(3300, 10),
(3100, 0),
]
class PiSugarI2CDriver(UPSDriver):
"""Native I2C driver for PiSugar UPS devices.
Reads directly from the IP5209/IP5312 battery management chip,
eliminating the need for the pisugar-server daemon.
"""
# Known I2C addresses for auto-detection
KNOWN_ADDRESSES = {
0x75: IP5209_CONFIG, # PiSugar 2 series
0x57: IP5312_CONFIG, # PiSugar 3 series
}
# RTC address (SD3078) - used for detection but not read
RTC_ADDRESS = 0x32
@classmethod
async def detect(cls, i2c_bus: int = 1, retries: int = 3, retry_delay: float = 0.5) -> Tuple[bool, Optional["PiSugarI2CDriver"]]:
"""Detect PiSugar hardware by probing I2C addresses.
Args:
i2c_bus: I2C bus number (default: 1 for Raspberry Pi)
retries: Number of detection attempts (for early-boot scenarios)
retry_delay: Delay between retries in seconds
Returns:
Tuple of (detected: bool, driver_instance or None)
"""
if SMBus is None:
print("PiSugar I2C: smbus2 not available")
return (False, None)
for attempt in range(retries):
try:
bus = SMBus(i2c_bus)
try:
# Try each known address
for addr, config in cls.KNOWN_ADDRESSES.items():
try:
# Try to read a byte from the address
bus.read_byte(addr)
# Validate by reading voltage registers
try:
low = bus.read_byte_data(addr, config.voltage_reg_low)
high = bus.read_byte_data(addr, config.voltage_reg_high)
# Success - create driver instance
print(f"PiSugar I2C: Found {config.model.value} at 0x{addr:02X} (voltage regs: {low}, {high})")
driver = cls(chip_config=config, i2c_bus=i2c_bus)
return (True, driver)
except OSError as e:
# Address responded but not the expected chip
print(f"PiSugar I2C: 0x{addr:02X} responded but voltage reg read failed: {e}")
continue
except OSError:
# No device at this address
continue
finally:
bus.close()
except Exception as e:
if attempt < retries - 1:
print(f"PiSugar I2C: Detection attempt {attempt + 1} failed ({e}), retrying...")
await asyncio.sleep(retry_delay)
else:
print(f"PiSugar I2C: All detection attempts failed: {e}")
return (False, None)
def __init__(
self,
chip_config: ChipConfig = IP5209_CONFIG,
i2c_bus: int = 1
):
"""Initialize PiSugar I2C driver.
Args:
chip_config: Configuration for the specific chip
i2c_bus: I2C bus number (default: 1)
"""
self._config = chip_config
self._i2c_bus = i2c_bus
self._bus: Optional[SMBus] = None
self._available = False
async def initialize(self) -> bool:
"""Initialize I2C connection.
Returns:
True if initialization successful
"""
if SMBus is None:
print("smbus2 library not available for PiSugar I2C driver")
return False
try:
self._bus = SMBus(self._i2c_bus)
# Verify we can read from the chip
loop = asyncio.get_event_loop()
await loop.run_in_executor(
None,
self._bus.read_byte_data,
self._config.i2c_address,
self._config.voltage_reg_low
)
self._available = True
return True
except Exception as e:
print(f"Failed to initialize PiSugar I2C: {e}")
self._available = False
if self._bus:
self._bus.close()
self._bus = None
return False
async def read_data(self) -> UPSData:
"""Read battery data directly from I2C.
Returns:
UPSData with current readings
"""
if not self._bus or not self._available:
raise RuntimeError("PiSugar I2C not initialized")
loop = asyncio.get_event_loop()
# Read voltage
voltage = await self._read_voltage(loop)
# Read current
current = await self._read_current(loop)
# Read power status
is_charging = await self._read_power_status(loop)
# Convert voltage to percentage using lookup curve
percentage = self._voltage_to_percentage(voltage)
return UPSData(
percentage=percentage,
voltage=voltage,
current=current,
is_charging=is_charging,
temperature=None,
time_remaining=None
)
async def _read_voltage(self, loop) -> float:
"""Read battery voltage in mV."""
low = await loop.run_in_executor(
None,
self._bus.read_byte_data,
self._config.i2c_address,
self._config.voltage_reg_low
)
high = await loop.run_in_executor(
None,
self._bus.read_byte_data,
self._config.i2c_address,
self._config.voltage_reg_high
)
if self._config.i2c_address == 0x75: # IP5209
# Two's complement with sign bit at 0x20
raw = ((high & 0x1F) << 8) | low
if high & 0x20:
voltage = 2600.0 - (raw * 0.26855)
else:
voltage = 2600.0 + (raw * 0.26855)
else: # IP5312
raw = ((high & 0x3F) << 8) | low
voltage = (raw * 0.26855) + 2600.0
return voltage
async def _read_current(self, loop) -> float:
"""Read battery current in Amps.
Returns:
Current in Amps (positive = charging, negative = discharging)
"""
low = await loop.run_in_executor(
None,
self._bus.read_byte_data,
self._config.i2c_address,
self._config.current_reg_low
)
high = await loop.run_in_executor(
None,
self._bus.read_byte_data,
self._config.i2c_address,
self._config.current_reg_high
)
if self._config.i2c_address == 0x75: # IP5209
if high & 0x20:
# Sign bit set = discharging = negative current
# Sign extend for proper 2's complement
raw_signed = (((high | 0xC0) << 8) | low)
# Convert to signed 16-bit
if raw_signed > 32767:
raw_signed -= 65536
current = raw_signed * 0.745985 / 1000.0 # Result in A
else:
# Sign bit clear = charging = positive current
raw = ((high & 0x1F) << 8) | low
current = raw * 0.745985 / 1000.0 # Result in A
else: # IP5312
raw = ((high & 0x1F) << 8) | low
current = raw * 2.68554 / 1000.0 # Result in A
if high & 0x20:
current = -current # Sign bit = discharging
return current
async def _read_power_status(self, loop) -> bool:
"""Read power plugged/charging status."""
status = await loop.run_in_executor(
None,
self._bus.read_byte_data,
self._config.i2c_address,
self._config.power_status_reg
)
if self._config.i2c_address == 0x75: # IP5209
return bool(status & self._config.power_plugged_mask)
else: # IP5312
# For IP5312, 0x1F means plugged in
return status == self._config.power_plugged_mask
def _voltage_to_percentage(self, voltage_mv: float) -> float:
"""Convert voltage to battery percentage using lookup curve."""
if voltage_mv >= BATTERY_CURVE[0][0]:
return 100.0
if voltage_mv <= BATTERY_CURVE[-1][0]:
return 0.0
# Linear interpolation between curve points
for i in range(len(BATTERY_CURVE) - 1):
v_high, p_high = BATTERY_CURVE[i]
v_low, p_low = BATTERY_CURVE[i + 1]
if v_low <= voltage_mv <= v_high:
# Interpolate
ratio = (voltage_mv - v_low) / (v_high - v_low)
return p_low + ratio * (p_high - p_low)
return 50.0 # Fallback
async def is_available(self) -> bool:
"""Check if hardware is available."""
if not self._available:
return await self.initialize()
return True
def close(self):
"""Close I2C bus."""
if self._bus:
self._bus.close()
self._bus = None
self._available = False
def get_model_name(self) -> str:
"""Get detected model name."""
return self._config.model.value
# ========== Button Detection ==========
async def read_button_state(self) -> bool:
"""Read current button GPIO state.
Returns:
True if button is pressed
"""
if not self._bus or not self._available:
return False
loop = asyncio.get_event_loop()
try:
status = await loop.run_in_executor(
None,
self._bus.read_byte_data,
self._config.i2c_address,
0x55 # GPIO status register
)
if self._config.i2c_address == 0x75: # IP5209
# 4-LED models use GPIO4 (bit 4), 2-LED use GPIO1 (bit 1)
# Default to 4-LED behavior
return bool(status & 0x10)
else: # IP5312
return bool(status & 0x10)
except Exception:
return False
# ========== RTC Functions (SD3078 at 0x32) ==========
async def get_rtc_time(self) -> Optional[datetime]:
"""Read current time from RTC.
Returns:
datetime object or None if RTC not available
"""
if not self._bus:
return None
loop = asyncio.get_event_loop()
try:
# Read 7 bytes starting from register 0x00
data = await loop.run_in_executor(
None,
self._bus.read_i2c_block_data,
self.RTC_ADDRESS,
0x00,
7
)
# Parse BCD format: sec, min, hour, weekday, day, month, year
second = self._bcd_to_int(data[0] & 0x7F)
minute = self._bcd_to_int(data[1] & 0x7F)
hour = self._bcd_to_int(data[2] & 0x3F) # 24-hour format
day = self._bcd_to_int(data[4] & 0x3F)
month = self._bcd_to_int(data[5] & 0x1F)
year = 2000 + self._bcd_to_int(data[6])
return datetime(year, month, day, hour, minute, second)
except Exception:
return None
async def set_rtc_time(self, dt: datetime) -> bool:
"""Set RTC time.
Args:
dt: datetime to set
Returns:
True if successful
"""
if not self._bus:
return False
loop = asyncio.get_event_loop()
try:
# Enable write mode (CTR2 register 0x10, set WRTC1/WRTC2/WRTC3)
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x10,
0x80 # Enable write
)
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x0F,
0x84 # Enable write
)
# Write time data in BCD format
data = [
self._int_to_bcd(dt.second),
self._int_to_bcd(dt.minute),
self._int_to_bcd(dt.hour) | 0x80, # 24-hour mode
self._int_to_bcd(dt.weekday()),
self._int_to_bcd(dt.day),
self._int_to_bcd(dt.month),
self._int_to_bcd(dt.year % 100)
]
await loop.run_in_executor(
None,
self._bus.write_i2c_block_data,
self.RTC_ADDRESS,
0x00,
data
)
# Disable write mode
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x0F,
0x00
)
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x10,
0x00
)
return True
except Exception:
return False
async def set_wake_alarm(self, wake_time: datetime, repeat_weekdays: int = 0) -> bool:
"""Set RTC alarm for scheduled wake-up.
Args:
wake_time: Time to wake up
repeat_weekdays: Bitmask for weekday repeat (0=one-time, 0x7F=daily)
Returns:
True if successful
"""
if not self._bus:
return False
loop = asyncio.get_event_loop()
try:
# Enable write mode
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x10,
0x80
)
# Write alarm time (registers 0x07-0x0D)
alarm_data = [
self._int_to_bcd(wake_time.second),
self._int_to_bcd(wake_time.minute),
self._int_to_bcd(wake_time.hour) | 0x80, # 24-hour mode
repeat_weekdays, # Weekday repeat mask
self._int_to_bcd(wake_time.day),
self._int_to_bcd(wake_time.month),
self._int_to_bcd(wake_time.year % 100)
]
await loop.run_in_executor(
None,
self._bus.write_i2c_block_data,
self.RTC_ADDRESS,
0x07,
alarm_data
)
# Enable alarm (CTR2 register 0x10, set INTAE bit)
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x0E,
0x07 # Enable hour/minute/second alarm match
)
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x10,
0x04 # Enable alarm interrupt
)
# Set frequency for auto power-on
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x11,
0x01 # 1/2Hz for auto power-on
)
return True
except Exception:
return False
async def clear_wake_alarm(self) -> bool:
"""Clear/disable wake alarm.
Returns:
True if successful
"""
if not self._bus:
return False
loop = asyncio.get_event_loop()
try:
# Disable alarm interrupt
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x10,
0x00
)
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self.RTC_ADDRESS,
0x0E,
0x00
)
return True
except Exception:
return False
# ========== Power Control ==========
async def force_shutdown(self) -> bool:
"""Force immediate shutdown of the Pi.
This enables light-load auto-shutdown on the IP5209/IP5312
which will cut power when the Pi draws minimal current.
Returns:
True if command was sent
"""
if not self._bus or not self._available:
return False
loop = asyncio.get_event_loop()
try:
if self._config.i2c_address == 0x75: # IP5209
# Enable light-load auto-shutdown and force shutdown
# Register 0x01, set appropriate bits
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self._config.i2c_address,
0x01,
0x29 # Enable auto-shutdown
)
else: # IP5312
# IP5312 has different shutdown mechanism
await loop.run_in_executor(
None,
self._bus.write_byte_data,
self._config.i2c_address,
0x03,
0x08 # Force shutdown
)
return True
except Exception:
return False
# ========== Helpers ==========
def _bcd_to_int(self, bcd: int) -> int:
"""Convert BCD byte to integer."""
return (bcd >> 4) * 10 + (bcd & 0x0F)
def _int_to_bcd(self, value: int) -> int:
"""Convert integer to BCD byte."""
return ((value // 10) << 4) | (value % 10)

View File

@@ -1,7 +1,11 @@
"""UPS Manager for Dangerous Pi.
Handles I2C battery monitoring, safe shutdown triggers,
and battery percentage reporting for UPS HAT devices.
Handles battery monitoring, safe shutdown triggers,
and battery percentage reporting for various UPS HAT devices.
Supports multiple UPS types via driver architecture:
- PiSugar (PiSugar 2/3 series via daemon)
- I2C Fuel Gauge (MAX17040/MAX17048)
"""
import asyncio
import subprocess
@@ -9,12 +13,9 @@ from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Optional, Dict, Any
try:
from smbus2 import SMBus
except ImportError:
SMBus = None # Mock for development environments
from .. import config
from .ups_drivers import UPSDriver, PiSugarDriver, I2CFuelGaugeDriver, auto_detect_driver
class BatteryStatus(str, Enum):
@@ -51,11 +52,14 @@ class UPSStatus:
class UPSManager:
"""Manages UPS battery monitoring and safe shutdown."""
def __init__(self):
"""Initialize the UPS manager."""
self._i2c_address = int(config.UPS_I2C_ADDRESS, 16)
def __init__(self, driver: Optional[UPSDriver] = None):
"""Initialize the UPS manager.
Args:
driver: UPS driver instance. If None, creates driver based on config.
"""
self._check_interval = config.UPS_CHECK_INTERVAL
self._bus: Optional[SMBus] = None
self._driver = driver or self._create_driver()
self._status = UPSStatus(
battery_percentage=0.0,
voltage=0.0,
@@ -67,30 +71,91 @@ class UPSManager:
self._shutdown_threshold = 10.0 # Shutdown at 10% battery
self._warning_threshold = 20.0 # Warning at 20% battery
self._critical_threshold = 15.0 # Critical at 15% battery
self._battery_capacity_mah = 1200 # Default for PiSugar 2 (1200mAh)
self._shutdown_initiated = False
self._config_warning_sent = False # Only send config warning once
self._event_callbacks = []
async def initialize(self) -> bool:
"""Initialize I2C connection to UPS.
def _create_driver(self) -> Optional[UPSDriver]:
"""Create UPS driver based on configuration.
Returns:
Appropriate UPS driver instance, or None for auto/none types
"""
ups_type = config.UPS_TYPE.lower()
if ups_type == "pisugar":
return PiSugarDriver(
host=config.UPS_PISUGAR_HOST,
port=config.UPS_PISUGAR_PORT
)
elif ups_type == "i2c":
i2c_address = int(config.UPS_I2C_ADDRESS, 16)
return I2CFuelGaugeDriver(i2c_address=i2c_address)
elif ups_type == "auto":
# Auto-detection happens in initialize()
return None
elif ups_type == "none":
# No UPS configured
return None
else:
# Default to auto-detection for unknown types
print(f"Unknown UPS type '{ups_type}', will auto-detect")
return None
async def initialize(self, startup_delay: float = 1.0) -> bool:
"""Initialize connection to UPS hardware.
Args:
startup_delay: Delay before detection to allow I2C bus to settle
Returns:
True if initialization successful, False otherwise
"""
if SMBus is None:
self._status.is_available = False
self._status.error_message = "smbus2 library not available"
return False
try:
# Try to open I2C bus (usually bus 1 on Raspberry Pi)
self._bus = SMBus(1)
# If no driver set, try auto-detection (for "auto" or unknown types)
if self._driver is None:
ups_type = config.UPS_TYPE.lower()
# Try to read from the device to verify it exists
await self._read_battery_data()
if ups_type == "none":
# Explicitly disabled
print("UPS disabled by configuration (UPS_TYPE=none)")
self._status.is_available = False
self._status.error_message = "UPS disabled"
return False
self._status.is_available = True
self._status.error_message = None
return True
# Small delay to ensure I2C bus is ready after boot
if startup_delay > 0:
await asyncio.sleep(startup_delay)
# Run auto-detection
print("Auto-detecting UPS hardware...")
driver, message = await auto_detect_driver(
pisugar_host=config.UPS_PISUGAR_HOST,
pisugar_port=config.UPS_PISUGAR_PORT
)
if driver:
self._driver = driver
print(message)
else:
print(message)
self._status.is_available = False
self._status.error_message = message
return False
# Initialize the driver
success = await self._driver.initialize()
if success:
self._status.is_available = True
self._status.error_message = None
print(f"UPS initialized: {self._driver.get_model_name()}")
else:
self._status.is_available = False
self._status.error_message = f"Failed to initialize {self._driver.get_model_name()}"
return success
except Exception as e:
self._status.is_available = False
@@ -125,6 +190,116 @@ class UPSManager:
await self._update_battery_status()
return self._status
def get_power_restrictions(self) -> Dict[str, Any]:
"""Get current power restrictions based on hardware state.
Returns:
Dict with restriction info including:
- restricted: bool - Whether operations are restricted
- reason: Optional[str] - Why operations are restricted
- power_source: str - Current power source
- ups_available: bool - Whether UPS hardware is present
- battery_percentage: Optional[float] - Current battery level
- allow_firmware_flash: bool - Can flash firmware (fullimage)
- allow_bootloader_flash: bool - Can flash bootloader
- allow_intensive_operations: bool - Can run intensive ops
- message: Optional[str] - User-friendly message
- warning: Optional[str] - Warning message
- shutdown_imminent: Optional[bool] - Shutdown about to happen
"""
# UPS not available = assume AC power, no restrictions
if not self._status.is_available:
return {
"restricted": False,
"reason": None,
"power_source": "assumed_ac",
"ups_available": False,
"battery_percentage": None,
"allow_firmware_flash": True,
"allow_bootloader_flash": True,
"allow_intensive_operations": True,
"message": "UPS not detected. Assuming stable AC power. Ensure power stability before firmware operations."
}
# UPS available - check power source and battery state
if self._status.power_source == PowerSource.AC:
return {
"restricted": False,
"reason": None,
"power_source": "ac",
"ups_available": True,
"battery_percentage": self._status.battery_percentage,
"allow_firmware_flash": True,
"allow_bootloader_flash": True,
"allow_intensive_operations": True,
"message": "On AC power. All operations allowed."
}
# On battery power - apply restrictions based on battery level
battery_pct = self._status.battery_percentage
if battery_pct >= 80:
return {
"restricted": False,
"reason": None,
"power_source": "battery",
"ups_available": True,
"battery_percentage": battery_pct,
"allow_firmware_flash": True,
"allow_bootloader_flash": True,
"allow_intensive_operations": True,
"warning": "On battery power. Bootloader flashing not recommended below 80%."
}
elif battery_pct >= 50:
return {
"restricted": True,
"reason": "Battery level below 80%",
"power_source": "battery",
"ups_available": True,
"battery_percentage": battery_pct,
"allow_firmware_flash": True, # Fullimage only
"allow_bootloader_flash": False,
"allow_intensive_operations": True,
"message": "Bootloader flashing disabled. Battery too low (minimum 80% required)."
}
elif battery_pct >= 20:
return {
"restricted": True,
"reason": "Battery level below 50%",
"power_source": "battery",
"ups_available": True,
"battery_percentage": battery_pct,
"allow_firmware_flash": False,
"allow_bootloader_flash": False,
"allow_intensive_operations": True,
"message": "Firmware flashing disabled. Battery too low (minimum 50% required)."
}
elif battery_pct >= 10:
return {
"restricted": True,
"reason": "Battery critically low",
"power_source": "battery",
"ups_available": True,
"battery_percentage": battery_pct,
"allow_firmware_flash": False,
"allow_bootloader_flash": False,
"allow_intensive_operations": False,
"message": "Critical battery level. Read-only mode active."
}
else:
return {
"restricted": True,
"reason": "Battery emergency level",
"power_source": "battery",
"ups_available": True,
"battery_percentage": battery_pct,
"allow_firmware_flash": False,
"allow_bootloader_flash": False,
"allow_intensive_operations": False,
"message": "Emergency battery level. System will shutdown soon.",
"shutdown_imminent": True
}
async def shutdown_device(self, delay: int = 30):
"""Initiate safe shutdown of the device.
@@ -161,21 +336,64 @@ class UPSManager:
self._event_callbacks.append(callback)
async def _update_battery_status(self):
"""Update battery status from I2C device."""
if not self._bus or not self._status.is_available:
"""Update battery status from UPS hardware."""
if not self._status.is_available:
return
try:
data = await self._read_battery_data()
# Read data from driver
data = await self._driver.read_data()
# Check for misconfigured UPS (all values are zero) - only notify once
if data.percentage == 0.0 and data.voltage == 0.0 and data.current == 0.0:
if not self._config_warning_sent:
self._config_warning_sent = True
model_name = self._driver.get_model_name() if self._driver else "Unknown"
await self._trigger_event("ups_config_required", {
"model": model_name,
"message": f"UPS '{model_name}' detected but returning no data. May need reconfiguration.",
"hint": "Run 'sudo dpkg-reconfigure pisugar-server' to select the correct PiSugar model."
})
else:
# Reset flag when we get valid data
self._config_warning_sent = False
# Update status with new data
self._status.battery_percentage = data['percentage']
self._status.voltage = data['voltage']
self._status.current = data['current']
self._status.power_source = data['power_source']
self._status.battery_status = data['battery_status']
self._status.time_remaining = data.get('time_remaining')
self._status.temperature = data.get('temperature')
self._status.battery_percentage = data.percentage
self._status.voltage = data.voltage
self._status.current = data.current
self._status.temperature = data.temperature
# Calculate time_remaining if not provided by driver
if data.time_remaining is not None:
self._status.time_remaining = data.time_remaining
elif data.current < 0 and data.percentage > 0:
# Discharging - estimate time remaining
# current is in Amps (negative when discharging)
draw_ma = abs(data.current * 1000)
if draw_ma > 10: # Only calculate if meaningful draw
remaining_mah = self._battery_capacity_mah * (data.percentage / 100)
hours_remaining = remaining_mah / draw_ma
self._status.time_remaining = int(hours_remaining * 60) # Minutes
else:
self._status.time_remaining = None
else:
self._status.time_remaining = None
# Determine power source and battery status from driver data
if data.is_charging:
self._status.power_source = PowerSource.AC
if data.percentage >= 99.0:
self._status.battery_status = BatteryStatus.FULL
else:
self._status.battery_status = BatteryStatus.CHARGING
else:
self._status.power_source = PowerSource.BATTERY
if data.percentage < self._critical_threshold:
self._status.battery_status = BatteryStatus.CRITICAL
else:
self._status.battery_status = BatteryStatus.DISCHARGING
self._status.last_updated = datetime.utcnow().isoformat()
self._status.error_message = None
@@ -183,78 +401,6 @@ class UPSManager:
print(f"Error reading battery data: {e}")
self._status.error_message = str(e)
async def _read_battery_data(self) -> Dict[str, Any]:
"""Read battery data from I2C device.
This implementation is for MAX17040/MAX17048 fuel gauge.
Adjust register addresses for different UPS HAT models.
Returns:
Dictionary with battery data
"""
if not self._bus:
raise RuntimeError("I2C bus not initialized")
# Run I2C read in thread pool to avoid blocking
loop = asyncio.get_event_loop()
# Read voltage (registers 0x02-0x03)
voltage_bytes = await loop.run_in_executor(
None,
self._bus.read_i2c_block_data,
self._i2c_address,
0x02,
2
)
voltage_raw = (voltage_bytes[0] << 8) | voltage_bytes[1]
voltage = (voltage_raw >> 4) * 1.25 # mV
# Read state of charge (registers 0x04-0x05)
soc_bytes = await loop.run_in_executor(
None,
self._bus.read_i2c_block_data,
self._i2c_address,
0x04,
2
)
soc_raw = (soc_bytes[0] << 8) | soc_bytes[1]
percentage = soc_raw / 256.0
# Estimate current based on voltage change
# This is a simple estimation; adjust based on your UPS HAT
current = 0.0 # Some UPS HATs don't provide current readings
# Determine power source and battery status
# Typically voltage > 4.1V means charging
if voltage > 4100: # 4.1V in mV
power_source = PowerSource.AC
if percentage >= 99.0:
battery_status = BatteryStatus.FULL
else:
battery_status = BatteryStatus.CHARGING
else:
power_source = PowerSource.BATTERY
if percentage < self._critical_threshold:
battery_status = BatteryStatus.CRITICAL
else:
battery_status = BatteryStatus.DISCHARGING
# Estimate time remaining (simplified)
time_remaining = None
if power_source == PowerSource.BATTERY and current > 0:
# Rough estimation: battery_mah * (percentage/100) / current_ma
# This would need actual battery capacity from config
pass
return {
'percentage': percentage,
'voltage': voltage,
'current': current,
'power_source': power_source,
'battery_status': battery_status,
'time_remaining': time_remaining,
'temperature': None # Not all UPS HATs provide temperature
}
async def _check_battery_thresholds(self):
"""Check battery levels and trigger actions."""
@@ -327,10 +473,9 @@ class UPSManager:
self._warning_threshold = threshold
def close(self):
"""Close I2C bus connection."""
if self._bus:
self._bus.close()
self._bus = None
"""Close UPS driver connection."""
if self._driver:
self._driver.close()
# Global UPS manager instance

View File

@@ -1,5 +1,6 @@
"""WiFi manager for network configuration and mode switching."""
import asyncio
import logging
import re
import subprocess
from dataclasses import dataclass
@@ -9,6 +10,12 @@ from pathlib import Path
from .. import config
logger = logging.getLogger(__name__)
# Persistent storage for WiFi mode
WIFI_MODE_FILE = Path("/opt/dangerous-pi/data/wifi_mode")
WIFI_DATA_DIR = Path("/opt/dangerous-pi/data")
class WiFiMode(str, Enum):
"""WiFi operation modes."""
@@ -29,6 +36,7 @@ class WiFiInterface:
connected: bool
ssid: Optional[str] = None
ip_address: Optional[str] = None
mode: str = "managed" # "AP" or "managed" (client)
@dataclass
@@ -62,6 +70,68 @@ class WiFiManager:
self._current_mode = WiFiMode.AUTO
self._interfaces: List[WiFiInterface] = []
self._supports_dual = False
self._startup_applied = False
def _save_mode(self, mode: WiFiMode) -> bool:
"""Save WiFi mode to persistent storage.
Args:
mode: WiFi mode to save
Returns:
True if saved successfully
"""
try:
# Ensure data directory exists
WIFI_DATA_DIR.mkdir(parents=True, exist_ok=True)
# Write mode to file
WIFI_MODE_FILE.write_text(mode.value)
logger.info(f"WiFi mode saved: {mode.value}")
return True
except Exception as e:
logger.error(f"Failed to save WiFi mode: {e}")
return False
def _load_mode(self) -> Optional[WiFiMode]:
"""Load WiFi mode from persistent storage.
Returns:
Saved WiFi mode or None if not found
"""
try:
if WIFI_MODE_FILE.exists():
mode_str = WIFI_MODE_FILE.read_text().strip()
mode = WiFiMode(mode_str)
logger.info(f"WiFi mode loaded: {mode.value}")
return mode
except Exception as e:
logger.warning(f"Failed to load WiFi mode: {e}")
return None
async def apply_saved_mode(self) -> bool:
"""Apply the saved WiFi mode on startup.
This should be called once during service startup to restore
the previously configured WiFi mode.
Returns:
True if mode was applied successfully
"""
if self._startup_applied:
logger.debug("Saved mode already applied, skipping")
return True
saved_mode = self._load_mode()
if saved_mode:
logger.info(f"Applying saved WiFi mode: {saved_mode.value}")
success = await self.set_mode(saved_mode, persist=False) # Don't re-save
self._startup_applied = True
return success
else:
logger.info("No saved WiFi mode found, using default (AUTO)")
self._startup_applied = True
return True
async def detect_interfaces(self) -> List[WiFiInterface]:
"""Detect available WiFi interfaces.
@@ -79,6 +149,15 @@ class WiFiManager:
return interfaces
# Parse iw dev output
# Example output:
# phy#0
# Interface wlan0
# ifindex 2
# wdev 0x1
# addr 2c:cf:67:87:db:13
# ssid Dangerous-Pi
# type AP
# channel 6 (2437 MHz), width: 20 MHz
current_interface = None
for line in result.split('\n'):
line = line.strip()
@@ -95,7 +174,8 @@ class WiFiManager:
'is_up': False,
'connected': False,
'ssid': None,
'ip_address': None
'ip_address': None,
'mode': 'managed' # Default to managed (client) mode
}
elif current_interface and line.startswith('addr '):
@@ -103,7 +183,14 @@ class WiFiManager:
elif current_interface and line.startswith('ssid '):
current_interface['ssid'] = ' '.join(line.split()[1:])
current_interface['connected'] = True
elif current_interface and line.startswith('type '):
# Parse interface type: "AP" or "managed"
iface_type = line.split()[1]
current_interface['mode'] = iface_type
# Only mark as "connected" if in managed (client) mode with SSID
if iface_type == 'managed' and current_interface.get('ssid'):
current_interface['connected'] = True
if current_interface:
interfaces.append(current_interface)
@@ -117,8 +204,9 @@ class WiFiManager:
if iface_dict['is_up']:
iface_dict['ip_address'] = await self._get_interface_ip(iface_dict['name'])
# Create WiFiInterface object
wifi_iface = WiFiInterface(**iface_dict)
# For AP mode, mark connected if we have IP (AP is "active")
if iface_dict['mode'] == 'AP' and iface_dict['ip_address']:
iface_dict['connected'] = True
# Convert dicts to WiFiInterface objects
self._interfaces = [WiFiInterface(**iface) for iface in interfaces]
@@ -206,28 +294,35 @@ class WiFiManager:
ap_ip = None
for iface in self._interfaces:
if iface.connected and iface.ssid:
# Check for AP mode interface
if iface.mode == 'AP':
ap_ip = iface.ip_address
ap_ssid = iface.ssid # SSID from iw dev output
# If no SSID from iw, try hostapd config
if not ap_ssid:
ap_ssid = await self._get_ap_ssid()
# Check for client mode interface that's connected
elif iface.mode == 'managed' and iface.connected and iface.ssid:
client_ssid = iface.ssid
client_ip = iface.ip_address
# Check if running as AP (typically 10.3.141.1)
if iface.ip_address and iface.ip_address.startswith("10.3.141"):
ap_ip = iface.ip_address
# Try to get AP SSID from hostapd
ap_ssid = await self._get_ap_ssid()
# Fallback: try to get AP SSID from hostapd if we detected AP mode
if current_mode == WiFiMode.AP and not ap_ssid:
ap_ssid = await self._get_ap_ssid()
return WiFiStatus(
mode=current_mode,
interfaces=self._interfaces,
current_ssid=client_ssid,
current_ip=client_ip,
ap_ssid=ap_ssid or "raspi-webgui", # Default from existing setup
ap_ip=ap_ip or "10.3.141.1",
ap_ssid=ap_ssid or "Dangerous-Pi", # Default
ap_ip=ap_ip,
supports_dual=self._supports_dual
)
async def _detect_current_mode(self) -> WiFiMode:
"""Detect current WiFi mode.
"""Detect current WiFi mode based on interface types.
Returns:
Current WiFi mode
@@ -235,14 +330,16 @@ class WiFiManager:
if not self._interfaces:
return WiFiMode.OFF
# Check if any interface is in AP mode
has_ap = any(
iface.ip_address and iface.ip_address.startswith("10.3.141")
# Check interface modes from iw dev output
has_ap = any(iface.mode == 'AP' for iface in self._interfaces)
has_client = any(
iface.mode == 'managed' and iface.connected
for iface in self._interfaces
)
# Check if any interface is connected as client
has_client = any(iface.connected for iface in self._interfaces)
# Also check if hostapd is running as backup detection
if not has_ap:
has_ap = await self._is_hostapd_running()
if has_ap and has_client:
return WiFiMode.DUAL
@@ -250,8 +347,25 @@ class WiFiManager:
return WiFiMode.AP
elif has_client:
return WiFiMode.CLIENT
elif any(iface.is_up for iface in self._interfaces):
return WiFiMode.AUTO # Interface up but not in AP or connected
else:
return WiFiMode.AUTO
return WiFiMode.OFF
async def _is_hostapd_running(self) -> bool:
"""Check if hostapd service is running.
Returns:
True if hostapd is active
"""
try:
result = await self._run_command(
"systemctl is-active hostapd",
check=False
)
return result.strip() == "active"
except Exception:
return False
async def _get_ap_ssid(self) -> Optional[str]:
"""Get AP SSID from hostapd config.
@@ -277,6 +391,10 @@ class WiFiManager:
Returns:
List of available networks
"""
# Ensure interfaces are detected
if not self._interfaces:
await self.detect_interfaces()
if not interface:
# Use first non-USB interface, or first available
for iface in self._interfaces:
@@ -292,13 +410,14 @@ class WiFiManager:
try:
# Request scan
await self._run_command(f"sudo iw dev {interface} scan trigger", check=False)
# Note: Requires CAP_NET_ADMIN capability (set via systemd service)
await self._run_command(f"iw dev {interface} scan trigger", check=False)
# Wait for scan to complete
await asyncio.sleep(2)
# Get scan results
result = await self._run_command(f"sudo iw dev {interface} scan")
result = await self._run_command(f"iw dev {interface} scan")
networks = []
current_network = None
@@ -306,11 +425,13 @@ class WiFiManager:
for line in result.split('\n'):
line = line.strip()
if line.startswith('BSS '):
if line.startswith('BSS ') and line.split()[1].count(':') >= 5:
# Match BSS lines with MAC addresses (xx:xx:xx:xx:xx:xx), not "BSS Load:" etc.
if current_network:
networks.append(current_network)
bssid = line.split()[1].rstrip('(')
# Handle format: BSS aa:bb:cc:dd:ee:ff(on wlan0)
bssid = line.split()[1].split('(')[0]
current_network = {
'ssid': '',
'bssid': bssid,
@@ -324,7 +445,8 @@ class WiFiManager:
if line.startswith('SSID: '):
current_network['ssid'] = line[6:]
elif line.startswith('freq: '):
current_network['frequency'] = int(line[6:])
# freq can be "2437" or "2437.0" depending on iw version
current_network['frequency'] = int(float(line[6:]))
elif line.startswith('signal: '):
# Parse signal strength (e.g., "-50.00 dBm")
signal = line[8:].split()[0]
@@ -346,11 +468,12 @@ class WiFiManager:
print(f"Error scanning networks: {e}")
return []
async def set_mode(self, mode: WiFiMode) -> bool:
async def set_mode(self, mode: WiFiMode, persist: bool = True) -> bool:
"""Set WiFi mode.
Args:
mode: Desired WiFi mode
persist: If True, save mode to persistent storage for boot persistence
Returns:
True if mode was set successfully
@@ -371,40 +494,122 @@ class WiFiManager:
await self._enable_auto_mode()
self._current_mode = mode
# Persist mode for boot persistence
if persist:
self._save_mode(mode)
return True
except Exception as e:
print(f"Error setting WiFi mode: {e}")
return False
async def _systemctl(self, action: str, service: str):
"""Control systemd service via dbus (no sudo required with polkit rule).
Args:
action: "start", "stop", or "restart"
service: Service name (e.g., "hostapd.service")
"""
if not service.endswith(".service"):
service = f"{service}.service"
method = {
"start": "StartUnit",
"stop": "StopUnit",
"restart": "RestartUnit"
}.get(action, "StartUnit")
cmd = (
f'busctl call org.freedesktop.systemd1 '
f'/org/freedesktop/systemd1 org.freedesktop.systemd1.Manager '
f'{method} ss "{service}" "replace"'
)
await self._run_command(cmd, check=False)
async def _enable_nm_management(self):
"""Enable NetworkManager to manage wlan0 for client mode.
Uses nmcli to set wlan0 as managed (no file permissions needed).
"""
import logging
logger = logging.getLogger(__name__)
# Check current device status
status = await self._run_command("nmcli device status", check=False)
logger.warning(f"[NM Management] Current status:\n{status}")
# Use nmcli to set device as managed (works without root)
logger.warning("[NM Management] Setting wlan0 as managed...")
result = await self._run_command("nmcli device set wlan0 managed yes", check=False)
logger.warning(f"[NM Management] nmcli set managed result: '{result}'")
# Give NM time to pick up the device
logger.warning("[NM Management] Waiting 2s...")
await asyncio.sleep(2)
# Verify device is now managed
status = await self._run_command("nmcli device status", check=False)
logger.warning(f"[NM Management] Status after:\n{status}")
async def _disable_nm_management(self):
"""Disable NetworkManager management of wlan0 for AP mode.
Uses nmcli to set wlan0 as unmanaged (for hostapd).
"""
import logging
logger = logging.getLogger(__name__)
# Use nmcli to set device as unmanaged
logger.warning("[NM Management] Setting wlan0 as unmanaged...")
result = await self._run_command("nmcli device set wlan0 managed no", check=False)
logger.warning(f"[NM Management] nmcli set unmanaged result: '{result}'")
await asyncio.sleep(1)
async def _enable_ap_mode(self):
"""Enable Access Point mode."""
# Ensure NM doesn't manage wlan0
await self._disable_nm_management()
# Start hostapd and dnsmasq for AP
await self._run_command("sudo systemctl start hostapd")
await self._run_command("sudo systemctl start dnsmasq")
await self._systemctl("start", "hostapd")
await self._systemctl("start", "dnsmasq")
# Set static IP for AP
await self._run_command("ip addr add 192.168.4.1/24 dev wlan0", check=False)
print("AP mode enabled")
async def _enable_client_mode(self):
"""Enable Client mode."""
"""Enable Client mode using NetworkManager."""
import logging
logger = logging.getLogger(__name__)
# Stop AP services
await self._run_command("sudo systemctl stop hostapd", check=False)
await self._run_command("sudo systemctl stop dnsmasq", check=False)
# Start wpa_supplicant
await self._run_command("sudo systemctl start wpa_supplicant")
print("Client mode enabled")
logger.warning("[Client Mode] Stopping hostapd...")
await self._systemctl("stop", "hostapd")
logger.warning("[Client Mode] Stopping dnsmasq...")
await self._systemctl("stop", "dnsmasq")
# Check hostapd status
hostapd_status = await self._run_command("systemctl is-active hostapd", check=False)
logger.warning(f"[Client Mode] hostapd status after stop: {hostapd_status.strip()}")
# Enable NetworkManager to manage wlan0
logger.warning("[Client Mode] Enabling NM management...")
await self._enable_nm_management()
logger.warning("[Client Mode] Client mode enabled")
async def _enable_dual_mode(self):
"""Enable Dual mode (AP + Client)."""
# Enable both AP and client
await self._run_command("sudo systemctl start hostapd")
await self._run_command("sudo systemctl start dnsmasq")
await self._run_command("sudo systemctl start wpa_supplicant")
await self._systemctl("start", "hostapd")
await self._systemctl("start", "dnsmasq")
await self._systemctl("start", "wpa_supplicant")
print("Dual mode enabled")
async def _disable_wifi(self):
"""Disable all WiFi."""
await self._run_command("sudo systemctl stop hostapd", check=False)
await self._run_command("sudo systemctl stop dnsmasq", check=False)
await self._run_command("sudo systemctl stop wpa_supplicant", check=False)
await self._systemctl("stop", "hostapd")
await self._systemctl("stop", "dnsmasq")
await self._systemctl("stop", "wpa_supplicant")
print("WiFi disabled")
async def _enable_auto_mode(self):
@@ -426,19 +631,25 @@ class WiFiManager:
ssid: str,
password: Optional[str] = None,
interface: Optional[str] = None,
hidden: bool = False
hidden: bool = False,
fallback_to_ap: bool = True
) -> bool:
"""Connect to a WiFi network.
"""Connect to a WiFi network using NetworkManager.
Args:
ssid: Network SSID
password: Network password (if encrypted)
interface: Interface to use (default: first available)
hidden: Whether network is hidden
fallback_to_ap: If True, revert to AP mode on connection failure
Returns:
True if connection successful
"""
# Ensure interfaces are detected before trying to connect
if not self._interfaces:
await self.detect_interfaces()
if not interface:
# Use first non-USB interface, or first available
for iface in self._interfaces:
@@ -449,52 +660,79 @@ class WiFiManager:
interface = self._interfaces[0].name
if not interface:
import logging
logger = logging.getLogger(__name__)
logger.warning("[WiFi Connect] No interface found!")
return False
try:
# Add network to wpa_supplicant configuration
config_path = Path("/etc/wpa_supplicant/wpa_supplicant.conf")
import logging
logger = logging.getLogger(__name__)
logger.warning(f"[WiFi Connect] Starting connect to {ssid}")
# Switch to client mode (stops hostapd, enables NM management)
logger.warning("[WiFi Connect] Step 1: Enabling client mode...")
await self._enable_client_mode()
logger.warning("[WiFi Connect] Step 1: Client mode enabled")
# Wait for NM to be ready and detect wlan0
logger.warning("[WiFi Connect] Step 2: Waiting 2s for NM...")
await asyncio.sleep(2)
# Check device status
dev_status = await self._run_command("nmcli device status", check=False)
logger.warning(f"[WiFi Connect] Device status after wait:\n{dev_status}")
# Delete any existing saved connection for this SSID
# (handles corrupted connections with missing key-mgmt property)
ssid_escaped = ssid.replace("'", "'\\''")
logger.warning(f"[WiFi Connect] Step 3: Deleting existing connection for {ssid}...")
del_result = await self._run_command(
f"nmcli connection delete '{ssid_escaped}'",
check=False
)
logger.warning(f"[WiFi Connect] Delete result: {del_result}")
await asyncio.sleep(1)
# Build nmcli connect command
cmd = f"nmcli device wifi connect '{ssid_escaped}'"
# Create network block
if password:
# Encrypted network
network_block = f"""
network={{
ssid="{ssid}"
psk="{password}"
scan_ssid={1 if hidden else 0}
priority=1
}}
"""
else:
# Open network
network_block = f"""
network={{
ssid="{ssid}"
key_mgmt=NONE
scan_ssid={1 if hidden else 0}
priority=1
}}
"""
password_escaped = password.replace("'", "'\\''")
cmd += f" password '{password_escaped}'"
# Append to config (or use wpa_cli)
# Using wpa_cli for immediate connection
await self._add_network_via_wpa_cli(ssid, password, hidden)
if hidden:
cmd += " hidden yes"
# Reconnect wpa_supplicant
await self._run_command(f"sudo wpa_cli -i {interface} reconfigure")
# Attempt connection
logger.warning(f"[WiFi Connect] Step 4: Running nmcli connect...")
result = await self._run_command(cmd, check=False)
logger.warning(f"[WiFi Connect] Connect result: {result}")
# Wait for connection
await asyncio.sleep(3)
# Check if connection was successful
if "successfully activated" in result.lower():
logger.warning(f"[WiFi Connect] SUCCESS - connected to {ssid}")
# Verify connection
result = await self._run_command(f"sudo wpa_cli -i {interface} status")
if f'ssid={ssid}' in result and 'wpa_state=COMPLETED' in result:
print(f"Successfully connected to {ssid}")
return True
else:
print(f"Connection to {ssid} failed")
return False
# Verify we have an IP address
await asyncio.sleep(2)
ip_result = await self._run_command(f"ip addr show {interface}")
logger.warning(f"[WiFi Connect] IP result: {ip_result}")
if "inet " in ip_result and "192.168.4." not in ip_result:
# Save client mode for boot persistence
self._current_mode = WiFiMode.CLIENT
self._save_mode(WiFiMode.CLIENT)
logger.info(f"WiFi client mode saved for boot persistence")
return True
# Connection failed
logger.warning(f"[WiFi Connect] FAILED - {result}")
if fallback_to_ap:
print("Falling back to AP mode...")
await self._enable_ap_mode()
return False
except Exception as e:
print(f"Error connecting to network: {e}")
@@ -532,7 +770,7 @@ network={{
return False
async def disconnect_from_network(self, interface: Optional[str] = None) -> bool:
"""Disconnect from current network.
"""Disconnect from current network and return to AP mode.
Args:
interface: Interface to disconnect (default: first connected)
@@ -550,30 +788,36 @@ network={{
return False
try:
await self._run_command(f"sudo wpa_cli -i {interface} disconnect")
# Disconnect using nmcli
await self._run_command(f"nmcli device disconnect {interface}", check=False)
# Return to AP mode
await self._enable_ap_mode()
return True
except Exception as e:
print(f"Error disconnecting: {e}")
return False
async def get_saved_networks(self) -> List[Dict[str, str]]:
"""Get list of saved networks from wpa_supplicant.
"""Get list of saved WiFi networks from NetworkManager.
Returns:
List of saved networks with SSID and other info
"""
try:
result = await self._run_command("sudo wpa_cli list_networks")
result = await self._run_command(
"nmcli -t -f NAME,TYPE connection show",
check=False
)
networks = []
for line in result.split('\n')[1:]: # Skip header
for line in result.split('\n'):
if line.strip():
parts = line.split('\t')
if len(parts) >= 2:
parts = line.split(':')
if len(parts) >= 2 and parts[1] == '802-11-wireless':
networks.append({
'id': parts[0].strip(),
'ssid': parts[1].strip(),
'enabled': 'CURRENT' in line or 'ENABLED' in line
'ssid': parts[0],
'type': 'wifi',
'enabled': True
})
return networks
@@ -591,23 +835,14 @@ network={{
True if network was forgotten
"""
try:
# Get network ID
networks = await self.get_saved_networks()
network_id = None
# Delete connection using nmcli
ssid_escaped = ssid.replace("'", "'\\''")
result = await self._run_command(
f"nmcli connection delete '{ssid_escaped}'",
check=False
)
for net in networks:
if net['ssid'] == ssid:
network_id = net['id']
break
if network_id is None:
return False
# Remove network
await self._run_command(f"sudo wpa_cli remove_network {network_id}")
await self._run_command("sudo wpa_cli save_config")
return True
return "successfully deleted" in result.lower()
except Exception as e:
print(f"Error forgetting network: {e}")
return False

View File

@@ -10,16 +10,40 @@ async def init_db():
config.DATA_DIR.mkdir(parents=True, exist_ok=True)
async with aiosqlite.connect(config.DATABASE_PATH) as db:
# Sessions table
# Devices table (NEW for multi-device support)
await db.execute("""
CREATE TABLE IF NOT EXISTS devices (
device_id TEXT PRIMARY KEY,
device_path TEXT NOT NULL,
serial_number TEXT,
friendly_name TEXT,
usb_vid TEXT,
usb_pid TEXT,
first_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
firmware_version TEXT,
bootrom_version TEXT,
metadata TEXT,
version_mismatch_ignored BOOLEAN DEFAULT FALSE,
ignored_at TIMESTAMP,
ignored_version TEXT
)
""")
# Sessions table (UPDATED for multi-device support)
await db.execute("""
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT UNIQUE NOT NULL,
device_id TEXT,
device_path TEXT,
client_ip TEXT NOT NULL,
user_agent TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT 1
released_at TIMESTAMP,
is_active BOOLEAN DEFAULT 1,
FOREIGN KEY (device_id) REFERENCES devices(device_id)
)
""")
@@ -56,6 +80,24 @@ async def init_db():
)
""")
# Firmware flash log table (NEW for firmware update tracking)
await db.execute("""
CREATE TABLE IF NOT EXISTS firmware_flash_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id TEXT NOT NULL,
device_path TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
old_version TEXT,
new_version TEXT,
flash_bootrom BOOLEAN DEFAULT FALSE,
success BOOLEAN,
error_message TEXT,
duration_seconds INTEGER,
user_ip TEXT,
FOREIGN KEY (device_id) REFERENCES devices(device_id)
)
""")
await db.commit()

View File

@@ -0,0 +1,35 @@
"""Service layer for Dangerous Pi.
The service layer provides reusable business logic that can be consumed by
multiple interfaces (REST API, BLE GATT, plugins, etc.).
Services handle:
- Business logic and validation
- Session management
- Error handling and formatting
- Cross-cutting concerns
This pattern prevents code duplication across interfaces.
"""
from .pm3_service import PM3Service, PM3ServiceResult, PM3ServiceError
from .system_service import SystemService
from .wifi_service import WiFiService
from .update_service import UpdateService
from .container import ServiceContainer, container
__all__ = [
# PM3 Service
"PM3Service",
"PM3ServiceResult",
"PM3ServiceError",
# Other Services
"SystemService",
"WiFiService",
"UpdateService",
# Service Container
"ServiceContainer",
"container",
]

View File

@@ -0,0 +1,192 @@
"""Service Container for Dependency Injection.
This module provides a singleton container that manages service instances
and their dependencies, ensuring consistent state across all interfaces
(REST API, BLE GATT, plugins, etc.).
"""
from typing import Optional
from ..workers.pm3_worker import PM3Worker, SubprocessPM3Worker
from ..managers.session_manager import SessionManager
from ..managers.wifi_manager import WiFiManager
from ..managers.update_manager import get_update_manager
from ..managers.pm3_device_manager import PM3DeviceManager
from .pm3_service import PM3Service
from .system_service import SystemService
from .wifi_service import WiFiService
from .update_service import UpdateService
class ServiceContainer:
"""Dependency injection container for services.
This container:
- Creates and manages singleton instances of services
- Injects shared dependencies (workers, managers)
- Ensures consistent state across all interfaces
- Provides centralized access to services
Usage:
# In REST API
from app.backend.services.container import container
result = await container.pm3_service.execute_command(...)
# In BLE GATT
from app.backend.services.container import container
result = await container.pm3_service.execute_command(...)
# Both use the same service instance!
"""
_instance: Optional['ServiceContainer'] = None
def __init__(self):
"""Initialize service container with shared dependencies."""
if ServiceContainer._instance is not None:
raise RuntimeError(
"ServiceContainer is a singleton. Use container.get_instance() "
"or import the global 'container' instance."
)
# Create shared worker/manager instances
# These are the low-level components that services will use
# Use PM3Worker with SWIG bindings for better performance
# Falls back to SubprocessPM3Worker if SWIG import fails
try:
self._pm3_worker = PM3Worker() # Try SWIG bindings first
except Exception:
self._pm3_worker = SubprocessPM3Worker() # Fallback to subprocess
self._pm3_device_manager = PM3DeviceManager() # NEW: Multi-device manager
self._session_manager = SessionManager()
self._wifi_manager = WiFiManager()
self._update_manager = get_update_manager()
# Create service instances with injected dependencies
self._pm3_service = PM3Service(
pm3_worker=self._pm3_worker,
session_manager=self._session_manager,
device_manager=self._pm3_device_manager # NEW: Multi-device support
)
self._system_service = SystemService()
self._wifi_service = WiFiService(
wifi_manager=self._wifi_manager
)
self._update_service = UpdateService(
update_manager=self._update_manager
)
# Note: WorkflowService will be added in Phase 5
# self._workflow_service = WorkflowService(
# pm3_service=self._pm3_service
# )
@classmethod
def get_instance(cls) -> 'ServiceContainer':
"""Get the singleton service container instance.
Returns:
ServiceContainer instance
"""
if cls._instance is None:
cls._instance = ServiceContainer()
return cls._instance
@classmethod
def reset_instance(cls):
"""Reset the singleton instance.
This is primarily used for testing purposes.
"""
cls._instance = None
# Service properties (read-only access)
@property
def pm3_service(self) -> PM3Service:
"""Get PM3 service instance.
Returns:
Shared PM3Service instance
"""
return self._pm3_service
@property
def system_service(self) -> SystemService:
"""Get system service instance.
Returns:
Shared SystemService instance
"""
return self._system_service
@property
def wifi_service(self) -> WiFiService:
"""Get WiFi service instance.
Returns:
Shared WiFiService instance
"""
return self._wifi_service
@property
def update_service(self) -> UpdateService:
"""Get update service instance.
Returns:
Shared UpdateService instance
"""
return self._update_service
# Manager/Worker access (for cases where direct access is needed)
@property
def pm3_worker(self) -> PM3Worker:
"""Get PM3 worker instance.
Returns:
Shared PM3Worker instance
"""
return self._pm3_worker
@property
def session_manager(self) -> SessionManager:
"""Get session manager instance.
Returns:
Shared SessionManager instance
"""
return self._session_manager
@property
def wifi_manager(self) -> WiFiManager:
"""Get WiFi manager instance.
Returns:
Shared WiFiManager instance
"""
return self._wifi_manager
@property
def pm3_device_manager(self) -> PM3DeviceManager:
"""Get PM3 device manager instance.
Returns:
Shared PM3DeviceManager instance for multi-device support
"""
return self._pm3_device_manager
# Global singleton instance
# Import this throughout the codebase for consistent service access
container = ServiceContainer.get_instance()
# Convenience exports for common services
__all__ = [
'ServiceContainer',
'container',
]

View File

@@ -0,0 +1,202 @@
"""Hardware service for plugin hardware access.
Provides controlled access to hardware interfaces (I2C, SPI, GPIO, Serial)
with permission checking and logging.
"""
import logging
from typing import Optional, Any
logger = logging.getLogger(__name__)
class HardwareService:
"""Service for controlled hardware access.
Provides safe wrappers for hardware interfaces that:
- Log all access attempts
- Handle import errors gracefully (for non-Pi systems)
- Return None if hardware is unavailable
Permission checking is done by PluginBase before calling these methods.
"""
# Track which plugins have accessed which hardware
_access_log: dict[str, list[str]] = {}
@classmethod
def _log_access(cls, plugin_id: str, hardware_type: str) -> None:
"""Log hardware access for auditing.
Args:
plugin_id: Plugin requesting access
hardware_type: Type of hardware (i2c, gpio, spi, serial)
"""
if plugin_id not in cls._access_log:
cls._access_log[plugin_id] = []
if hardware_type not in cls._access_log[plugin_id]:
cls._access_log[plugin_id].append(hardware_type)
logger.info(f"Plugin '{plugin_id}' accessed {hardware_type}")
@classmethod
def get_access_log(cls) -> dict[str, list[str]]:
"""Get the hardware access log.
Returns:
Dictionary mapping plugin IDs to list of accessed hardware types
"""
return cls._access_log.copy()
@staticmethod
def get_i2c_bus(plugin_id: str, bus: int = 1) -> Optional[Any]:
"""Get I2C bus for a plugin.
Args:
plugin_id: Plugin requesting access (for logging)
bus: I2C bus number (default: 1 for Raspberry Pi)
Returns:
SMBus instance or None if unavailable
"""
HardwareService._log_access(plugin_id, "i2c")
try:
from smbus2 import SMBus
return SMBus(bus)
except ImportError:
logger.warning("smbus2 not available - I2C access disabled")
return None
except Exception as e:
logger.error(f"Failed to open I2C bus {bus}: {e}")
return None
@staticmethod
def get_gpio(plugin_id: str) -> Optional[Any]:
"""Get GPIO access for a plugin.
Returns the RPi.GPIO module if available.
Plugin is responsible for setup/cleanup.
Args:
plugin_id: Plugin requesting access (for logging)
Returns:
GPIO module or None if unavailable
"""
HardwareService._log_access(plugin_id, "gpio")
try:
import RPi.GPIO as GPIO
return GPIO
except ImportError:
# Try gpiozero as fallback
try:
import gpiozero
logger.info("Using gpiozero instead of RPi.GPIO")
return gpiozero
except ImportError:
logger.warning("No GPIO library available (RPi.GPIO or gpiozero)")
return None
except Exception as e:
logger.error(f"Failed to access GPIO: {e}")
return None
@staticmethod
def get_spi(plugin_id: str, bus: int = 0, device: int = 0) -> Optional[Any]:
"""Get SPI device for a plugin.
Args:
plugin_id: Plugin requesting access (for logging)
bus: SPI bus number (default: 0)
device: SPI device/chip select (default: 0)
Returns:
SpiDev instance or None if unavailable
"""
HardwareService._log_access(plugin_id, "spi")
try:
import spidev
spi = spidev.SpiDev()
spi.open(bus, device)
return spi
except ImportError:
logger.warning("spidev not available - SPI access disabled")
return None
except Exception as e:
logger.error(f"Failed to open SPI bus {bus} device {device}: {e}")
return None
@staticmethod
def get_serial(
plugin_id: str,
port: str,
baudrate: int = 9600,
timeout: float = 1.0
) -> Optional[Any]:
"""Get serial port for a plugin.
Args:
plugin_id: Plugin requesting access (for logging)
port: Serial port path (e.g., '/dev/ttyUSB0')
baudrate: Baud rate (default: 9600)
timeout: Read timeout in seconds (default: 1.0)
Returns:
Serial instance or None if unavailable
"""
HardwareService._log_access(plugin_id, "serial")
try:
import serial
return serial.Serial(port, baudrate, timeout=timeout)
except ImportError:
logger.warning("pyserial not available - serial access disabled")
return None
except Exception as e:
logger.error(f"Failed to open serial port {port}: {e}")
return None
@staticmethod
def is_hardware_available(hardware_type: str) -> bool:
"""Check if a hardware type is available on this system.
Args:
hardware_type: One of 'i2c', 'gpio', 'spi', 'serial'
Returns:
True if the hardware library is importable
"""
try:
if hardware_type == "i2c":
from smbus2 import SMBus
return True
elif hardware_type == "gpio":
try:
import RPi.GPIO
return True
except ImportError:
import gpiozero
return True
elif hardware_type == "spi":
import spidev
return True
elif hardware_type == "serial":
import serial
return True
else:
return False
except ImportError:
return False
@staticmethod
def get_available_hardware() -> list[str]:
"""Get list of available hardware types.
Returns:
List of available hardware type names
"""
available = []
for hw_type in ["i2c", "gpio", "spi", "serial"]:
if HardwareService.is_hardware_available(hw_type):
available.append(hw_type)
return available

View File

@@ -0,0 +1,660 @@
"""PM3 Service Layer.
This service encapsulates all PM3-related business logic and is used by
both REST API and BLE GATT handlers to avoid code duplication.
"""
from typing import Optional, Dict, Any, List
from dataclasses import dataclass
from ..workers.pm3_worker import PM3Worker, PM3CommandResult
from ..managers.session_manager import SessionManager
from ..managers.pm3_device_manager import PM3DeviceManager, PM3Device, DeviceStatus
@dataclass
class PM3ServiceError:
"""Error response from PM3 service."""
code: str # "session_locked", "pm3_not_connected", "command_failed"
message: str
details: Optional[str] = None
@dataclass
class PM3ServiceResult:
"""Result from PM3 service operations."""
success: bool
data: Optional[Dict[str, Any]] = None
error: Optional[PM3ServiceError] = None
class PM3Service:
"""PM3 service layer for command execution and status queries.
This service can be used by multiple interfaces:
- REST API (FastAPI endpoints)
- BLE GATT (Bluetooth handlers)
- Plugin system (future)
It encapsulates:
- Session validation
- PM3 command execution
- Session management
- Response formatting
"""
def __init__(
self,
pm3_worker: Optional[PM3Worker] = None,
session_manager: Optional[SessionManager] = None,
device_manager: Optional[PM3DeviceManager] = None
):
"""Initialize PM3 service.
Args:
pm3_worker: PM3 worker instance (legacy, kept for backward compatibility)
session_manager: Session manager instance (creates new if not provided)
device_manager: PM3 device manager for multi-device support (optional)
"""
self.pm3_worker = pm3_worker or PM3Worker() # Legacy single-device support
self.session_manager = session_manager or SessionManager()
self.device_manager = device_manager # Multi-device support (optional)
async def execute_command(
self,
command: str,
session_id: Optional[str] = None,
timeout: Optional[int] = None,
device_id: Optional[str] = None
) -> PM3ServiceResult:
"""Execute a PM3 command with session validation.
This method handles:
1. Session validation
2. Command execution
3. Session activity updates
4. Error handling
Args:
command: PM3 command to execute
session_id: Optional session ID for multi-user support
timeout: Optional command timeout in seconds
device_id: Optional device ID for multi-device support (uses legacy worker if not provided)
Returns:
PM3ServiceResult with success status and data/error
"""
# Determine which worker to use
worker = None
device_path = None
if device_id and self.device_manager:
# Multi-device mode: get device from device manager
device = await self.device_manager.get_device(device_id)
if not device:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_not_found",
message=f"Device {device_id} not found",
details="Device may have been disconnected"
)
)
if not device.worker:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_no_worker",
message=f"Device {device_id} has no worker instance",
details="Device may not be fully initialized"
)
)
worker = device.worker
device_path = device.device_path
else:
# Legacy single-device mode
worker = self.pm3_worker
device_path = self.pm3_worker.device_path
# 1. Validate session (per-device)
if not self.session_manager.can_execute(session_id, device_id):
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="session_locked",
message=f"Another session is active for device {device_id or 'default'}",
details="Please take over the session or wait for it to expire"
)
)
# 2. Check PM3 connection
if not await worker.is_connected():
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="pm3_not_connected",
message="Proxmark3 not connected",
details=f"Device path: {device_path}"
)
)
# 3. Execute command
try:
result = await worker.execute_command(command)
# 4. Update session activity
if session_id:
self.session_manager.update_activity(session_id, device_id)
# 5. Return result
if result.success:
return PM3ServiceResult(
success=True,
data={
"output": result.output,
"command": command,
"session_id": session_id,
"device_id": device_id
}
)
else:
# Include both error message and output for better diagnostics
# PM3 CLI often outputs error details to stdout
error_details = result.error or ""
if result.output:
error_details = f"{error_details}\nOutput: {result.output}" if error_details else result.output
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="command_failed",
message="PM3 command failed",
details=error_details
)
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="execution_error",
message="Command execution error",
details=str(e)
)
)
async def get_status(self, device_id: Optional[str] = None) -> PM3ServiceResult:
"""Get PM3 device status.
Args:
device_id: Optional device ID. If None and device_manager exists, returns all devices.
If None and no device_manager, returns legacy single device status.
Returns:
PM3ServiceResult with connection status, version, etc.
"""
try:
# Multi-device mode: return all devices or specific device
if device_id is None and self.device_manager:
# Return status for all devices
devices = await self.device_manager.get_all_devices()
return PM3ServiceResult(
success=True,
data={
"devices": [
{
"device_id": d.device_id,
"device_path": d.device_path,
"friendly_name": d.friendly_name or d.device_path.split('/')[-1],
"serial_number": d.serial_number,
"connected": d.status == DeviceStatus.CONNECTED,
"in_use": d.status == DeviceStatus.IN_USE,
"status": d.status.value,
"firmware_info": {
"bootrom_version": d.firmware_info.bootrom_version,
"os_version": d.firmware_info.os_version,
"compatible": d.firmware_info.compatible,
},
"last_seen": d.last_seen.isoformat(),
}
for d in devices
]
}
)
elif device_id and self.device_manager:
# Return status for specific device
device = await self.device_manager.get_device(device_id)
if not device:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_not_found",
message=f"Device {device_id} not found"
)
)
return PM3ServiceResult(
success=True,
data={
"device_id": device.device_id,
"device_path": device.device_path,
"friendly_name": device.friendly_name or device.device_path.split('/')[-1],
"serial_number": device.serial_number,
"connected": device.status == DeviceStatus.CONNECTED,
"in_use": device.status == DeviceStatus.IN_USE,
"status": device.status.value,
"firmware_info": {
"bootrom_version": device.firmware_info.bootrom_version,
"os_version": device.firmware_info.os_version,
"compatible": device.firmware_info.compatible,
},
"last_seen": device.last_seen.isoformat(),
}
)
else:
# Legacy single-device mode
is_connected = await self.pm3_worker.is_connected()
version = None
if is_connected:
# Try to get version info
result = await self.pm3_worker.execute_command("hw version")
if result.success:
version = result.output.split("\n")[0] if result.output else None
return PM3ServiceResult(
success=True,
data={
"connected": is_connected,
"device_path": self.pm3_worker.device_path,
"version": version,
"session_active": self.session_manager.has_active_session()
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="status_error",
message="Failed to get PM3 status",
details=str(e)
)
)
async def connect(self) -> PM3ServiceResult:
"""Connect to PM3 device.
Returns:
PM3ServiceResult indicating success/failure
"""
try:
await self.pm3_worker.connect()
return PM3ServiceResult(
success=True,
data={"message": "Connected to Proxmark3"}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="connection_error",
message="Failed to connect to PM3",
details=str(e)
)
)
async def disconnect(self) -> PM3ServiceResult:
"""Disconnect from PM3 device.
Returns:
PM3ServiceResult indicating success/failure
"""
try:
await self.pm3_worker.disconnect()
return PM3ServiceResult(
success=True,
data={"message": "Disconnected from Proxmark3"}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="disconnection_error",
message="Failed to disconnect from PM3",
details=str(e)
)
)
# Session management methods (for both REST and BLE)
async def create_session(
self,
client_ip: str = "unknown",
user_agent: Optional[str] = None,
force_takeover: bool = False,
device_id: Optional[str] = None
) -> PM3ServiceResult:
"""Create a new session for a device.
Args:
client_ip: Client IP address
user_agent: Client user agent string
force_takeover: Whether to forcefully take over existing session
device_id: Device ID to create session for (None for legacy mode)
Returns:
PM3ServiceResult with session_id
"""
success, session_id, error_msg = await self.session_manager.create_session(
client_ip=client_ip,
user_agent=user_agent,
force_takeover=force_takeover,
device_id=device_id
)
if success and session_id:
return PM3ServiceResult(
success=True,
data={"session_id": session_id, "device_id": device_id}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="session_exists",
message=error_msg or "Session already exists",
details="Set force_takeover=true to take over"
)
)
async def release_session(
self,
session_id: str,
device_id: Optional[str] = None
) -> PM3ServiceResult:
"""Release a session.
Args:
session_id: Session ID to release
device_id: Device ID (if known)
Returns:
PM3ServiceResult indicating success
"""
released = await self.session_manager.release_session(session_id, device_id)
if released:
return PM3ServiceResult(
success=True,
data={"message": "Session released"}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="session_not_found",
message="Session not found or already released"
)
)
def get_session_info(self, device_id: Optional[str] = None) -> PM3ServiceResult:
"""Get session information for a device.
Args:
device_id: Device ID to get session for (None for any active session)
Returns:
PM3ServiceResult with session details
"""
session = self.session_manager.get_active_session(device_id)
if session:
return PM3ServiceResult(
success=True,
data={
"session_id": session.session_id,
"device_id": session.device_id,
"client_ip": session.client_ip,
"created_at": session.created_at,
"last_activity": session.last_activity,
}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="session_not_found",
message=f"No active session for device {device_id or 'default'}"
)
)
def get_all_sessions(self) -> PM3ServiceResult:
"""Get all active sessions.
Returns:
PM3ServiceResult with all session details
"""
sessions = self.session_manager.get_all_active_sessions()
return PM3ServiceResult(
success=True,
data={
"sessions": [
{
"session_id": s.session_id,
"device_id": s.device_id,
"client_ip": s.client_ip,
"created_at": s.created_at,
"last_activity": s.last_activity,
}
for s in sessions.values()
]
}
)
# Multi-device management methods
async def list_devices(self) -> PM3ServiceResult:
"""List all discovered PM3 devices.
Returns:
PM3ServiceResult with list of all devices
"""
if not self.device_manager:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_manager_not_available",
message="Device manager not initialized",
details="Multi-device support is not enabled"
)
)
try:
devices = await self.device_manager.get_all_devices()
return PM3ServiceResult(
success=True,
data={
"devices": [device.to_dict() for device in devices]
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="list_devices_error",
message="Failed to list devices",
details=str(e)
)
)
async def get_available_devices(self) -> PM3ServiceResult:
"""Get devices without active sessions (available for use).
Returns:
PM3ServiceResult with list of available devices
"""
if not self.device_manager:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_manager_not_available",
message="Device manager not initialized",
details="Multi-device support is not enabled"
)
)
try:
all_devices = await self.device_manager.get_all_devices()
# Filter for devices that are CONNECTED (not IN_USE or other states)
available_devices = [
device for device in all_devices
if device.status == DeviceStatus.CONNECTED
]
return PM3ServiceResult(
success=True,
data={
"devices": [device.to_dict() for device in available_devices]
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="get_available_devices_error",
message="Failed to get available devices",
details=str(e)
)
)
async def identify_device(
self,
device_id: str,
duration_ms: int = 2000
) -> PM3ServiceResult:
"""Blink LEDs on a device for physical identification.
Args:
device_id: Device ID to identify
duration_ms: Duration to blink LEDs in milliseconds (default: 2000)
Returns:
PM3ServiceResult indicating success
"""
if not self.device_manager:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_manager_not_available",
message="Device manager not initialized",
details="Multi-device support is not enabled"
)
)
try:
# Check if device exists
device = await self.device_manager.get_device(device_id)
if not device:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_not_found",
message=f"Device {device_id} not found"
)
)
# Trigger LED identification
await self.device_manager.identify_device(device_id, duration_ms)
return PM3ServiceResult(
success=True,
data={
"message": f"Device {device_id} identified",
"device_path": device.device_path,
"duration_ms": duration_ms
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="identify_device_error",
message="Failed to identify device",
details=str(e)
)
)
async def flash_firmware(self, device_id: str) -> PM3ServiceResult:
"""Flash firmware to a PM3 device.
Flashes both bootrom and fullimage from bundled firmware files.
Progress is reported via WebSocket notifications.
Args:
device_id: Device ID to flash
Returns:
PM3ServiceResult indicating success/failure with message
"""
if not self.device_manager:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_manager_not_available",
message="Device manager not initialized",
details="Multi-device support is not enabled"
)
)
try:
# Check if device exists
device = await self.device_manager.get_device(device_id)
if not device:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_not_found",
message=f"Device {device_id} not found"
)
)
# Check if device is already flashing
if device.status == DeviceStatus.FLASHING:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="device_busy",
message="Device is already being flashed",
details="Please wait for current flash to complete"
)
)
# Flash firmware
result = await self.device_manager.flash_firmware(device_id)
if result["success"]:
return PM3ServiceResult(
success=True,
data={
"message": result["message"],
"device_id": device_id
}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="flash_failed",
message="Firmware flash failed",
details=result.get("error", "Unknown error")
)
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="flash_error",
message="Failed to flash firmware",
details=str(e)
)
)

View File

@@ -0,0 +1,824 @@
"""System Service Layer.
This service provides system operations (shutdown, restart, info) that can be
consumed by multiple interfaces (REST API, BLE GATT, etc.).
"""
import asyncio
import os
import platform
import psutil
import shutil
from dataclasses import dataclass
from typing import Optional, Dict, Any
from pathlib import Path
from .pm3_service import PM3ServiceError, PM3ServiceResult
@dataclass
class CPUCoreInfo:
"""Per-core CPU information."""
core_id: int
percent: float
online: bool = True # Whether this core is currently online
@dataclass
class PiModelInfo:
"""Raspberry Pi model information."""
model: str # Full model string (e.g., "Raspberry Pi Zero 2 W Rev 1.0")
model_short: str # Short name (e.g., "Pi Zero 2 W")
total_cores: int # Total physical cores
default_active_cores: int # Recommended default active cores
min_cores: int # Minimum cores (always 1)
max_cores: int # Maximum configurable cores
@dataclass
class CPUCoresConfig:
"""CPU cores configuration."""
total_cores: int
online_cores: int
configurable_cores: list # List of core IDs that can be toggled (usually all except 0)
pi_model: Optional[PiModelInfo] = None
@dataclass
class SystemInfo:
"""System information data."""
hostname: str
platform: str
platform_version: str
cpu_count: int
cpu_percent: float
cpu_per_core: list # List of CPUCoreInfo
memory_total: int
memory_used: int
memory_percent: float
disk_total: int
disk_used: int
disk_percent: float
uptime: float
temperature: Optional[float] = None
load_average: Optional[tuple] = None # 1, 5, 15 min load averages
class SystemService:
"""System operations service.
Provides reusable business logic for:
- System information queries
- Shutdown/restart operations
- Service log retrieval
"""
def __init__(self):
"""Initialize system service."""
pass
async def get_info(self) -> PM3ServiceResult:
"""Get system information.
Returns:
PM3ServiceResult with system info (CPU, memory, disk, etc.)
"""
try:
# Get CPU usage (blocking call, run in executor)
loop = asyncio.get_event_loop()
# Get per-core CPU percentages (requires percpu=True)
# First call to initialize, then wait briefly for measurement
await loop.run_in_executor(None, lambda: psutil.cpu_percent(percpu=True))
await asyncio.sleep(0.1) # Brief pause for accurate measurement
cpu_per_core_raw = await loop.run_in_executor(
None,
lambda: psutil.cpu_percent(percpu=True)
)
# Check which cores are online
total_cores = psutil.cpu_count(logical=True) or 1
core_online_status = {}
for i in range(total_cores):
online_file = Path(f"/sys/devices/system/cpu/cpu{i}/online")
if i == 0:
# Core 0 is always online
core_online_status[i] = True
elif online_file.exists():
core_online_status[i] = online_file.read_text().strip() == "1"
else:
# File doesn't exist, core is always on
core_online_status[i] = True
# Build per-core info with online status
cpu_per_core = [
CPUCoreInfo(
core_id=i,
percent=pct if core_online_status.get(i, True) else 0.0,
online=core_online_status.get(i, True)
)
for i, pct in enumerate(cpu_per_core_raw)
]
# Overall CPU percentage
cpu_percent = sum(cpu_per_core_raw) / len(cpu_per_core_raw) if cpu_per_core_raw else 0.0
# Get load average (Unix only)
try:
load_average = os.getloadavg()
except (OSError, AttributeError):
load_average = None
# Get memory info
memory = psutil.virtual_memory()
# Get disk info for root partition
disk = psutil.disk_usage('/')
# Get system uptime
boot_time = psutil.boot_time()
uptime = psutil.time.time() - boot_time
# Try to get CPU temperature (Raspberry Pi specific)
temperature = await self._get_cpu_temperature()
system_info = SystemInfo(
hostname=platform.node(),
platform=platform.system(),
platform_version=platform.release(),
cpu_count=psutil.cpu_count(),
cpu_percent=cpu_percent,
cpu_per_core=cpu_per_core,
memory_total=memory.total,
memory_used=memory.used,
memory_percent=memory.percent,
disk_total=disk.total,
disk_used=disk.used,
disk_percent=disk.percent,
uptime=uptime,
temperature=temperature,
load_average=load_average
)
return PM3ServiceResult(
success=True,
data={
"hostname": system_info.hostname,
"platform": system_info.platform,
"platform_version": system_info.platform_version,
"cpu": {
"count": system_info.cpu_count,
"percent": system_info.cpu_percent,
"temperature": system_info.temperature,
"per_core": [
{"core_id": c.core_id, "percent": c.percent, "online": c.online}
for c in system_info.cpu_per_core
],
"load_average": list(system_info.load_average) if system_info.load_average else None
},
"memory": {
"total": system_info.memory_total,
"used": system_info.memory_used,
"percent": system_info.memory_percent
},
"disk": {
"total": system_info.disk_total,
"used": system_info.disk_used,
"percent": system_info.disk_percent
},
"uptime": system_info.uptime
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="system_info_error",
message="Failed to get system information",
details=str(e)
)
)
async def _get_cpu_temperature(self) -> Optional[float]:
"""Get CPU temperature (Raspberry Pi specific).
Returns:
Temperature in Celsius or None if unavailable
"""
try:
temp_file = Path("/sys/class/thermal/thermal_zone0/temp")
if temp_file.exists():
temp_str = temp_file.read_text().strip()
# Temperature is in millidegrees
return float(temp_str) / 1000.0
except Exception:
pass
return None
async def shutdown(self, delay: int = 0) -> PM3ServiceResult:
"""Initiate system shutdown.
Args:
delay: Delay in seconds before shutdown (default: 0)
Returns:
PM3ServiceResult indicating success/failure
"""
try:
if delay > 0:
# Schedule shutdown
await self._run_command(f"sudo shutdown -h +{delay // 60}")
return PM3ServiceResult(
success=True,
data={
"message": f"Shutdown scheduled in {delay} seconds",
"delay": delay
}
)
else:
# Immediate shutdown
await self._run_command("sudo shutdown -h now")
return PM3ServiceResult(
success=True,
data={"message": "Shutdown initiated"}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="shutdown_error",
message="Failed to initiate shutdown",
details=str(e)
)
)
async def restart(self, delay: int = 0) -> PM3ServiceResult:
"""Initiate system restart.
Args:
delay: Delay in seconds before restart (default: 0)
Returns:
PM3ServiceResult indicating success/failure
"""
try:
if delay > 0:
# Schedule restart
await self._run_command(f"sudo shutdown -r +{delay // 60}")
return PM3ServiceResult(
success=True,
data={
"message": f"Restart scheduled in {delay} seconds",
"delay": delay
}
)
else:
# Immediate restart
await self._run_command("sudo shutdown -r now")
return PM3ServiceResult(
success=True,
data={"message": "Restart initiated"}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="restart_error",
message="Failed to initiate restart",
details=str(e)
)
)
async def cancel_shutdown(self) -> PM3ServiceResult:
"""Cancel a scheduled shutdown or restart.
Returns:
PM3ServiceResult indicating success/failure
"""
try:
await self._run_command("sudo shutdown -c")
return PM3ServiceResult(
success=True,
data={"message": "Shutdown/restart cancelled"}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="cancel_shutdown_error",
message="Failed to cancel shutdown",
details=str(e)
)
)
async def get_logs(
self,
service: str = "dangerous-pi",
lines: int = 100
) -> PM3ServiceResult:
"""Get service logs using journalctl.
Args:
service: Service name to get logs for
lines: Number of lines to retrieve (default: 100)
Returns:
PM3ServiceResult with log content
"""
try:
output = await self._run_command(
f"sudo journalctl -u {service} -n {lines} --no-pager"
)
return PM3ServiceResult(
success=True,
data={
"service": service,
"lines": lines,
"logs": output
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="logs_error",
message=f"Failed to get logs for service '{service}'",
details=str(e)
)
)
async def get_service_status(self, service: str) -> PM3ServiceResult:
"""Get systemd service status.
Args:
service: Service name
Returns:
PM3ServiceResult with service status
"""
try:
output = await self._run_command(
f"sudo systemctl status {service}",
check=False # Don't raise on non-zero exit
)
# Parse status
is_active = "active (running)" in output.lower()
is_enabled = await self._is_service_enabled(service)
return PM3ServiceResult(
success=True,
data={
"service": service,
"active": is_active,
"enabled": is_enabled,
"status": output
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="service_status_error",
message=f"Failed to get status for service '{service}'",
details=str(e)
)
)
async def _is_service_enabled(self, service: str) -> bool:
"""Check if a systemd service is enabled.
Args:
service: Service name
Returns:
True if service is enabled
"""
try:
output = await self._run_command(
f"sudo systemctl is-enabled {service}",
check=False
)
return output.strip() == "enabled"
except Exception:
return False
async def _run_command(
self,
command: str,
check: bool = True
) -> str:
"""Run a shell command asynchronously.
Args:
command: Command to run
check: Raise exception on non-zero exit code
Returns:
Command output
Raises:
RuntimeError: If command fails and check=True
"""
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if check and process.returncode != 0:
raise RuntimeError(
f"Command failed with exit code {process.returncode}: "
f"{stderr.decode()}"
)
return stdout.decode()
# Pi model defaults: maps model substring to (short_name, default_active_cores, physical_cores)
# default_active_cores: recommended cores for thermal/power management
# physical_cores: actual hardware cores regardless of boot config
PI_MODEL_DEFAULTS = {
"Pi Zero 2": ("Pi Zero 2 W", 2, 4), # 4 cores, default to 2 for thermal
"Pi Zero W": ("Pi Zero W", 1, 1), # Single core
"Pi Zero": ("Pi Zero", 1, 1), # Single core
"Pi 4": ("Pi 4", 4, 4),
"Pi 3": ("Pi 3", 4, 4),
"Pi 2": ("Pi 2", 4, 4),
"Pi 5": ("Pi 5", 4, 4),
}
def _get_physical_cores(self) -> int:
"""Get the actual physical core count (not limited by maxcpus).
Reads from /sys/devices/system/cpu/possible to get the full range
of possible CPUs regardless of boot-time restrictions.
Returns:
Physical core count
"""
try:
# /sys/devices/system/cpu/possible contains the full range like "0-3" for 4 cores
possible_file = Path("/sys/devices/system/cpu/possible")
if possible_file.exists():
content = possible_file.read_text().strip()
# Parse "0-3" format to get count of 4
if '-' in content:
start, end = content.split('-')
return int(end) - int(start) + 1
elif content.isdigit():
return int(content) + 1
except Exception:
pass
# Fallback to psutil (may be limited by maxcpus)
return psutil.cpu_count(logical=True) or 1
async def get_pi_model(self) -> PM3ServiceResult:
"""Detect Raspberry Pi model.
Reads from /proc/device-tree/model or /proc/cpuinfo.
Returns:
PM3ServiceResult with PiModelInfo data
"""
try:
model_str = "Unknown"
model_short = "Unknown"
physical_cores = self._get_physical_cores()
total_cores = physical_cores # Use physical cores as total
default_cores = total_cores
# Try device tree first (most reliable)
model_file = Path("/proc/device-tree/model")
if model_file.exists():
model_str = model_file.read_text().strip().rstrip('\x00')
else:
# Fallback to cpuinfo
cpuinfo = Path("/proc/cpuinfo")
if cpuinfo.exists():
for line in cpuinfo.read_text().split('\n'):
if line.startswith("Model"):
model_str = line.split(':')[1].strip()
break
# Determine short name and default/physical cores based on model
for pattern, (short_name, def_cores, phys_cores) in self.PI_MODEL_DEFAULTS.items():
if pattern in model_str:
model_short = short_name
# Use the known physical cores from model defaults if detected
total_cores = max(physical_cores, phys_cores)
default_cores = min(def_cores, total_cores)
break
else:
# Not a known Pi model, use detected physical cores
if "Raspberry" in model_str:
model_short = "Raspberry Pi"
else:
model_short = model_str[:20] if len(model_str) > 20 else model_str
pi_model = PiModelInfo(
model=model_str,
model_short=model_short,
total_cores=total_cores,
default_active_cores=default_cores,
min_cores=1,
max_cores=total_cores
)
return PM3ServiceResult(
success=True,
data={
"model": pi_model.model,
"model_short": pi_model.model_short,
"total_cores": pi_model.total_cores,
"default_active_cores": pi_model.default_active_cores,
"min_cores": pi_model.min_cores,
"max_cores": pi_model.max_cores
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="pi_model_error",
message="Failed to detect Pi model",
details=str(e)
)
)
async def get_cpu_cores_config(self) -> PM3ServiceResult:
"""Get CPU cores configuration.
Returns info about total cores, online cores, configured cores (from cmdline.txt),
and Pi model with defaults.
Returns:
PM3ServiceResult with CPUCoresConfig data
"""
try:
# Get physical core count (not limited by maxcpus)
physical_cores = self._get_physical_cores()
# Get currently online cores (runtime state)
# On Pi, we can use nproc or count from /proc/cpuinfo
try:
import subprocess
result = subprocess.run(
["nproc"],
capture_output=True,
text=True,
timeout=5
)
online_cores = int(result.stdout.strip()) if result.returncode == 0 else physical_cores
except Exception:
online_cores = physical_cores
# Get configured cores from cmdline.txt (boot-time setting)
configured_cores = self._get_configured_maxcpus()
# Use physical cores as total (what the hardware actually has)
total_cores = physical_cores
# Configurable cores are all cores except 0 (which is always on)
configurable_cores = list(range(1, total_cores))
# Get Pi model info
model_result = await self.get_pi_model()
pi_model_data = model_result.data if model_result.success else None
return PM3ServiceResult(
success=True,
data={
"total_cores": total_cores,
"online_cores": online_cores,
"configured_cores": configured_cores, # From cmdline.txt
"configurable_cores": configurable_cores,
"pi_model": pi_model_data
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="cpu_cores_error",
message="Failed to get CPU cores config",
details=str(e)
)
)
# Possible locations for cmdline.txt (varies by Pi OS version)
CMDLINE_PATHS = [
Path("/boot/firmware/cmdline.txt"), # Newer Pi OS (Bookworm+)
Path("/boot/cmdline.txt"), # Older Pi OS
]
def _find_cmdline_path(self) -> Optional[Path]:
"""Find the cmdline.txt file location.
Returns:
Path to cmdline.txt or None if not found
"""
for path in self.CMDLINE_PATHS:
if path.exists():
return path
return None
def _get_configured_maxcpus(self) -> Optional[int]:
"""Read the maxcpus value from cmdline.txt.
Returns:
Configured maxcpus value, or None if not set
"""
cmdline_path = self._find_cmdline_path()
if not cmdline_path:
return None
try:
content = cmdline_path.read_text().strip()
# Parse cmdline parameters
for param in content.split():
if param.startswith("maxcpus="):
return int(param.split("=")[1])
except Exception:
pass
return None
async def set_cpu_cores(
self,
num_cores: int,
persist: bool = True,
reboot: bool = True
) -> PM3ServiceResult:
"""Set the number of active CPU cores via kernel parameter.
On Pi Zero 2 W (and other ARM systems), CPU hotplug via sysfs doesn't work.
Instead, we modify the maxcpus=N kernel parameter in /boot/cmdline.txt.
This requires a reboot to take effect.
Args:
num_cores: Number of cores to use (1 to total_cores)
persist: Must be True (always persists to cmdline.txt)
reboot: If True, reboot the system immediately
Returns:
PM3ServiceResult indicating success/failure
"""
try:
# Use physical cores (not limited by current maxcpus setting)
total_cores = self._get_physical_cores()
# Validate input
if num_cores < 1:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="invalid_cores",
message="Must have at least 1 core active",
details=f"Requested: {num_cores}"
)
)
if num_cores > total_cores:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="invalid_cores",
message=f"Cannot exceed {total_cores} cores",
details=f"Requested: {num_cores}, Available: {total_cores}"
)
)
# Find cmdline.txt
cmdline_path = self._find_cmdline_path()
if not cmdline_path:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="cmdline_not_found",
message="Could not find /boot/cmdline.txt or /boot/firmware/cmdline.txt",
details="This feature requires a Raspberry Pi with standard boot configuration"
)
)
# Update cmdline.txt with maxcpus parameter
update_result = await self._update_cmdline_maxcpus(cmdline_path, num_cores)
if not update_result.success:
return update_result
# Reboot if requested
if reboot:
await self._run_command("sudo shutdown -r +0", check=False)
return PM3ServiceResult(
success=True,
data={
"message": f"CPU cores set to {num_cores}. Rebooting...",
"requested": num_cores,
"rebooting": True
}
)
return PM3ServiceResult(
success=True,
data={
"message": f"CPU cores set to {num_cores}. Reboot required to apply.",
"requested": num_cores,
"rebooting": False,
"reboot_required": True
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="set_cores_error",
message="Failed to set CPU cores",
details=str(e)
)
)
async def _update_cmdline_maxcpus(
self,
cmdline_path: Path,
num_cores: int
) -> PM3ServiceResult:
"""Update the maxcpus parameter in cmdline.txt.
Args:
cmdline_path: Path to cmdline.txt
num_cores: Number of cores to set
Returns:
PM3ServiceResult indicating success/failure
"""
try:
# Read current cmdline
content = cmdline_path.read_text().strip()
# Parse and update parameters
params = content.split()
new_params = []
maxcpus_found = False
for param in params:
if param.startswith("maxcpus="):
# Replace existing maxcpus
new_params.append(f"maxcpus={num_cores}")
maxcpus_found = True
else:
new_params.append(param)
# Add maxcpus if not present
if not maxcpus_found:
new_params.append(f"maxcpus={num_cores}")
new_content = " ".join(new_params)
# Backup original
await self._run_command(
f"sudo cp {cmdline_path} {cmdline_path}.bak",
check=True
)
# Write new cmdline.txt
# Use a temp file and move to avoid corruption
await self._run_command(
f"echo '{new_content}' | sudo tee {cmdline_path}.new > /dev/null",
check=True
)
await self._run_command(
f"sudo mv {cmdline_path}.new {cmdline_path}",
check=True
)
return PM3ServiceResult(
success=True,
data={"message": f"Updated {cmdline_path} with maxcpus={num_cores}"}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="cmdline_update_error",
message="Failed to update cmdline.txt",
details=str(e)
)
)
def get_configured_cpu_cores(self) -> Optional[int]:
"""Get the configured CPU cores from cmdline.txt.
Returns:
Configured maxcpus value, or None if not explicitly set
"""
return self._get_configured_maxcpus()

View File

@@ -0,0 +1,312 @@
"""Update Service Layer.
This service provides software update operations that can be consumed by
multiple interfaces (REST API, BLE GATT, etc.).
"""
from typing import Optional, Dict, Any
from ..managers.update_manager import UpdateManager, UpdateProgress, UpdateStatus
from .pm3_service import PM3ServiceError, PM3ServiceResult
class UpdateService:
"""Update service layer for software update management.
This service can be used by multiple interfaces:
- REST API (FastAPI endpoints)
- BLE GATT (Bluetooth handlers)
- Plugin system (future)
It encapsulates:
- Update checking
- Update downloading
- Update installation
- Progress monitoring
"""
def __init__(self, update_manager: Optional[UpdateManager] = None):
"""Initialize update service.
Args:
update_manager: Update manager instance (creates new if not provided)
"""
from ..managers.update_manager import get_update_manager
self.update_manager = update_manager or get_update_manager()
async def check_for_updates(self) -> PM3ServiceResult:
"""Check for available updates.
Returns:
PM3ServiceResult with update availability and information
"""
try:
result = await self.update_manager.check_for_updates()
return PM3ServiceResult(
success=True,
data=result
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="update_check_error",
message="Failed to check for updates",
details=str(e)
)
)
async def download_update(self) -> PM3ServiceResult:
"""Download the latest available update.
Returns:
PM3ServiceResult indicating download success/failure
"""
try:
success = await self.update_manager.download_update()
if success:
return PM3ServiceResult(
success=True,
data={
"message": "Update downloaded successfully",
"ready_to_install": True
}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="download_failed",
message="Update download failed"
)
)
except ValueError as e:
# No update available
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="no_update_available",
message=str(e)
)
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="update_download_error",
message="Error downloading update",
details=str(e)
)
)
async def install_update(self) -> PM3ServiceResult:
"""Install the downloaded update.
Returns:
PM3ServiceResult indicating installation success/failure
"""
try:
success = await self.update_manager.install_update()
if success:
return PM3ServiceResult(
success=True,
data={
"message": "Update installed successfully",
"requires_restart": True
}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="installation_failed",
message="Update installation failed"
)
)
except ValueError as e:
# No update downloaded
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="no_update_downloaded",
message=str(e)
)
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="update_install_error",
message="Error installing update",
details=str(e)
)
)
async def get_progress(self) -> PM3ServiceResult:
"""Get current update progress.
Returns:
PM3ServiceResult with progress information
"""
try:
progress = await self.update_manager.get_progress()
return PM3ServiceResult(
success=True,
data={
"status": progress.status.value,
"current_version": progress.current_version,
"available_version": progress.available_version,
"download_progress": progress.download_progress,
"error_message": progress.error_message,
"last_check": progress.last_check
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="progress_error",
message="Failed to get update progress",
details=str(e)
)
)
async def get_release_notes(
self,
version: Optional[str] = None
) -> PM3ServiceResult:
"""Get release notes for a specific version or latest.
Args:
version: Version to get notes for (latest if None)
Returns:
PM3ServiceResult with release notes
"""
try:
notes = await self.update_manager.get_release_notes(version)
return PM3ServiceResult(
success=True,
data={
"version": version or "latest",
"release_notes": notes
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="release_notes_error",
message="Failed to get release notes",
details=str(e)
)
)
async def check_and_download_update(self) -> PM3ServiceResult:
"""Combined operation: check for updates and download if available.
Returns:
PM3ServiceResult with check and download status
"""
try:
# First check for updates
check_result = await self.check_for_updates()
if not check_result.success:
return check_result
# If update available, download it
if check_result.data.get("update_available"):
download_result = await self.download_update()
if download_result.success:
return PM3ServiceResult(
success=True,
data={
"message": "Update checked and downloaded",
"update_info": check_result.data,
"ready_to_install": True
}
)
else:
return download_result
else:
return PM3ServiceResult(
success=True,
data={
"message": "System is up to date",
"update_available": False,
"current_version": check_result.data.get("current_version")
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="check_download_error",
message="Error checking and downloading update",
details=str(e)
)
)
async def full_update(self) -> PM3ServiceResult:
"""Full update workflow: check, download, and install.
Returns:
PM3ServiceResult with complete update status
"""
try:
# Check for updates
check_result = await self.check_for_updates()
if not check_result.success:
return check_result
if not check_result.data.get("update_available"):
return PM3ServiceResult(
success=True,
data={
"message": "System is already up to date",
"update_performed": False
}
)
# Download update
download_result = await self.download_update()
if not download_result.success:
return download_result
# Install update
install_result = await self.install_update()
if not install_result.success:
return install_result
return PM3ServiceResult(
success=True,
data={
"message": "Update completed successfully",
"update_performed": True,
"previous_version": check_result.data.get("current_version"),
"new_version": check_result.data.get("latest_version"),
"requires_restart": True
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="full_update_error",
message="Error performing full update",
details=str(e)
)
)

View File

@@ -0,0 +1,351 @@
"""WiFi Service Layer.
This service provides WiFi management operations that can be consumed by
multiple interfaces (REST API, BLE GATT, etc.).
"""
from typing import Optional, List, Dict, Any
from ..managers.wifi_manager import WiFiManager, WiFiMode, WiFiStatus, WiFiNetwork
from .pm3_service import PM3ServiceError, PM3ServiceResult
class WiFiService:
"""WiFi service layer for network management.
This service can be used by multiple interfaces:
- REST API (FastAPI endpoints)
- BLE GATT (Bluetooth handlers)
- Plugin system (future)
It encapsulates:
- Network scanning
- Connection management
- WiFi mode switching
- Status queries
"""
def __init__(self, wifi_manager: Optional[WiFiManager] = None):
"""Initialize WiFi service.
Args:
wifi_manager: WiFi manager instance (creates new if not provided)
"""
self.wifi_manager = wifi_manager or WiFiManager()
async def get_status(self) -> PM3ServiceResult:
"""Get current WiFi status.
Returns:
PM3ServiceResult with WiFi status (mode, interfaces, connections)
"""
try:
status = await self.wifi_manager.get_status()
return PM3ServiceResult(
success=True,
data={
"mode": status.mode.value,
"interfaces": [
{
"name": iface.name,
"mac": iface.mac,
"is_usb": iface.is_usb,
"is_up": iface.is_up,
"connected": iface.connected,
"ssid": iface.ssid,
"ip_address": iface.ip_address,
"mode": iface.mode # "AP" or "managed"
}
for iface in status.interfaces
],
"client": {
"ssid": status.current_ssid,
"ip": status.current_ip
} if status.current_ssid else None,
"access_point": {
"ssid": status.ap_ssid,
"ip": status.ap_ip
},
"supports_dual": status.supports_dual
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="wifi_status_error",
message="Failed to get WiFi status",
details=str(e)
)
)
async def scan_networks(
self,
interface: Optional[str] = None
) -> PM3ServiceResult:
"""Scan for available WiFi networks.
Args:
interface: Interface to scan with (default: auto-select)
Returns:
PM3ServiceResult with list of available networks
"""
try:
networks = await self.wifi_manager.scan_networks(interface)
return PM3ServiceResult(
success=True,
data={
"networks": [
{
"ssid": net.ssid,
"bssid": net.bssid,
"signal_strength": net.signal_strength,
"frequency": net.frequency,
"encrypted": net.encrypted,
"in_use": net.in_use
}
for net in networks
],
"count": len(networks)
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="wifi_scan_error",
message="Failed to scan for networks",
details=str(e)
)
)
async def connect(
self,
ssid: str,
password: Optional[str] = None,
interface: Optional[str] = None,
hidden: bool = False
) -> PM3ServiceResult:
"""Connect to a WiFi network.
Args:
ssid: Network SSID
password: Network password (if encrypted)
interface: Interface to use (default: auto-select)
hidden: Whether network is hidden
Returns:
PM3ServiceResult indicating connection success/failure
"""
try:
success = await self.wifi_manager.connect_to_network(
ssid=ssid,
password=password,
interface=interface,
hidden=hidden
)
if success:
# Get updated status to include new connection info
status = await self.wifi_manager.get_status()
return PM3ServiceResult(
success=True,
data={
"message": f"Successfully connected to {ssid}",
"ssid": ssid,
"ip": status.current_ip
}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="connection_failed",
message=f"Failed to connect to {ssid}",
details="Connection attempt failed or timed out"
)
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="wifi_connect_error",
message=f"Error connecting to {ssid}",
details=str(e)
)
)
async def disconnect(
self,
interface: Optional[str] = None
) -> PM3ServiceResult:
"""Disconnect from current network.
Args:
interface: Interface to disconnect (default: first connected)
Returns:
PM3ServiceResult indicating success/failure
"""
try:
success = await self.wifi_manager.disconnect_from_network(interface)
if success:
return PM3ServiceResult(
success=True,
data={"message": "Disconnected from network"}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="disconnect_failed",
message="Failed to disconnect",
details="No active connection found or disconnect failed"
)
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="wifi_disconnect_error",
message="Error disconnecting from network",
details=str(e)
)
)
async def set_mode(self, mode: str) -> PM3ServiceResult:
"""Set WiFi operation mode.
Args:
mode: WiFi mode ("ap", "client", "dual", "auto", "off")
Returns:
PM3ServiceResult indicating success/failure
"""
try:
# Validate and convert mode string to enum
try:
wifi_mode = WiFiMode(mode)
except ValueError:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="invalid_mode",
message=f"Invalid WiFi mode: {mode}",
details=f"Valid modes: ap, client, dual, auto, off"
)
)
success = await self.wifi_manager.set_mode(wifi_mode)
if success:
return PM3ServiceResult(
success=True,
data={
"message": f"WiFi mode set to {mode}",
"mode": mode
}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="mode_change_failed",
message=f"Failed to set WiFi mode to {mode}",
details="Mode change operation failed"
)
)
except ValueError as e:
# Handle dual mode without USB adapter
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="mode_not_supported",
message=str(e),
details="Dual mode requires USB WiFi adapter"
)
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="wifi_mode_error",
message="Error setting WiFi mode",
details=str(e)
)
)
async def get_saved_networks(self) -> PM3ServiceResult:
"""Get list of saved networks.
Returns:
PM3ServiceResult with list of saved networks
"""
try:
networks = await self.wifi_manager.get_saved_networks()
return PM3ServiceResult(
success=True,
data={
"networks": networks,
"count": len(networks)
}
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="saved_networks_error",
message="Failed to get saved networks",
details=str(e)
)
)
async def forget_network(self, ssid: str) -> PM3ServiceResult:
"""Forget a saved network.
Args:
ssid: SSID of network to forget
Returns:
PM3ServiceResult indicating success/failure
"""
try:
success = await self.wifi_manager.forget_network(ssid)
if success:
return PM3ServiceResult(
success=True,
data={
"message": f"Network '{ssid}' forgotten",
"ssid": ssid
}
)
else:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="network_not_found",
message=f"Network '{ssid}' not found in saved networks"
)
)
except Exception as e:
return PM3ServiceResult(
success=False,
error=PM3ServiceError(
code="forget_network_error",
message=f"Error forgetting network '{ssid}'",
details=str(e)
)
)

View File

@@ -1 +0,0 @@
"""Server-Sent Events (SSE) endpoints."""

View File

@@ -1,165 +0,0 @@
"""SSE event endpoints for real-time notifications."""
import asyncio
import json
from typing import AsyncGenerator
from fastapi import APIRouter
from sse_starlette.sse import EventSourceResponse
router = APIRouter()
# Global event queue for broadcasting events
event_queues: list[asyncio.Queue] = []
class EventBroadcaster:
"""Broadcasts events to all connected SSE clients."""
@staticmethod
async def broadcast(event_type: str, data: dict):
"""Broadcast an event to all connected clients.
Args:
event_type: Type of event (e.g., "update_available", "backup_complete")
data: Event data to send
"""
message = {
"type": event_type,
"data": data
}
# Send to all connected clients
dead_queues = []
for queue in event_queues:
try:
await queue.put(message)
except Exception:
# Queue is dead, mark for removal
dead_queues.append(queue)
# Remove dead queues
for dead_queue in dead_queues:
event_queues.remove(dead_queue)
broadcaster = EventBroadcaster()
async def event_generator() -> AsyncGenerator[dict, None]:
"""Generate SSE events for a client connection."""
# Create a new queue for this client
queue = asyncio.Queue()
event_queues.append(queue)
try:
# Send initial connection event
yield {
"event": "connected",
"data": json.dumps({"message": "Connected to Dangerous Pi event stream"})
}
# Keep connection alive and send events
while True:
try:
# Wait for events with timeout to send keep-alive
message = await asyncio.wait_for(queue.get(), timeout=30.0)
yield {
"event": message["type"],
"data": json.dumps(message["data"])
}
except asyncio.TimeoutError:
# Send keep-alive comment
yield {
"comment": "keep-alive"
}
except asyncio.CancelledError:
# Client disconnected
pass
finally:
# Remove queue when client disconnects
if queue in event_queues:
event_queues.remove(queue)
@router.get("/events")
async def stream_events():
"""SSE endpoint for streaming events to clients.
Events include:
- update_available: New version available on GitHub
- update_downloading: Update download in progress
- update_complete: Update downloaded and ready to install
- backup_complete: Backup operation completed
- ups_low_battery: UPS battery below threshold
- pm3_rebuild_required: PM3 client rebuild needed
- command_complete: Long-running command completed
"""
return EventSourceResponse(event_generator())
# Helper functions for sending specific event types
async def notify_update_available(version: str, url: str):
"""Notify clients that an update is available."""
await broadcaster.broadcast("update_available", {
"version": version,
"url": url
})
async def notify_update_progress(progress: float, status: str):
"""Notify clients of update download progress."""
await broadcaster.broadcast("update_downloading", {
"progress": progress,
"status": status
})
async def notify_backup_complete(backup_path: str, size_bytes: int):
"""Notify clients that backup is complete."""
await broadcaster.broadcast("backup_complete", {
"path": backup_path,
"size": size_bytes
})
async def notify_ups_battery(percentage: float, voltage: float):
"""Notify clients of UPS battery status."""
await broadcaster.broadcast("ups_battery", {
"percentage": percentage,
"voltage": voltage
})
async def notify_ups_warning(percentage: float, threshold: float):
"""Notify clients of low battery warning."""
await broadcaster.broadcast("ups_warning", {
"percentage": percentage,
"threshold": threshold,
"message": f"Battery low: {percentage}%"
})
async def notify_ups_critical(percentage: float):
"""Notify clients of critical battery level."""
await broadcaster.broadcast("ups_critical", {
"percentage": percentage,
"message": f"Battery critical: {percentage}%"
})
async def notify_ups_shutdown(delay: int, percentage: float):
"""Notify clients that shutdown has been initiated."""
await broadcaster.broadcast("ups_shutdown", {
"delay": delay,
"percentage": percentage,
"message": f"Shutdown initiated due to low battery ({percentage}%)"
})
async def notify_pm3_status(connected: bool, message: str):
"""Notify clients of PM3 status changes."""
await broadcaster.broadcast("pm3_status", {
"connected": connected,
"message": message
})

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)

View File

@@ -4,6 +4,7 @@ from dataclasses import dataclass
from typing import Optional
from pathlib import Path
import sys
import os
from .. import config
@@ -35,7 +36,41 @@ class PM3Worker:
"""Import the pm3 module (lazy loading)."""
if self._pm3_module is None:
try:
# The pm3 module should be available after pm3 client installation
# Setup Python path for pm3 module
# The pm3 module is in proxmark3/client/pyscripts
# The _pm3.so is in proxmark3/client/experimental_lib/example_py
# Try multiple possible locations for pyscripts
# The pm3 module is in proxmark3/client/pyscripts
possible_pyscripts = [
os.path.expanduser("~/.pm3/proxmark3/client/pyscripts"), # Pi install location
"/home/dt/.pm3/proxmark3/client/pyscripts", # Pi install (explicit path)
os.path.expanduser("~/.pm3/client/pyscripts"), # Alternative structure
"/usr/local/share/proxmark3/pyscripts", # System install
"/usr/share/proxmark3/pyscripts", # System install alt
os.path.join(os.path.dirname(__file__), "../../../.pm3-test/proxmark3/client/pyscripts"), # Dev build
]
pm3_pyscripts = None
for path in possible_pyscripts:
pm3_py = os.path.join(path, "pm3.py")
if os.path.exists(pm3_py):
pm3_pyscripts = path
break
if not pm3_pyscripts:
raise ImportError(f"Could not find pm3.py in any of: {possible_pyscripts}")
# experimental_lib is at the same level as pyscripts (client/experimental_lib)
pm3_lib = os.path.join(os.path.dirname(pm3_pyscripts), "experimental_lib/example_py")
# Add to Python path if not already there
if pm3_pyscripts not in sys.path:
sys.path.insert(0, pm3_pyscripts)
if pm3_lib not in sys.path:
sys.path.insert(0, pm3_lib)
# Import pm3 module
import pm3
self._pm3_module = pm3
except ImportError as e:
@@ -45,25 +80,29 @@ class PM3Worker:
)
return self._pm3_module
async def _connect_internal(self):
"""Internal connect without locking (caller must hold lock)."""
if self._connected:
return
try:
pm3 = await self._import_pm3()
# Run blocking pm3.pm3() constructor in executor
loop = asyncio.get_event_loop()
self._device = await loop.run_in_executor(
None,
pm3.pm3,
self.device_path
)
self._connected = True
except Exception as e:
raise ConnectionError(f"Failed to connect to PM3 at {self.device_path}: {e}")
async def connect(self):
"""Connect to the Proxmark3 device."""
async with self._lock:
if self._connected:
return
try:
pm3 = await self._import_pm3()
# Run blocking pm3.open() in executor
loop = asyncio.get_event_loop()
self._device = await loop.run_in_executor(
None,
pm3.open,
self.device_path
)
self._connected = True
except Exception as e:
raise ConnectionError(f"Failed to connect to PM3 at {self.device_path}: {e}")
await self._connect_internal()
async def disconnect(self):
"""Disconnect from the Proxmark3 device."""
@@ -95,9 +134,9 @@ class PM3Worker:
"""
async with self._lock:
try:
# Ensure we're connected
# Ensure we're connected (use internal method since we hold the lock)
if not self._connected:
await self.connect()
await self._connect_internal()
if not self._device:
return PM3CommandResult(
@@ -110,14 +149,18 @@ class PM3Worker:
loop = asyncio.get_event_loop()
try:
# Use .cmd() method to execute command
output = await loop.run_in_executor(
None,
self._device.cmd,
command
)
# Helper function to run command and get output in same executor call
def run_command():
try:
self._device.console(command)
output = self._device.grabbed_output
return output
except Exception as e:
raise Exception(f"Error in run_command: {e}, device type: {type(self._device)}")
# Execute command and get output
output = await loop.run_in_executor(None, run_command)
# pm3.cmd() returns the output string
return PM3CommandResult(
success=True,
output=str(output) if output else "",
@@ -148,6 +191,7 @@ class MockPM3Worker(PM3Worker):
"hw version": "Proxmark3 RFID instrument\n client: RRG/Iceman/master/v4.14831",
"hw status": "Device: PM3 GENERIC\nBootrom: master/v4.14831\nOS: master/v4.14831",
"hw tune": "Measuring antenna characteristics, please wait...\n# LF antenna: 50.00 V @ 125.00 kHz",
"hw led": "[+] LED control command executed",
}
async def connect(self):
@@ -181,3 +225,128 @@ class MockPM3Worker(PM3Worker):
output=f"Mock response for: {command}",
error=None
)
class SubprocessPM3Worker(PM3Worker):
"""PM3 worker using subprocess to call pm3 CLI directly.
This is a fallback for when the Python SWIG bindings aren't working.
It executes pm3 CLI commands via subprocess which is more robust.
"""
def __init__(self, device_path: str = None):
super().__init__(device_path)
self._pm3_path = None
self._find_pm3_executable()
def _find_pm3_executable(self):
"""Find the pm3 executable."""
possible_paths = [
"/usr/local/bin/pm3",
os.path.expanduser("~/.pm3/proxmark3/client/proxmark3"),
"/home/dt/.pm3/proxmark3/client/proxmark3",
"/usr/bin/pm3",
]
for path in possible_paths:
if os.path.exists(path) and os.access(path, os.X_OK):
self._pm3_path = path
break
if not self._pm3_path:
# Try to find in PATH
import shutil
pm3_in_path = shutil.which("pm3") or shutil.which("proxmark3")
if pm3_in_path:
self._pm3_path = pm3_in_path
async def connect(self):
"""Check that pm3 executable exists and device is available."""
async with self._lock:
if self._connected:
return
if not self._pm3_path:
raise ConnectionError("pm3 executable not found")
if not Path(self.device_path).exists():
raise ConnectionError(f"PM3 device not found at {self.device_path}")
self._connected = True
async def disconnect(self):
"""Mark as disconnected."""
async with self._lock:
self._connected = False
async def is_connected(self) -> bool:
"""Check if device exists."""
return Path(self.device_path).exists() if self.device_path else False
async def execute_command(self, command: str) -> PM3CommandResult:
"""Execute a PM3 command via subprocess.
Args:
command: PM3 command to execute (e.g., "hw version")
Returns:
PM3CommandResult with success status, output, and optional error
"""
async with self._lock:
try:
if not self._pm3_path:
return PM3CommandResult(
success=False,
output="",
error="pm3 executable not found"
)
# Build command: pm3 -p /dev/ttyACM0 -c "command"
cmd = [
self._pm3_path,
"-p", self.device_path,
"-c", command
]
# Run subprocess
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=30.0 # 30 second timeout
)
except asyncio.TimeoutError:
process.kill()
return PM3CommandResult(
success=False,
output="",
error="Command timed out after 30 seconds"
)
output = stdout.decode("utf-8", errors="replace")
error_output = stderr.decode("utf-8", errors="replace")
if process.returncode == 0:
return PM3CommandResult(
success=True,
output=output,
error=None
)
else:
return PM3CommandResult(
success=False,
output=output,
error=error_output or f"Command failed with exit code {process.returncode}"
)
except Exception as e:
return PM3CommandResult(
success=False,
output="",
error=str(e)
)