0e3ae78de7
Closes the issues surfaced by the pre-merge code review of the expand-device-support branch. CRITICAL #2 -- update_device double-encrypts secrets in memory. storage/device_store.py round-tripped through device.to_dict() which encrypts hue_username / hue_client_key / ble_govee_key / nanoleaf_token via _enc(), but Device.__init__ does not decrypt. The cached self._items[device_id] thus held ciphertext where plaintext belonged, breaking runtime auth for paired devices on any update -- even an innocuous rename. Sourcing kwargs from vars(device) directly avoids the round-trip. Regression tests cover Nanoleaf and Hue. HIGH #3 -- secrets leaked in GET /api/v1/devices response. DeviceResponse previously returned nanoleaf_token / hue_username / hue_client_key in plaintext (decrypted server-side from storage), defeating the encryption-at-rest. Replaced with nanoleaf_paired and hue_paired booleans. ble_govee_key intentionally stays -- it's a user-managed value pasted from a third-party tool, must remain visible for edit. Frontend types.ts + the one nanoleaf_token reader updated to the boolean. HIGH #4 -- SSRF surface. validate_lan_host() added to net_classify.py; called from each new driver's validate_device (DDP / Yeelight / WiZ / LIFX / Govee / OPC / Nanoleaf) and from pair_device. Rejects literal public IPs with a descriptive ValueError; non-IP hostnames pass through (mDNS labels, bare hostnames). RFC6890 ranges (documentation, former class E) are accepted as LAN-like since Python's ipaddress.is_private treats them so -- correct policy for LedGrab. HIGH #5 -- decrypt failure deletes the device row. _dec() now catches the exception, logs an error, and returns "" instead of propagating. Without the fix, a regenerated data/.secret_key would silently make every Hue / Nanoleaf / BLE-Govee device disappear from the device list on next startup. Regression test asserts a corrupt envelope leaves the device hydratable. HIGH #6 -- update_device route does not rstrip("/") for non-WLED. Moved the trim before the WLED-specific scheme inference so every device type gets consistent URL normalization between create and update. MEDIUM #7 -- Govee discovery port 4002 collision. Added a lazily- initialized module-level asyncio.Lock that serializes concurrent discover_govee_devices() calls; the previous behavior had the second parallel scan silently return [] when the first still held port 4002. Error message also clarified to mention another Govee tool. MEDIUM #8 -- Nanoleaf discover() leaked browser tasks on cancellation. Moved the browser cancel loop into the finally block so an interrupted mDNS scan still tears them down. MEDIUM #9 -- pair endpoint logged user-supplied URL with exc_info=True. Added _sanitize_url_for_log() that strips userinfo + fragment, and demoted the log from exc_info to type(exc).__name__ + str(exc) so a hostile receiver's response body can't end up in the log file. LOW -- Nanoleaf was the only client without a .port property. Added one (returns NANOLEAF_PORT, fixed) for cross-driver symmetry. LOW -- no end-to-end pair-then-create coverage. Added TestPairThenCreateFlow.test_pair_then_create_persists_encrypted_token which exercises the full path: POST /api/v1/devices/pair returned fields, store.create_device, then asserts (a) in-memory plaintext, (b) to_config() plaintext, (c) persisted ciphertext, (d) API response strip + paired-boolean. Tests: 1379 pass (was 1358 -- 21 new regression tests added). ruff clean. TypeScript clean.
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