e24f9d33cc
Two bugs caused user data ('G502' target's color-strip ref, etc.) to
revert after PC restart while persisting fine across normal app
restarts:
1. SQLite was in WAL mode with synchronous=NORMAL and Database.close()
was never called. On graceful Python exit the sqlite3 finalizer
checkpoints the WAL, but on an unclean PC shutdown (power loss,
forced reboot, or Windows force-terminating pythonw.exe) the WAL
stayed in OS cache, never reached disk, and the next boot rolled the
DB back to the last checkpoint -- losing recent edits.
2. Nothing handled WM_QUERYENDSESSION / WM_ENDSESSION, so on PC
shutdown Windows force-killed pythonw.exe after ~5s and the FastAPI
lifespan never ran. The 'stop_targets' setting was silently ignored
and devices were left at their last frame.
Changes:
- Database: PRAGMA synchronous=FULL + wal_autocheckpoint=100, plus an
explicit wal_checkpoint(TRUNCATE) inside Database.close().
- New utils/win_shutdown.py: hidden top-level window in a daemon thread
with a ctypes WindowProc that catches WM_QUERYENDSESSION (calls
ShutdownBlockReasonCreate to extend Windows' 5s hung-app timeout up
to the ~20s GUI ceiling), fires the shutdown callback, then waits in
WM_ENDSESSION on a completion event before returning. Also raises
the process shutdown priority via SetProcessShutdownParameters. All
Win32 argtypes/restypes are bound once at import to avoid LPARAM
overflow on x64.
- New shutdown_state.py: leaf module owning the cross-thread Event so
__main__ does not import the heavy ledgrab.main at startup.
- main.py lifespan: per-step asyncio.wait_for budgets (8s for
processor_manager.stop_all, 1.5s each for HA/MQTT, etc.) so a hung
device cannot starve the DB checkpoint, then db.close() and
shutdown_complete.set() always run.
- __main__.py: install the Windows shutdown guard before tray start;
install SIGINT/SIGTERM/SIGBREAK handlers only on the tray path
(uvicorn overwrites them on no-tray); raise server_thread.join to 20s.
- Tests cover WM_QUERYENDSESSION (fires callback, returns TRUE,
idempotent), WM_ENDSESSION (waits on event, times out cleanly,
cancel-path returns instantly), signal handler installation, and
that main and shutdown_state share the same Event instance.
LedGrab - Server
High-performance FastAPI server that captures screen content and controls WLED devices for ambient lighting.
Overview
The server component provides:
- 🎯 Real-time Screen Capture - Multi-monitor support with configurable FPS
- 🎨 Advanced Processing - Border pixel extraction with color correction
- 🔧 Flexible Calibration - Map screen edges to any LED layout
- 🌐 REST API - Complete control via 25+ REST endpoints
- 💾 Persistent Storage - JSON-based device and configuration management
- 📊 Metrics & Monitoring - Real-time FPS, status, and performance data
Quick Start
Option 1: Docker (Recommended)
# Start server
docker-compose up -d
# View logs
docker-compose logs -f
# Stop server
docker-compose down
Server runs on: http://localhost:8080
Option 2: Python
# Create virtual environment
python -m venv venv
# Activate
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
# Install dependencies
pip install .
# Set PYTHONPATH
export PYTHONPATH=$(pwd)/src # Linux/Mac
set PYTHONPATH=%CD%\src # Windows
# Run server
uvicorn ledgrab.main:app --host 0.0.0.0 --port 8080
Installation
Requirements
- Python 3.11+ (for Python installation)
- Docker & Docker Compose (for Docker installation)
- WLED device on your network
See ../INSTALLATION.md for comprehensive installation guide.
Configuration
Configuration File
Edit config/default_config.yaml:
server:
host: "0.0.0.0"
port: 8080
log_level: "INFO"
processing:
default_fps: 30 # Target frames per second
max_fps: 60 # Maximum allowed FPS
border_width: 10 # Pixels to sample from edge
wled:
timeout: 5 # Connection timeout (seconds)
retry_attempts: 3 # Number of retries
storage:
devices_file: "data/devices.json"
logging:
format: "json"
file: "logs/ledgrab.log"
Environment Variables
# Server configuration
export LEDGRAB_SERVER__HOST="0.0.0.0"
export LEDGRAB_SERVER__PORT=8080
export LEDGRAB_SERVER__LOG_LEVEL="INFO"
# Processing configuration
export LEDGRAB_PROCESSING__DEFAULT_FPS=30
export LEDGRAB_PROCESSING__BORDER_WIDTH=10
# WLED configuration
export WLED_WLED__TIMEOUT=5
Usage
WLED Device Setup
Important: Configure your WLED device using the official WLED web interface before connecting it to this controller:
- Access WLED Interface: Open
http://[wled-ip]in your browser - Configure Device Settings:
- Set LED count and type
- Configure brightness, color order, and power limits
- Set up segments if needed
- Configure effects and presets
This controller only sends pixel color data - it does not manage WLED settings like brightness, effects, or segments. All WLED device configuration should be done through the official WLED interface.
API Documentation
- Web UI: http://localhost:8080 (recommended for device management)
- Swagger UI: http://localhost:8080/docs
- ReDoc: http://localhost:8080/redoc
Quick Example
# 1. Add device
curl -X POST http://localhost:8080/api/v1/devices \
-H "Content-Type: application/json" \
-d '{"name":"Living Room","url":"http://192.168.1.100","led_count":150}'
# 2. Start processing
curl -X POST http://localhost:8080/api/v1/devices/{device_id}/start
# 3. Check status
curl http://localhost:8080/api/v1/devices/{device_id}/state
Testing
# Run all tests
pytest
# Run with coverage
pytest --cov=ledgrab --cov-report=html
# Run specific test
pytest tests/test_screen_capture.py -v
Development
Project Structure
src/ledgrab/
├── main.py # FastAPI application
├── config.py # Configuration
├── api/ # API routes
├── core/ # Core functionality
│ ├── screen_capture.py
│ ├── wled_client.py
│ ├── calibration.py
│ └── processor_manager.py
├── storage/ # Data persistence
└── utils/ # Utilities
Code Quality
# Format code
black src/ tests/
# Lint code
ruff check src/ tests/
License
MIT - see ../LICENSE