Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4808132436 | ||
|
|
eca41f8daa | ||
|
|
cc1db66662 | ||
|
|
97336b805e | ||
|
|
b428ae3eae | ||
|
|
66336fe160 | ||
|
|
1aa9cb7504 | ||
|
|
ae47c89531 | ||
|
|
6edd6f9beb | ||
|
|
e1fa597b29 | ||
|
|
1073e7098a | ||
|
|
1994a81617 | ||
|
|
0ec3431815 | ||
|
|
b68c1fa8fe | ||
|
|
1ec22db2d1 | ||
|
|
45032f96e1 | ||
|
|
e1efbaf6a2 | ||
|
|
5ae1a2b7c4 | ||
|
|
832bf32a8c | ||
|
|
a41cad6bc5 | ||
|
|
b22fe2e71f | ||
|
|
63076254d4 | ||
|
|
2408309d84 | ||
|
|
ab087cf600 | ||
|
|
c0a2d2f301 | ||
|
|
6087d5162f | ||
|
|
27ce5af714 | ||
|
|
2dae36a094 | ||
|
|
2af41c561b | ||
|
|
5b81cca684 | ||
|
|
d305be6089 | ||
|
|
53af53b4a1 | ||
|
|
183e23edb3 | ||
|
|
970ca2d04f | ||
|
|
f2b246ef03 | ||
|
|
963ab8292a | ||
|
|
16fbb7ebeb | ||
|
|
21825cbfbc | ||
|
|
82a65ad2a2 | ||
|
|
83f20b64fe | ||
|
|
5b45f35888 | ||
|
|
e2acbfb566 | ||
|
|
3872a68ff7 | ||
|
|
989162d28f | ||
|
|
cdf03fb107 | ||
|
|
6a9d8014e5 | ||
|
|
c90129285c | ||
|
|
66f9950a30 | ||
|
|
4abcd0e4f9 | ||
|
|
2a1c47fa76 | ||
|
|
9db1d2391a | ||
|
|
14a59c863c | ||
|
|
bff13129c4 | ||
|
|
6499794c12 | ||
|
|
3d347a368a | ||
|
|
0aca40cf3a | ||
|
|
9837315308 | ||
|
|
c1fa5094be | ||
|
|
4d49b0f892 | ||
|
|
efe76d3add | ||
|
|
273d9962d1 | ||
|
|
9e3b5f366e | ||
|
|
6edd80d9f3 | ||
|
|
1c7a0cef66 | ||
|
|
6052a60d22 | ||
|
|
7f7f0d6464 | ||
|
|
05e7c43b27 | ||
|
|
2ffc57cf40 | ||
|
|
aab0e9ade0 | ||
|
|
978a03b42d | ||
|
|
bd9f461f70 | ||
|
|
3b93024993 | ||
|
|
85d321cf33 | ||
|
|
63a233f3ed | ||
|
|
7a9d01342a | ||
|
|
9b2f02681d | ||
|
|
7a6bad29fe | ||
|
|
bea00448d3 | ||
|
|
deaa3d7a98 | ||
|
|
cbb8ec41e8 | ||
|
|
c6ce332d49 | ||
|
|
8e5f66501a | ||
|
|
639e1c3a93 | ||
|
|
6096a22c3d | ||
|
|
fefc2d44a2 | ||
|
|
d297dd6217 | ||
|
|
974d7ea57a | ||
|
|
ab0cfd2362 | ||
|
|
d22d0a3754 | ||
|
|
5beef0aa01 | ||
|
|
cf28a8c0d5 | ||
|
|
a06682981c | ||
|
|
bc027c921d | ||
|
|
e0bd7088fa | ||
|
|
313e35a98f |
@@ -1,145 +0,0 @@
|
||||
# Cursor Helper Files for LEDMatrix Plugin Development
|
||||
|
||||
This directory contains Cursor-specific helper files to assist with plugin development in the LEDMatrix project.
|
||||
|
||||
## Files Overview
|
||||
|
||||
### `.cursorrules`
|
||||
Comprehensive rules file that Cursor uses to understand plugin development patterns, best practices, and workflows. This file is automatically loaded by Cursor and helps guide AI-assisted development.
|
||||
|
||||
### `plugins_guide.md`
|
||||
Detailed guide covering:
|
||||
- Plugin system overview
|
||||
- Creating new plugins
|
||||
- Running plugins (emulator and hardware)
|
||||
- Loading and configuring plugins
|
||||
- Development workflow
|
||||
- Testing strategies
|
||||
- Troubleshooting
|
||||
|
||||
### `plugin_templates/`
|
||||
Template files for quick plugin creation:
|
||||
- `manifest.json.template` - Plugin metadata template
|
||||
- `manager.py.template` - Plugin class template
|
||||
- `config_schema.json.template` - Configuration schema template
|
||||
- `README.md.template` - Plugin documentation template
|
||||
- `requirements.txt.template` - Dependencies template
|
||||
- `QUICK_START.md` - Quick start guide for using templates
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Creating a New Plugin
|
||||
|
||||
1. **Using templates** (recommended):
|
||||
```bash
|
||||
# See QUICK_START.md in plugin_templates/
|
||||
cd plugins
|
||||
mkdir my-plugin
|
||||
cd my-plugin
|
||||
cp ../../.cursor/plugin_templates/*.template .
|
||||
# Edit files, replacing PLUGIN_ID and other placeholders
|
||||
```
|
||||
|
||||
2. **Using dev_plugin_setup.sh**:
|
||||
```bash
|
||||
# Link from GitHub
|
||||
./scripts/dev/dev_plugin_setup.sh link-github my-plugin
|
||||
|
||||
# Link local repo
|
||||
./scripts/dev/dev_plugin_setup.sh link my-plugin /path/to/repo
|
||||
```
|
||||
|
||||
### Running the Display
|
||||
|
||||
```bash
|
||||
# Emulator mode (development, no hardware required)
|
||||
python3 run.py --emulator
|
||||
# (equivalent: EMULATOR=true python3 run.py)
|
||||
|
||||
# Hardware (production, requires the rpi-rgb-led-matrix submodule built)
|
||||
python3 run.py
|
||||
|
||||
# As a systemd service
|
||||
sudo systemctl start ledmatrix
|
||||
|
||||
# Dev preview server (renders plugins to a browser without running run.py)
|
||||
python3 scripts/dev_server.py # then open http://localhost:5001
|
||||
```
|
||||
|
||||
The `-e`/`--emulator` CLI flag is defined in `run.py:19-20` and
|
||||
sets `os.environ["EMULATOR"] = "true"` before any display imports,
|
||||
which `src/display_manager.py:2` then reads to switch between the
|
||||
hardware and emulator backends.
|
||||
|
||||
### Managing Plugins
|
||||
|
||||
```bash
|
||||
# List plugins
|
||||
./scripts/dev/dev_plugin_setup.sh list
|
||||
|
||||
# Check status
|
||||
./scripts/dev/dev_plugin_setup.sh status
|
||||
|
||||
# Update plugin(s)
|
||||
./scripts/dev/dev_plugin_setup.sh update [plugin-name]
|
||||
|
||||
# Unlink plugin
|
||||
./scripts/dev/dev_plugin_setup.sh unlink <plugin-name>
|
||||
```
|
||||
|
||||
## Using These Files with Cursor
|
||||
|
||||
### `.cursorrules`
|
||||
Cursor automatically reads this file to understand:
|
||||
- Plugin structure and requirements
|
||||
- Development workflows
|
||||
- Best practices
|
||||
- Common patterns
|
||||
- API reference
|
||||
|
||||
When asking Cursor to help with plugins, it will use this context to provide better assistance.
|
||||
|
||||
### Plugin Templates
|
||||
Use templates when creating new plugins:
|
||||
1. Copy templates from `.cursor/plugin_templates/`
|
||||
2. Replace placeholders (PLUGIN_ID, PluginClassName, etc.)
|
||||
3. Customize for your plugin's needs
|
||||
4. Follow the guide in `plugins_guide.md`
|
||||
|
||||
### Documentation
|
||||
Refer to `plugins_guide.md` for:
|
||||
- Detailed explanations
|
||||
- Troubleshooting steps
|
||||
- Best practices
|
||||
- Examples and patterns
|
||||
|
||||
## Plugin Development Workflow
|
||||
|
||||
1. **Plan**: Determine plugin functionality and requirements
|
||||
2. **Create**: Use templates or dev_plugin_setup.sh to create plugin structure
|
||||
3. **Develop**: Implement plugin logic following BasePlugin interface
|
||||
4. **Test**: Test with emulator first, then on hardware
|
||||
5. **Configure**: Add plugin config to config/config.json
|
||||
6. **Iterate**: Refine based on testing and feedback
|
||||
|
||||
## Resources
|
||||
|
||||
- **Plugin System**: `src/plugin_system/`
|
||||
- **Base Plugin**: `src/plugin_system/base_plugin.py`
|
||||
- **Plugin Manager**: `src/plugin_system/plugin_manager.py`
|
||||
- **Example Plugins**: see the
|
||||
[`ledmatrix-plugins`](https://github.com/ChuckBuilds/ledmatrix-plugins)
|
||||
repo for canonical sources (e.g. `plugins/hockey-scoreboard/`,
|
||||
`plugins/football-scoreboard/`). Installed plugins land in
|
||||
`plugin-repos/` (default) or `plugins/` (dev fallback).
|
||||
- **Architecture Docs**: `docs/PLUGIN_ARCHITECTURE_SPEC.md`
|
||||
- **Development Setup**: `scripts/dev/dev_plugin_setup.sh`
|
||||
|
||||
## Getting Help
|
||||
|
||||
1. Check `plugins_guide.md` for detailed documentation
|
||||
2. Review `.cursorrules` for development patterns
|
||||
3. Look at existing plugins for examples
|
||||
4. Check logs for error messages
|
||||
5. Review plugin system code in `src/plugin_system/`
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
# Quick Start: Creating a New Plugin
|
||||
|
||||
This guide will help you create a new plugin using the templates in `.cursor/plugin_templates/`.
|
||||
|
||||
## Step 1: Create Plugin Directory
|
||||
|
||||
```bash
|
||||
cd /path/to/LEDMatrix
|
||||
mkdir -p plugins/my-plugin
|
||||
cd plugins/my-plugin
|
||||
```
|
||||
|
||||
## Step 2: Copy Templates
|
||||
|
||||
```bash
|
||||
# Copy all template files
|
||||
cp ../../.cursor/plugin_templates/manifest.json.template ./manifest.json
|
||||
cp ../../.cursor/plugin_templates/manager.py.template ./manager.py
|
||||
cp ../../.cursor/plugin_templates/config_schema.json.template ./config_schema.json
|
||||
cp ../../.cursor/plugin_templates/README.md.template ./README.md
|
||||
cp ../../.cursor/plugin_templates/requirements.txt.template ./requirements.txt
|
||||
```
|
||||
|
||||
## Step 3: Customize Files
|
||||
|
||||
### manifest.json
|
||||
|
||||
Replace placeholders:
|
||||
- `PLUGIN_ID` → `my-plugin` (lowercase, use hyphens)
|
||||
- `Plugin Name` → Your plugin's display name
|
||||
- `PluginClassName` → `MyPlugin` (PascalCase)
|
||||
- Update description, author, homepage, etc.
|
||||
|
||||
### manager.py
|
||||
|
||||
Replace placeholders:
|
||||
- `PluginClassName` → `MyPlugin` (must match manifest)
|
||||
- Implement `_fetch_data()` method
|
||||
- Implement `_render_content()` method
|
||||
- Add any custom validation in `validate_config()`
|
||||
|
||||
### config_schema.json
|
||||
|
||||
Customize:
|
||||
- Update description
|
||||
- Add/remove configuration properties
|
||||
- Set default values
|
||||
- Add validation rules
|
||||
|
||||
### README.md
|
||||
|
||||
Replace placeholders:
|
||||
- `PLUGIN_ID` → `my-plugin`
|
||||
- `Plugin Name` → Your plugin's name
|
||||
- Fill in features, installation, configuration sections
|
||||
|
||||
### requirements.txt
|
||||
|
||||
Add your plugin's dependencies:
|
||||
```txt
|
||||
requests>=2.28.0
|
||||
pillow>=9.0.0
|
||||
```
|
||||
|
||||
## Step 4: Enable Plugin
|
||||
|
||||
Edit `config/config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"my-plugin": {
|
||||
"enabled": true,
|
||||
"display_duration": 15
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Step 5: Test Plugin
|
||||
|
||||
### Test with Emulator
|
||||
|
||||
```bash
|
||||
cd /path/to/LEDMatrix
|
||||
python run.py --emulator
|
||||
```
|
||||
|
||||
### Check Plugin Loading
|
||||
|
||||
Look for logs like:
|
||||
```
|
||||
[INFO] Discovered 1 plugin(s)
|
||||
[INFO] Loaded plugin: my-plugin v1.0.0
|
||||
[INFO] Added plugin mode: my-plugin
|
||||
```
|
||||
|
||||
### Test Plugin Display
|
||||
|
||||
The plugin should appear in the display rotation. Check logs for any errors.
|
||||
|
||||
## Step 6: Develop and Iterate
|
||||
|
||||
1. Edit `manager.py` to implement your plugin logic
|
||||
2. Test with emulator: `python run.py --emulator`
|
||||
3. Check logs for errors
|
||||
4. Iterate until working correctly
|
||||
|
||||
## Step 7: Test on Hardware (Optional)
|
||||
|
||||
When ready, test on Raspberry Pi:
|
||||
|
||||
```bash
|
||||
# Deploy to Pi
|
||||
rsync -avz plugins/my-plugin/ pi@raspberrypi:/path/to/LEDMatrix/plugins/my-plugin/
|
||||
|
||||
# Or if using git
|
||||
ssh pi@raspberrypi "cd /path/to/LEDMatrix/plugins/my-plugin && git pull"
|
||||
|
||||
# Restart service
|
||||
ssh pi@raspberrypi "sudo systemctl restart ledmatrix"
|
||||
```
|
||||
|
||||
## Common Customizations
|
||||
|
||||
### Adding API Integration
|
||||
|
||||
1. Add API key to `config_schema.json`:
|
||||
```json
|
||||
{
|
||||
"api_key": {
|
||||
"type": "string",
|
||||
"description": "API key for service"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. Implement API call in `_fetch_data()`:
|
||||
```python
|
||||
import requests
|
||||
|
||||
def _fetch_data(self):
|
||||
response = requests.get(
|
||||
"https://api.example.com/data",
|
||||
headers={"Authorization": f"Bearer {self.api_key}"}
|
||||
)
|
||||
return response.json()
|
||||
```
|
||||
|
||||
3. Store API key in `config/config_secrets.json`:
|
||||
```json
|
||||
{
|
||||
"my-plugin": {
|
||||
"api_key": "your-secret-key"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Image Rendering
|
||||
|
||||
There is no `draw_image()` helper on `DisplayManager`. To render an
|
||||
image, paste it directly onto the underlying PIL `Image`
|
||||
(`display_manager.image`) and then call `update_display()`:
|
||||
|
||||
```python
|
||||
def _render_content(self):
|
||||
# Load and paste image onto the display canvas
|
||||
image = Image.open("assets/logo.png").convert("RGB")
|
||||
self.display_manager.image.paste(image, (0, 0))
|
||||
|
||||
# Draw text overlay
|
||||
self.display_manager.draw_text(
|
||||
"Text",
|
||||
x=10, y=20,
|
||||
color=(255, 255, 255)
|
||||
)
|
||||
|
||||
self.display_manager.update_display()
|
||||
```
|
||||
|
||||
For transparency, paste with a mask:
|
||||
|
||||
```python
|
||||
icon = Image.open("assets/icon.png").convert("RGBA")
|
||||
self.display_manager.image.paste(icon, (5, 5), icon)
|
||||
```
|
||||
|
||||
|
||||
### Adding Live Priority
|
||||
|
||||
1. Enable in config:
|
||||
```json
|
||||
{
|
||||
"my-plugin": {
|
||||
"live_priority": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. Implement `has_live_content()`:
|
||||
```python
|
||||
def has_live_content(self) -> bool:
|
||||
return self.data and self.data.get("is_live", False)
|
||||
```
|
||||
|
||||
3. Override `get_live_modes()` if needed:
|
||||
```python
|
||||
def get_live_modes(self) -> list:
|
||||
return ["my_plugin_live_mode"]
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Plugin Not Loading
|
||||
|
||||
- Check `manifest.json` syntax (must be valid JSON)
|
||||
- Verify `entry_point` file exists
|
||||
- Ensure `class_name` matches class name in manager.py
|
||||
- Check for import errors in logs
|
||||
|
||||
### Configuration Errors
|
||||
|
||||
- Validate config against `config_schema.json`
|
||||
- Check required fields are present
|
||||
- Verify data types match schema
|
||||
|
||||
### Display Issues
|
||||
|
||||
- Check display dimensions: `display_manager.width`, `display_manager.height`
|
||||
- Verify coordinates are within bounds
|
||||
- Ensure `update_display()` is called
|
||||
- Test with emulator first
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Review existing plugins for patterns:
|
||||
- `plugins/hockey-scoreboard/` - Sports scoreboard example
|
||||
- `plugins/ledmatrix-music/` - Real-time data example
|
||||
- `plugins/ledmatrix-stocks/` - Data display example
|
||||
|
||||
- Read full documentation:
|
||||
- `.cursor/plugins_guide.md` - Comprehensive guide
|
||||
- `docs/PLUGIN_ARCHITECTURE_SPEC.md` - Architecture details
|
||||
- `.cursorrules` - Development rules
|
||||
|
||||
- Check plugin system code:
|
||||
- `src/plugin_system/base_plugin.py` - Base class
|
||||
- `src/plugin_system/plugin_manager.py` - Plugin manager
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
# Plugin Name
|
||||
|
||||
Brief description of what this plugin does.
|
||||
|
||||
## Features
|
||||
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
- Feature 3
|
||||
|
||||
## Installation
|
||||
|
||||
1. Link the plugin to your LEDMatrix installation:
|
||||
|
||||
```bash
|
||||
cd /path/to/LEDMatrix
|
||||
./scripts/dev/dev_plugin_setup.sh link-github PLUGIN_ID
|
||||
```
|
||||
|
||||
Or for local development:
|
||||
|
||||
```bash
|
||||
./scripts/dev/dev_plugin_setup.sh link PLUGIN_ID /path/to/plugin/repo
|
||||
```
|
||||
|
||||
2. Install dependencies:
|
||||
|
||||
```bash
|
||||
pip install -r plugins/PLUGIN_ID/requirements.txt
|
||||
```
|
||||
|
||||
3. Configure the plugin in `config/config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"PLUGIN_ID": {
|
||||
"enabled": true,
|
||||
"display_duration": 15
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** API keys and other sensitive credentials must be stored in `config/config_secrets.json`, not in `config/config.json`.
|
||||
|
||||
4. Store API keys in `config/config_secrets.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"PLUGIN_ID": {
|
||||
"api_key": "your-secret-api-key"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Required Settings
|
||||
|
||||
- `enabled` (boolean): Enable or disable the plugin
|
||||
- `api_key` (string): API key for external service (if required)
|
||||
|
||||
### Optional Settings
|
||||
|
||||
- `display_duration` (number): How long to display this plugin (default: 15 seconds)
|
||||
- `refresh_interval` (integer): How often to refresh data in seconds (default: 60)
|
||||
- `live_priority` (boolean): Enable live priority takeover (default: false)
|
||||
|
||||
## Display Modes
|
||||
|
||||
This plugin provides the following display modes:
|
||||
|
||||
- `PLUGIN_ID`: Main display mode
|
||||
|
||||
## API Requirements
|
||||
|
||||
This plugin requires:
|
||||
|
||||
- **API Name**: Description of API requirements
|
||||
- URL: https://api.example.com
|
||||
- Rate Limit: X requests per minute
|
||||
- Authentication: API key required
|
||||
|
||||
## Development
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
cd plugins/PLUGIN_ID
|
||||
python test_PLUGIN_ID.py
|
||||
```
|
||||
|
||||
### Testing with Emulator
|
||||
|
||||
```bash
|
||||
cd /path/to/LEDMatrix
|
||||
python run.py --emulator
|
||||
```
|
||||
|
||||
### Debugging
|
||||
|
||||
Enable debug logging in `config/config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"logging": {
|
||||
"level": "DEBUG"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Check logs:
|
||||
|
||||
```bash
|
||||
# On Raspberry Pi (if running as service)
|
||||
journalctl -u ledmatrix -f
|
||||
|
||||
# Direct execution
|
||||
python run.py
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Plugin Not Loading
|
||||
|
||||
1. Check that `manifest.json` exists and is valid
|
||||
2. Verify `entry_point` file exists
|
||||
3. Check that `class_name` matches the class in manager.py
|
||||
4. Review logs for import errors
|
||||
|
||||
### Configuration Errors
|
||||
|
||||
1. Validate config against `config_schema.json`
|
||||
2. Check required fields are present
|
||||
3. Verify data types match schema
|
||||
|
||||
### API Errors
|
||||
|
||||
1. Verify API key is correct
|
||||
2. Check API rate limits
|
||||
3. Review network connectivity
|
||||
4. Check API service status
|
||||
|
||||
## License
|
||||
|
||||
[License information]
|
||||
|
||||
## Author
|
||||
|
||||
Your Name
|
||||
|
||||
## Links
|
||||
|
||||
- GitHub: https://github.com/username/ledmatrix-PLUGIN_ID
|
||||
- Documentation: [Link to docs]
|
||||
- Issues: https://github.com/username/ledmatrix-PLUGIN_ID/issues
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"title": "Plugin Configuration Schema",
|
||||
"description": "Configuration schema for Plugin Name",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Enable or disable this plugin"
|
||||
},
|
||||
"display_duration": {
|
||||
"type": "number",
|
||||
"default": 15,
|
||||
"minimum": 1,
|
||||
"maximum": 300,
|
||||
"description": "How long to display this plugin in seconds"
|
||||
},
|
||||
"live_priority": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Enable live priority takeover when plugin has live content"
|
||||
},
|
||||
"refresh_interval": {
|
||||
"type": "integer",
|
||||
"default": 60,
|
||||
"minimum": 1,
|
||||
"description": "How often to refresh data in seconds"
|
||||
},
|
||||
"api_key": {
|
||||
"type": "string",
|
||||
"description": "API key for external service (store in config_secrets.json)",
|
||||
"default": ""
|
||||
},
|
||||
"custom_setting": {
|
||||
"type": "string",
|
||||
"description": "Example custom setting - replace with your plugin's settings",
|
||||
"default": "default_value"
|
||||
}
|
||||
},
|
||||
"required": ["enabled"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
|
||||
@@ -1,226 +0,0 @@
|
||||
"""
|
||||
Plugin Name
|
||||
|
||||
Brief description of what this plugin does.
|
||||
|
||||
API Version: 1.0.0
|
||||
"""
|
||||
|
||||
from src.plugin_system.base_plugin import BasePlugin
|
||||
from PIL import Image
|
||||
from typing import Dict, Any, Optional
|
||||
import logging
|
||||
import time
|
||||
|
||||
|
||||
class PluginClassName(BasePlugin):
|
||||
"""
|
||||
Plugin class that inherits from BasePlugin.
|
||||
|
||||
This plugin demonstrates the basic structure and common patterns
|
||||
for LEDMatrix plugins.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
plugin_id: str,
|
||||
config: Dict[str, Any],
|
||||
display_manager,
|
||||
cache_manager,
|
||||
plugin_manager,
|
||||
):
|
||||
"""Initialize the plugin."""
|
||||
super().__init__(plugin_id, config, display_manager, cache_manager, plugin_manager)
|
||||
|
||||
# Initialize plugin-specific data
|
||||
self.data = None
|
||||
self.last_update_time = None
|
||||
|
||||
# Load configuration values
|
||||
self.api_key = config.get("api_key", "")
|
||||
self.refresh_interval = config.get("refresh_interval", 60)
|
||||
|
||||
self.logger.info(f"Plugin {plugin_id} initialized")
|
||||
|
||||
def update(self) -> None:
|
||||
"""
|
||||
Fetch/update data for this plugin.
|
||||
|
||||
This method is called periodically based on update_interval
|
||||
specified in the manifest. Use cache_manager to avoid
|
||||
excessive API calls.
|
||||
"""
|
||||
cache_key = f"{self.plugin_id}_data"
|
||||
|
||||
# Check cache first
|
||||
cached = self.cache_manager.get(cache_key, max_age=self.refresh_interval)
|
||||
if cached:
|
||||
self.data = cached
|
||||
self.logger.debug("Using cached data")
|
||||
return
|
||||
|
||||
try:
|
||||
# Fetch new data
|
||||
self.data = self._fetch_data()
|
||||
|
||||
# Cache the data
|
||||
self.cache_manager.set(cache_key, self.data, ttl=self.refresh_interval)
|
||||
self.last_update_time = time.time()
|
||||
|
||||
self.logger.info("Data updated successfully")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to update data: {e}")
|
||||
# Use cached data if available, even if expired
|
||||
# Use a very large max_age (1 year) to effectively bypass expiration for fallback
|
||||
expired_cached = self.cache_manager.get(cache_key, max_age=31536000)
|
||||
if expired_cached:
|
||||
self.data = expired_cached
|
||||
self.logger.warning("Using expired cache due to update failure")
|
||||
|
||||
def display(self, force_clear: bool = False) -> None:
|
||||
"""
|
||||
Render this plugin's display.
|
||||
|
||||
Args:
|
||||
force_clear: If True, clear display before rendering
|
||||
"""
|
||||
if force_clear:
|
||||
self.display_manager.clear()
|
||||
|
||||
# Check if we have data to display
|
||||
if not self.data:
|
||||
self._display_error("No data available")
|
||||
return
|
||||
|
||||
try:
|
||||
# Render plugin content
|
||||
self._render_content()
|
||||
|
||||
# Update the display
|
||||
self.display_manager.update_display()
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Display error: {e}")
|
||||
self._display_error("Display error")
|
||||
|
||||
def _fetch_data(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Fetch data from external source.
|
||||
|
||||
Returns:
|
||||
Dictionary containing fetched data
|
||||
"""
|
||||
# TODO: Implement data fetching logic
|
||||
# Example:
|
||||
# import requests
|
||||
# response = requests.get("https://api.example.com/data",
|
||||
# headers={"Authorization": f"Bearer {self.api_key}"})
|
||||
# return response.json()
|
||||
|
||||
# Placeholder
|
||||
return {
|
||||
"message": "Hello, World!",
|
||||
"timestamp": time.time()
|
||||
}
|
||||
|
||||
def _render_content(self) -> None:
|
||||
"""Render the plugin content on the display."""
|
||||
# Get display dimensions
|
||||
width = self.display_manager.width
|
||||
height = self.display_manager.height
|
||||
|
||||
# Example: Draw text
|
||||
text = self.data.get("message", "No data")
|
||||
x = 5
|
||||
y = height // 2
|
||||
|
||||
self.display_manager.draw_text(
|
||||
text,
|
||||
x=x,
|
||||
y=y,
|
||||
color=(255, 255, 255) # White
|
||||
)
|
||||
|
||||
# Example: Draw image
|
||||
# if hasattr(self, 'logo_image'):
|
||||
# self.display_manager.draw_image(
|
||||
# self.logo_image,
|
||||
# x=0,
|
||||
# y=0
|
||||
# )
|
||||
|
||||
def _display_error(self, message: str) -> None:
|
||||
"""Display an error message."""
|
||||
self.display_manager.clear()
|
||||
width = self.display_manager.width
|
||||
height = self.display_manager.height
|
||||
|
||||
self.display_manager.draw_text(
|
||||
message,
|
||||
x=5,
|
||||
y=height // 2,
|
||||
color=(255, 0, 0) # Red
|
||||
)
|
||||
self.display_manager.update_display()
|
||||
|
||||
def validate_config(self) -> bool:
|
||||
"""
|
||||
Validate plugin configuration.
|
||||
|
||||
Returns:
|
||||
True if config is valid, False otherwise
|
||||
"""
|
||||
# Call parent validation first
|
||||
if not super().validate_config():
|
||||
return False
|
||||
|
||||
# Add custom validation
|
||||
# Example: Check for required API key
|
||||
# if self.config.get("require_api_key", True):
|
||||
# if not self.api_key:
|
||||
# self.logger.error("API key is required but not provided")
|
||||
# return False
|
||||
|
||||
return True
|
||||
|
||||
def has_live_content(self) -> bool:
|
||||
"""
|
||||
Check if plugin has live content to display.
|
||||
|
||||
Override this method to enable live priority features.
|
||||
|
||||
Returns:
|
||||
True if plugin has live content, False otherwise
|
||||
"""
|
||||
# Example: Check if there's live data
|
||||
# return self.data and self.data.get("is_live", False)
|
||||
return False
|
||||
|
||||
def get_info(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Return plugin info for display in web UI.
|
||||
|
||||
Returns:
|
||||
Dictionary with plugin information
|
||||
"""
|
||||
info = super().get_info()
|
||||
|
||||
# Add plugin-specific info
|
||||
info.update({
|
||||
"data_available": self.data is not None,
|
||||
"last_update": self.last_update_time,
|
||||
# Add more info as needed
|
||||
})
|
||||
|
||||
return info
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""Cleanup resources when plugin is unloaded."""
|
||||
# Clean up any resources (threads, connections, etc.)
|
||||
# Example:
|
||||
# if hasattr(self, 'api_client'):
|
||||
# self.api_client.close()
|
||||
|
||||
super().cleanup()
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
{
|
||||
"id": "PLUGIN_ID",
|
||||
"name": "Plugin Name",
|
||||
"version": "1.0.0",
|
||||
"author": "Your Name",
|
||||
"description": "Brief description of what this plugin does",
|
||||
"homepage": "https://github.com/username/ledmatrix-PLUGIN_ID",
|
||||
"entry_point": "manager.py",
|
||||
"class_name": "PluginClassName",
|
||||
"category": "custom",
|
||||
"tags": ["custom", "example"],
|
||||
"icon": "fas fa-icon-name",
|
||||
"compatible_versions": [">=2.0.0"],
|
||||
"min_ledmatrix_version": "2.0.0",
|
||||
"max_ledmatrix_version": "3.0.0",
|
||||
"requires": {
|
||||
"python": ">=3.9",
|
||||
"display_size": {
|
||||
"min_width": 64,
|
||||
"min_height": 32
|
||||
}
|
||||
},
|
||||
"config_schema": "config_schema.json",
|
||||
"assets": {
|
||||
"logos": "Optional: Description of asset requirements"
|
||||
},
|
||||
"update_interval": 60,
|
||||
"default_duration": 15,
|
||||
"display_modes": [
|
||||
"PLUGIN_ID"
|
||||
],
|
||||
"api_requirements": [
|
||||
{
|
||||
"name": "API Name",
|
||||
"required": false,
|
||||
"description": "Description of API requirements",
|
||||
"url": "https://api.example.com",
|
||||
"rate_limit": "Rate limit information"
|
||||
}
|
||||
],
|
||||
"download_url_template": "https://github.com/username/ledmatrix-PLUGIN_ID/archive/refs/tags/v{version}.zip",
|
||||
"versions": [
|
||||
{
|
||||
"released": "2025-01-01",
|
||||
"version": "1.0.0",
|
||||
"ledmatrix_min_version": "2.0.0"
|
||||
}
|
||||
],
|
||||
"last_updated": "2025-01-01",
|
||||
"stars": 0,
|
||||
"downloads": 0,
|
||||
"verified": false,
|
||||
"screenshot": ""
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
# Plugin Dependencies
|
||||
# Add your plugin's Python dependencies here
|
||||
|
||||
# Example dependencies (uncomment and modify as needed):
|
||||
# requests>=2.28.0
|
||||
# pillow>=9.0.0
|
||||
# python-dateutil>=2.8.0
|
||||
|
||||
# Note: Core LEDMatrix dependencies are already available:
|
||||
# - PIL/Pillow (for image handling)
|
||||
# - Core plugin system classes
|
||||
# - Display manager, cache manager, config manager
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
"""
|
||||
Test file for Plugin Name plugin.
|
||||
|
||||
This file provides example unit tests for your plugin.
|
||||
Run tests with: python -m pytest test_manager.py
|
||||
Or: python test_manager.py
|
||||
"""
|
||||
|
||||
import unittest
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add project root to path
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from src.plugin_system.testing import PluginTestCase
|
||||
from manager import PluginClassName
|
||||
|
||||
|
||||
class TestPluginClassName(PluginTestCase):
|
||||
"""Test cases for PluginClassName plugin."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
super().setUp()
|
||||
|
||||
# Update plugin_id to match the plugin being tested
|
||||
self.plugin_id = 'PLUGIN_ID'
|
||||
|
||||
# Create plugin instance
|
||||
self.plugin = self.create_plugin_instance(
|
||||
PluginClassName,
|
||||
plugin_id='PLUGIN_ID',
|
||||
config=self.get_mock_config()
|
||||
)
|
||||
|
||||
def test_plugin_initialization(self):
|
||||
"""Test that plugin initializes correctly."""
|
||||
self.assert_plugin_initialized(self.plugin)
|
||||
self.assertTrue(self.plugin.enabled)
|
||||
|
||||
def test_config_validation(self):
|
||||
"""Test configuration validation."""
|
||||
# Valid config should pass
|
||||
self.assertTrue(self.plugin.validate_config())
|
||||
|
||||
# Test with invalid config if applicable
|
||||
# invalid_config = self.get_mock_config(enabled='not-a-boolean')
|
||||
# invalid_plugin = self.create_plugin_instance(
|
||||
# PluginClassName,
|
||||
# config=invalid_config
|
||||
# )
|
||||
# self.assertFalse(invalid_plugin.validate_config())
|
||||
|
||||
def test_update_method(self):
|
||||
"""Test the update() method."""
|
||||
# Reset mocks
|
||||
self.cache_manager.reset()
|
||||
|
||||
# Call update
|
||||
self.plugin.update()
|
||||
|
||||
# Assertions
|
||||
# Example: Check that cache was used
|
||||
# self.assert_cache_get('PLUGIN_ID_data')
|
||||
|
||||
# Example: Check that data was fetched and cached
|
||||
# self.assert_cache_set('PLUGIN_ID_data')
|
||||
|
||||
def test_display_method(self):
|
||||
"""Test the display() method."""
|
||||
# Ensure plugin has data (call update first if needed)
|
||||
# self.plugin.update()
|
||||
|
||||
# Call display
|
||||
self.plugin.display(force_clear=True)
|
||||
|
||||
# Assertions
|
||||
self.assert_display_cleared()
|
||||
self.assert_display_updated()
|
||||
|
||||
# Example: Check that text was drawn
|
||||
# self.assert_text_drawn("Expected Text")
|
||||
|
||||
# Example: Check that image was drawn
|
||||
# self.assert_image_drawn()
|
||||
|
||||
def test_display_without_data(self):
|
||||
"""Test display() behavior when no data is available."""
|
||||
# Clear any cached data
|
||||
self.cache_manager.reset()
|
||||
|
||||
# Call display
|
||||
self.plugin.display()
|
||||
|
||||
# Should handle gracefully (no exceptions)
|
||||
# May show error message or fallback content
|
||||
self.assert_display_updated()
|
||||
|
||||
def test_get_display_duration(self):
|
||||
"""Test display duration configuration."""
|
||||
duration = self.plugin.get_display_duration()
|
||||
self.assertIsInstance(duration, (int, float))
|
||||
self.assertGreater(duration, 0)
|
||||
|
||||
# Test with custom duration
|
||||
custom_config = self.get_mock_config(display_duration=30.0)
|
||||
custom_plugin = self.create_plugin_instance(
|
||||
PluginClassName,
|
||||
config=custom_config
|
||||
)
|
||||
self.assertEqual(custom_plugin.get_display_duration(), 30.0)
|
||||
|
||||
def test_enable_disable(self):
|
||||
"""Test plugin enable/disable functionality."""
|
||||
self.assertTrue(self.plugin.enabled)
|
||||
|
||||
self.plugin.on_disable()
|
||||
self.assertFalse(self.plugin.enabled)
|
||||
|
||||
self.plugin.on_enable()
|
||||
self.assertTrue(self.plugin.enabled)
|
||||
|
||||
def test_config_change(self):
|
||||
"""Test configuration change handling."""
|
||||
new_config = self.get_mock_config(display_duration=20.0)
|
||||
self.plugin.on_config_change(new_config)
|
||||
|
||||
self.assertEqual(self.plugin.config.get('display_duration'), 20.0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -1,751 +0,0 @@
|
||||
# LEDMatrix Plugin Development Guide
|
||||
|
||||
This guide provides comprehensive instructions for creating, running, and loading plugins in the LEDMatrix project.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Plugin System Overview](#plugin-system-overview)
|
||||
2. [Creating a New Plugin](#creating-a-new-plugin)
|
||||
3. [Running Plugins](#running-plugins)
|
||||
4. [Loading Plugins](#loading-plugins)
|
||||
5. [Plugin Development Workflow](#plugin-development-workflow)
|
||||
6. [Testing Plugins](#testing-plugins)
|
||||
7. [Troubleshooting](#troubleshooting)
|
||||
|
||||
---
|
||||
|
||||
## Plugin System Overview
|
||||
|
||||
The LEDMatrix project uses a plugin-based architecture where all display functionality (except core calendar) is implemented as plugins. Plugins are dynamically loaded from the `plugins/` directory and integrated into the display rotation.
|
||||
|
||||
### Plugin Architecture
|
||||
|
||||
```
|
||||
LEDMatrix Core
|
||||
├── Plugin Manager (discovers, loads, manages plugins)
|
||||
├── Display Manager (handles LED matrix rendering)
|
||||
├── Cache Manager (data persistence)
|
||||
├── Config Manager (configuration management)
|
||||
└── Plugins/ (plugin directory)
|
||||
├── plugin-1/
|
||||
├── plugin-2/
|
||||
└── ...
|
||||
```
|
||||
|
||||
### Plugin Lifecycle
|
||||
|
||||
1. **Discovery**: PluginManager scans `plugins/` for directories with `manifest.json`
|
||||
2. **Loading**: Plugin module is imported and class is instantiated
|
||||
3. **Configuration**: Plugin config is loaded from `config/config.json`
|
||||
4. **Validation**: `validate_config()` is called to verify configuration
|
||||
5. **Registration**: Plugin is added to available display modes
|
||||
6. **Execution**: `update()` is called periodically, `display()` is called during rotation
|
||||
|
||||
---
|
||||
|
||||
## Creating a New Plugin
|
||||
|
||||
### Method 1: Using dev_plugin_setup.sh (Recommended)
|
||||
|
||||
This method is best for plugins stored in separate Git repositories.
|
||||
|
||||
#### From GitHub Repository
|
||||
|
||||
```bash
|
||||
# Link a plugin from GitHub (auto-detects URL)
|
||||
./scripts/dev/dev_plugin_setup.sh link-github <plugin-name>
|
||||
|
||||
# Example: Link hockey-scoreboard plugin
|
||||
./scripts/dev/dev_plugin_setup.sh link-github hockey-scoreboard
|
||||
|
||||
# With custom URL
|
||||
./scripts/dev/dev_plugin_setup.sh link-github <plugin-name> https://github.com/user/repo.git
|
||||
```
|
||||
|
||||
The script will:
|
||||
- Clone the repository to `~/.ledmatrix-dev-plugins/` (or configured directory)
|
||||
- Create a symlink in `plugins/<plugin-name>/` pointing to the cloned repo
|
||||
- Validate the plugin structure
|
||||
|
||||
#### From Local Repository
|
||||
|
||||
```bash
|
||||
# Link a local plugin repository
|
||||
./scripts/dev/dev_plugin_setup.sh link <plugin-name> <path-to-repo>
|
||||
|
||||
# Example: Link a local plugin
|
||||
./scripts/dev/dev_plugin_setup.sh link my-plugin ../ledmatrix-my-plugin
|
||||
```
|
||||
|
||||
### Method 2: Manual Plugin Creation
|
||||
|
||||
1. **Create Plugin Directory**
|
||||
|
||||
```bash
|
||||
mkdir -p plugins/my-plugin
|
||||
cd plugins/my-plugin
|
||||
```
|
||||
|
||||
2. **Create manifest.json**
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-plugin",
|
||||
"name": "My Plugin",
|
||||
"version": "1.0.0",
|
||||
"author": "Your Name",
|
||||
"description": "Description of what this plugin does",
|
||||
"entry_point": "manager.py",
|
||||
"class_name": "MyPlugin",
|
||||
"category": "custom",
|
||||
"tags": ["custom", "example"],
|
||||
"display_modes": ["my_plugin"],
|
||||
"update_interval": 60,
|
||||
"default_duration": 15,
|
||||
"requires": {
|
||||
"python": ">=3.9"
|
||||
},
|
||||
"config_schema": "config_schema.json"
|
||||
}
|
||||
```
|
||||
|
||||
3. **Create manager.py**
|
||||
|
||||
```python
|
||||
from src.plugin_system.base_plugin import BasePlugin
|
||||
from PIL import Image
|
||||
import logging
|
||||
|
||||
class MyPlugin(BasePlugin):
|
||||
"""My custom plugin implementation."""
|
||||
|
||||
def update(self):
|
||||
"""Fetch/update data for this plugin."""
|
||||
# Fetch data from API, files, etc.
|
||||
# Use self.cache_manager for caching
|
||||
cache_key = f"{self.plugin_id}_data"
|
||||
cached = self.cache_manager.get(cache_key, max_age=3600)
|
||||
if cached:
|
||||
self.data = cached
|
||||
return
|
||||
|
||||
# Fetch new data
|
||||
self.data = self._fetch_data()
|
||||
self.cache_manager.set(cache_key, self.data)
|
||||
|
||||
def display(self, force_clear=False):
|
||||
"""Render this plugin's display."""
|
||||
if force_clear:
|
||||
self.display_manager.clear()
|
||||
|
||||
# Render content using display_manager
|
||||
self.display_manager.draw_text(
|
||||
"Hello, World!",
|
||||
x=10, y=15,
|
||||
color=(255, 255, 255)
|
||||
)
|
||||
|
||||
self.display_manager.update_display()
|
||||
|
||||
def _fetch_data(self):
|
||||
"""Fetch data from external source."""
|
||||
# Implement your data fetching logic
|
||||
return {"message": "Hello, World!"}
|
||||
|
||||
def validate_config(self):
|
||||
"""Validate plugin configuration."""
|
||||
# Check required config fields
|
||||
if not super().validate_config():
|
||||
return False
|
||||
|
||||
# Add custom validation
|
||||
required_fields = ['api_key'] # Example
|
||||
for field in required_fields:
|
||||
if field not in self.config:
|
||||
self.logger.error(f"Missing required field: {field}")
|
||||
return False
|
||||
|
||||
return True
|
||||
```
|
||||
|
||||
4. **Create config_schema.json**
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Enable or disable this plugin"
|
||||
},
|
||||
"display_duration": {
|
||||
"type": "number",
|
||||
"default": 15,
|
||||
"minimum": 1,
|
||||
"description": "How long to display this plugin (seconds)"
|
||||
},
|
||||
"api_key": {
|
||||
"type": "string",
|
||||
"description": "API key for external service"
|
||||
}
|
||||
},
|
||||
"required": ["enabled"]
|
||||
}
|
||||
```
|
||||
|
||||
5. **Create requirements.txt** (if needed)
|
||||
|
||||
```
|
||||
requests>=2.28.0
|
||||
pillow>=9.0.0
|
||||
```
|
||||
|
||||
6. **Create README.md**
|
||||
|
||||
Document your plugin's functionality, configuration options, and usage.
|
||||
|
||||
---
|
||||
|
||||
## Running Plugins
|
||||
|
||||
### Development Mode (Emulator)
|
||||
|
||||
Run the LEDMatrix system with emulator for plugin testing:
|
||||
|
||||
```bash
|
||||
# Using run.py
|
||||
python run.py --emulator
|
||||
|
||||
# Using emulator script
|
||||
./run_emulator.sh
|
||||
```
|
||||
|
||||
The emulator will:
|
||||
- Load all enabled plugins
|
||||
- Display plugin content in a window (simulating LED matrix)
|
||||
- Show logs for plugin loading and execution
|
||||
- Allow testing without Raspberry Pi hardware
|
||||
|
||||
### Production Mode (Raspberry Pi)
|
||||
|
||||
Run on actual Raspberry Pi hardware:
|
||||
|
||||
```bash
|
||||
# Direct execution
|
||||
python run.py
|
||||
|
||||
# As systemd service
|
||||
sudo systemctl start ledmatrix
|
||||
sudo systemctl status ledmatrix
|
||||
sudo journalctl -u ledmatrix -f # View logs
|
||||
```
|
||||
|
||||
### Plugin-Specific Testing
|
||||
|
||||
Test individual plugin loading:
|
||||
|
||||
```python
|
||||
# test_my_plugin.py
|
||||
from src.plugin_system.plugin_manager import PluginManager
|
||||
from src.config_manager import ConfigManager
|
||||
from src.display_manager import DisplayManager
|
||||
from src.cache_manager import CacheManager
|
||||
|
||||
# Initialize managers
|
||||
config_manager = ConfigManager()
|
||||
config = config_manager.load_config()
|
||||
display_manager = DisplayManager(config)
|
||||
cache_manager = CacheManager()
|
||||
|
||||
# Initialize plugin manager
|
||||
plugin_manager = PluginManager(
|
||||
plugins_dir="plugins",
|
||||
config_manager=config_manager,
|
||||
display_manager=display_manager,
|
||||
cache_manager=cache_manager
|
||||
)
|
||||
|
||||
# Discover and load plugin
|
||||
plugins = plugin_manager.discover_plugins()
|
||||
print(f"Discovered plugins: {plugins}")
|
||||
|
||||
if "my-plugin" in plugins:
|
||||
if plugin_manager.load_plugin("my-plugin"):
|
||||
plugin = plugin_manager.get_plugin("my-plugin")
|
||||
plugin.update()
|
||||
plugin.display()
|
||||
print("Plugin loaded and displayed successfully!")
|
||||
else:
|
||||
print("Failed to load plugin")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Loading Plugins
|
||||
|
||||
### Enabling Plugins
|
||||
|
||||
Plugins are enabled/disabled in `config/config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"my-plugin": {
|
||||
"enabled": true,
|
||||
"display_duration": 15,
|
||||
"api_key": "your-api-key-here"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Plugin Configuration Structure
|
||||
|
||||
Each plugin has its own section in `config/config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"<plugin-id>": {
|
||||
"enabled": true, // Enable/disable plugin
|
||||
"display_duration": 15, // Display duration in seconds
|
||||
"live_priority": false, // Enable live priority takeover
|
||||
"high_performance_transitions": false, // Use 120 FPS transitions
|
||||
"transition": { // Transition configuration
|
||||
"type": "redraw", // Transition type
|
||||
"speed": 2, // Transition speed
|
||||
"enabled": true // Enable transitions
|
||||
},
|
||||
// ... plugin-specific configuration
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Secrets Management
|
||||
|
||||
Store sensitive data (API keys, tokens) in `config/config_secrets.json`
|
||||
under the same plugin id you use in `config/config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"my-plugin": {
|
||||
"api_key": "secret-api-key-here"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
At load time, the config manager deep-merges `config_secrets.json` into
|
||||
the main config (verified at `src/config_manager.py:162-172`). So in
|
||||
your plugin's code:
|
||||
|
||||
```python
|
||||
class MyPlugin(BasePlugin):
|
||||
def __init__(self, plugin_id, config, display_manager, cache_manager, plugin_manager):
|
||||
super().__init__(plugin_id, config, display_manager, cache_manager, plugin_manager)
|
||||
self.api_key = config.get("api_key") # already merged from secrets
|
||||
```
|
||||
|
||||
There is no separate `config_secrets` reference field — just put the
|
||||
secret value under the same plugin namespace and read it from the
|
||||
merged config.
|
||||
|
||||
### Plugin Discovery
|
||||
|
||||
Plugins are automatically discovered when:
|
||||
- Directory exists in `plugins/`
|
||||
- Directory contains `manifest.json`
|
||||
- Manifest has required fields (`id`, `entry_point`, `class_name`)
|
||||
|
||||
Check discovered plugins:
|
||||
|
||||
```bash
|
||||
# Using dev_plugin_setup.sh
|
||||
./scripts/dev/dev_plugin_setup.sh list
|
||||
|
||||
# Output shows:
|
||||
# ✓ plugin-name (symlink)
|
||||
# → /path/to/repo
|
||||
# ✓ Git repo is clean (branch: main)
|
||||
```
|
||||
|
||||
### Plugin Status
|
||||
|
||||
Check plugin status and git information:
|
||||
|
||||
```bash
|
||||
./scripts/dev/dev_plugin_setup.sh status
|
||||
|
||||
# Output shows:
|
||||
# ✓ plugin-name
|
||||
# Path: /path/to/repo
|
||||
# Branch: main
|
||||
# Remote: https://github.com/user/repo.git
|
||||
# Status: Clean and up to date
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Plugin Development Workflow
|
||||
|
||||
### 1. Initial Setup
|
||||
|
||||
```bash
|
||||
# Create or clone plugin repository
|
||||
git clone https://github.com/user/ledmatrix-my-plugin.git
|
||||
cd ledmatrix-my-plugin
|
||||
|
||||
# Link to LEDMatrix project
|
||||
cd /path/to/LEDMatrix
|
||||
./scripts/dev/dev_plugin_setup.sh link my-plugin ../ledmatrix-my-plugin
|
||||
```
|
||||
|
||||
### 2. Development Cycle
|
||||
|
||||
1. **Edit plugin code** in linked repository
|
||||
2. **Test with the dev preview server**:
|
||||
`python3 scripts/dev_server.py` (then open `http://localhost:5001`).
|
||||
Or run the full display in emulator mode with
|
||||
`python3 run.py --emulator` (or equivalently
|
||||
`EMULATOR=true python3 run.py`). The `-e`/`--emulator` CLI flag is
|
||||
defined in `run.py:19-20` and sets the same `EMULATOR` environment
|
||||
variable internally.
|
||||
3. **Check logs** for errors or warnings
|
||||
4. **Update configuration** in `config/config.json` if needed
|
||||
5. **Iterate** until plugin works correctly
|
||||
|
||||
### 3. Testing on Hardware
|
||||
|
||||
```bash
|
||||
# Deploy to Raspberry Pi
|
||||
rsync -avz plugins/my-plugin/ ledpi@your-pi-ip:/path/to/LEDMatrix/plugins/my-plugin/
|
||||
|
||||
# Or if using git, pull on Pi
|
||||
ssh ledpi@your-pi-ip "cd /path/to/LEDMatrix/plugins/my-plugin && git pull"
|
||||
|
||||
# Restart service
|
||||
ssh ledpi@your-pi-ip "sudo systemctl restart ledmatrix"
|
||||
```
|
||||
|
||||
### 4. Updating Plugins
|
||||
|
||||
```bash
|
||||
# Update single plugin from git
|
||||
./scripts/dev/dev_plugin_setup.sh update my-plugin
|
||||
|
||||
# Update all linked plugins
|
||||
./scripts/dev/dev_plugin_setup.sh update
|
||||
```
|
||||
|
||||
### 5. Unlinking Plugins
|
||||
|
||||
```bash
|
||||
# Remove symlink (preserves repository)
|
||||
./scripts/dev/dev_plugin_setup.sh unlink my-plugin
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing Plugins
|
||||
|
||||
### Unit Testing
|
||||
|
||||
Create test files in plugin directory:
|
||||
|
||||
```python
|
||||
# plugins/my-plugin/test_my_plugin.py
|
||||
import unittest
|
||||
from unittest.mock import Mock, MagicMock
|
||||
from manager import MyPlugin
|
||||
|
||||
class TestMyPlugin(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.config = {"enabled": True}
|
||||
self.display_manager = Mock()
|
||||
self.cache_manager = Mock()
|
||||
self.plugin_manager = Mock()
|
||||
|
||||
self.plugin = MyPlugin(
|
||||
plugin_id="my-plugin",
|
||||
config=self.config,
|
||||
display_manager=self.display_manager,
|
||||
cache_manager=self.cache_manager,
|
||||
plugin_manager=self.plugin_manager
|
||||
)
|
||||
|
||||
def test_plugin_initialization(self):
|
||||
self.assertEqual(self.plugin.plugin_id, "my-plugin")
|
||||
self.assertTrue(self.plugin.enabled)
|
||||
|
||||
def test_config_validation(self):
|
||||
self.assertTrue(self.plugin.validate_config())
|
||||
|
||||
def test_update(self):
|
||||
self.cache_manager.get.return_value = None
|
||||
self.plugin.update()
|
||||
# Assert data was fetched and cached
|
||||
|
||||
def test_display(self):
|
||||
self.plugin.display()
|
||||
self.display_manager.draw_text.assert_called()
|
||||
self.display_manager.update_display.assert_called()
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
```
|
||||
|
||||
Run tests:
|
||||
|
||||
```bash
|
||||
cd plugins/my-plugin
|
||||
python -m pytest test_my_plugin.py
|
||||
# or
|
||||
python test_my_plugin.py
|
||||
```
|
||||
|
||||
### Integration Testing
|
||||
|
||||
Test plugin with actual managers:
|
||||
|
||||
```python
|
||||
# test_plugin_integration.py
|
||||
from src.plugin_system.plugin_manager import PluginManager
|
||||
from src.config_manager import ConfigManager
|
||||
from src.display_manager import DisplayManager
|
||||
from src.cache_manager import CacheManager
|
||||
|
||||
def test_plugin_loading():
|
||||
config_manager = ConfigManager()
|
||||
config = config_manager.load_config()
|
||||
display_manager = DisplayManager(config)
|
||||
cache_manager = CacheManager()
|
||||
|
||||
plugin_manager = PluginManager(
|
||||
plugins_dir="plugins",
|
||||
config_manager=config_manager,
|
||||
display_manager=display_manager,
|
||||
cache_manager=cache_manager
|
||||
)
|
||||
|
||||
plugins = plugin_manager.discover_plugins()
|
||||
assert "my-plugin" in plugins
|
||||
|
||||
assert plugin_manager.load_plugin("my-plugin")
|
||||
plugin = plugin_manager.get_plugin("my-plugin")
|
||||
assert plugin is not None
|
||||
assert plugin.enabled
|
||||
|
||||
plugin.update()
|
||||
plugin.display()
|
||||
```
|
||||
|
||||
### Emulator Testing
|
||||
|
||||
Test plugin rendering visually:
|
||||
|
||||
```bash
|
||||
# Run with emulator
|
||||
python run.py --emulator
|
||||
|
||||
# Plugin should appear in display rotation
|
||||
# Check logs for plugin loading and execution
|
||||
```
|
||||
|
||||
### Hardware Testing
|
||||
|
||||
1. Deploy plugin to Raspberry Pi
|
||||
2. Enable in `config/config.json`
|
||||
3. Restart LEDMatrix service
|
||||
4. Observe LED matrix display
|
||||
5. Check logs: `journalctl -u ledmatrix -f`
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Plugin Not Loading
|
||||
|
||||
**Symptoms**: Plugin doesn't appear in available modes, no logs about plugin
|
||||
|
||||
**Solutions**:
|
||||
1. Check plugin directory exists: `ls plugins/my-plugin/`
|
||||
2. Verify `manifest.json` exists and is valid JSON
|
||||
3. Check manifest has required fields: `id`, `entry_point`, `class_name`
|
||||
4. Verify entry_point file exists: `ls plugins/my-plugin/manager.py`
|
||||
5. Check class name matches: `grep "class.*Plugin" plugins/my-plugin/manager.py`
|
||||
6. Review logs for import errors
|
||||
|
||||
### Plugin Loading but Not Displaying
|
||||
|
||||
**Symptoms**: Plugin loads successfully but doesn't appear in rotation
|
||||
|
||||
**Solutions**:
|
||||
1. Check plugin is enabled: `config/config.json` has `"enabled": true`
|
||||
2. Verify display_modes in manifest match config
|
||||
3. Check plugin is in rotation schedule
|
||||
4. Review `display()` method for errors
|
||||
5. Check logs for runtime errors
|
||||
|
||||
### Configuration Errors
|
||||
|
||||
**Symptoms**: Plugin fails to load, validation errors in logs
|
||||
|
||||
**Solutions**:
|
||||
1. Validate config against `config_schema.json`
|
||||
2. Check required fields are present
|
||||
3. Verify data types match schema
|
||||
4. Check for typos in config keys
|
||||
5. Review `validate_config()` method
|
||||
|
||||
### Import Errors
|
||||
|
||||
**Symptoms**: ModuleNotFoundError or ImportError in logs
|
||||
|
||||
**Solutions**:
|
||||
1. Install plugin dependencies: `pip install -r plugins/my-plugin/requirements.txt`
|
||||
2. Check Python path includes plugin directory
|
||||
3. Verify relative imports are correct
|
||||
4. Check for circular import issues
|
||||
5. Ensure all dependencies are in requirements.txt
|
||||
|
||||
### Display Issues
|
||||
|
||||
**Symptoms**: Plugin renders incorrectly or not at all
|
||||
|
||||
**Solutions**:
|
||||
1. Check display dimensions: `display_manager.width`, `display_manager.height`
|
||||
2. Verify coordinates are within display bounds
|
||||
3. Check color values are valid (0-255)
|
||||
4. Ensure `update_display()` is called after rendering
|
||||
5. Test with emulator first to debug rendering
|
||||
|
||||
### Performance Issues
|
||||
|
||||
**Symptoms**: Slow display updates, high CPU usage
|
||||
|
||||
**Solutions**:
|
||||
1. Use `cache_manager` to avoid excessive API calls
|
||||
2. Implement background data fetching
|
||||
3. Optimize rendering code
|
||||
4. Consider using `high_performance_transitions`
|
||||
5. Profile plugin code to identify bottlenecks
|
||||
|
||||
### Git/Symlink Issues
|
||||
|
||||
**Symptoms**: Plugin changes not appearing, broken symlinks
|
||||
|
||||
**Solutions**:
|
||||
1. Check symlink: `ls -la plugins/my-plugin`
|
||||
2. Verify target exists: `readlink -f plugins/my-plugin`
|
||||
3. Update plugin: `./scripts/dev/dev_plugin_setup.sh update my-plugin`
|
||||
4. Re-link plugin if needed: `./scripts/dev/dev_plugin_setup.sh unlink my-plugin && ./scripts/dev/dev_plugin_setup.sh link my-plugin <path>`
|
||||
5. Check git status: `cd plugins/my-plugin && git status`
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Code Organization
|
||||
|
||||
- Keep plugin code in `plugins/<plugin-id>/` directory
|
||||
- Use descriptive class and method names
|
||||
- Follow existing plugin patterns
|
||||
- Place shared utilities in `src/common/` if reusable
|
||||
|
||||
### Configuration
|
||||
|
||||
- Always use `config_schema.json` for validation
|
||||
- Store secrets in `config_secrets.json`
|
||||
- Provide sensible defaults
|
||||
- Document all configuration options in README
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Use plugin logger for all logging
|
||||
- Handle API failures gracefully
|
||||
- Provide fallback displays when data unavailable
|
||||
- Cache data to avoid excessive requests
|
||||
|
||||
### Performance
|
||||
|
||||
- Cache API responses appropriately
|
||||
- Use background data fetching for long operations
|
||||
- Optimize rendering for Pi's limited resources
|
||||
- Test performance on actual hardware
|
||||
|
||||
### Testing
|
||||
|
||||
- Write unit tests for core logic
|
||||
- Test with emulator before hardware
|
||||
- Test on Raspberry Pi before deploying
|
||||
- Test with other plugins enabled
|
||||
|
||||
### Documentation
|
||||
|
||||
- Document plugin functionality in README
|
||||
- Include configuration examples
|
||||
- Document API requirements and rate limits
|
||||
- Provide usage examples
|
||||
|
||||
---
|
||||
|
||||
## Resources
|
||||
|
||||
- **Plugin System Documentation**: `docs/PLUGIN_ARCHITECTURE_SPEC.md`
|
||||
- **Base Plugin Class**: `src/plugin_system/base_plugin.py`
|
||||
- **Plugin Manager**: `src/plugin_system/plugin_manager.py`
|
||||
- **Example Plugins**:
|
||||
- `plugins/hockey-scoreboard/` - Sports scoreboard example
|
||||
- `plugins/football-scoreboard/` - Complex multi-league example
|
||||
- `plugins/ledmatrix-music/` - Real-time data example
|
||||
- **Development Setup**: `dev_plugin_setup.sh`
|
||||
- **Example Config**: `dev_plugins.json.example`
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Common Commands
|
||||
|
||||
```bash
|
||||
# Link plugin from GitHub
|
||||
./scripts/dev/dev_plugin_setup.sh link-github <name>
|
||||
|
||||
# Link local plugin
|
||||
./scripts/dev/dev_plugin_setup.sh link <name> <path>
|
||||
|
||||
# List all plugins
|
||||
./scripts/dev/dev_plugin_setup.sh list
|
||||
|
||||
# Check plugin status
|
||||
./scripts/dev/dev_plugin_setup.sh status
|
||||
|
||||
# Update plugin(s)
|
||||
./scripts/dev/dev_plugin_setup.sh update [name]
|
||||
|
||||
# Unlink plugin
|
||||
./scripts/dev/dev_plugin_setup.sh unlink <name>
|
||||
|
||||
# Run with emulator
|
||||
python run.py --emulator
|
||||
|
||||
# Run on Pi
|
||||
python run.py
|
||||
```
|
||||
|
||||
### Plugin File Structure
|
||||
|
||||
```
|
||||
plugins/my-plugin/
|
||||
├── manifest.json # Required: Plugin metadata
|
||||
├── manager.py # Required: Plugin class
|
||||
├── config_schema.json # Required: Config validation
|
||||
├── requirements.txt # Optional: Dependencies
|
||||
├── README.md # Optional: Documentation
|
||||
└── ... # Plugin-specific files
|
||||
```
|
||||
|
||||
### Required Manifest Fields
|
||||
|
||||
- `id`: Plugin identifier
|
||||
- `entry_point`: Python file (usually "manager.py")
|
||||
- `class_name`: Plugin class name
|
||||
- `display_modes`: Array of mode names
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
globs: *.py
|
||||
---
|
||||
|
||||
# Python Coding Standards
|
||||
|
||||
## Code Quality Principles
|
||||
- **Simplicity First**: Prefer clear, readable code over clever optimizations
|
||||
- **Explicit over Implicit**: Make intentions clear through naming and structure
|
||||
- **Fail Fast**: Validate inputs and handle errors early
|
||||
- **Documentation**: Use docstrings for classes and complex functions
|
||||
|
||||
## Naming Conventions
|
||||
- **Classes**: PascalCase (e.g., `NHLRecentManager`)
|
||||
- **Functions/Variables**: snake_case (e.g., `fetch_game_data`)
|
||||
- **Constants**: UPPER_SNAKE_CASE (e.g., `ESPN_NHL_SCOREBOARD_URL`)
|
||||
- **Private methods**: Leading underscore (e.g., `_fetch_data`)
|
||||
|
||||
## Error Handling
|
||||
- **Logging**: Use structured logging with context (e.g., `[NHL Recent]`)
|
||||
- **Exceptions**: Catch specific exceptions, not bare `except:`
|
||||
- **User-friendly messages**: Explain what went wrong and potential solutions
|
||||
- **Graceful degradation**: Continue operation when non-critical features fail
|
||||
|
||||
## Manager Pattern
|
||||
All sports managers should follow this structure:
|
||||
```python
|
||||
class BaseManager:
|
||||
def __init__(self, config, display_manager, cache_manager)
|
||||
def update(self) # Fetch and process data
|
||||
def display(self, force_clear=False) # Render to display
|
||||
```
|
||||
|
||||
## Configuration Management
|
||||
- **Type hints**: Use for function parameters and return values
|
||||
- **Configuration validation**: Check required fields on initialization
|
||||
- **Default values**: Provide sensible defaults in code, not config
|
||||
- **Environment awareness**: Handle different deployment contexts
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
globs: config/*.json,src/*.py
|
||||
---
|
||||
|
||||
# Configuration Management
|
||||
|
||||
## Configuration Structure
|
||||
- **Main config**: [config/config.json](mdc:config/config.json) - Primary configuration
|
||||
- **Secrets**: [config/config_secrets.json](mdc:config/config_secrets.json) - API keys and sensitive data
|
||||
- **Templates**: [config/config.template.json](mdc:config/config.template.json) - Default values
|
||||
|
||||
## Configuration Principles
|
||||
- **Validation**: Check required fields and data types on startup
|
||||
- **Defaults**: Provide sensible defaults in code, not just config
|
||||
- **Environment awareness**: Handle development vs production differences
|
||||
- **Security**: Never commit secrets to version control
|
||||
|
||||
## Manager Configuration Pattern
|
||||
```python
|
||||
def __init__(self, config, display_manager, cache_manager):
|
||||
self.mode_config = config.get("sport_scoreboard", {})
|
||||
self.favorite_teams = self.mode_config.get("favorite_teams", [])
|
||||
self.show_favorite_only = self.mode_config.get("show_favorite_teams_only", False)
|
||||
```
|
||||
|
||||
## Required Configuration Sections
|
||||
- **Display settings**: Update intervals, display durations
|
||||
- **API settings**: Timeouts, retry logic, rate limiting
|
||||
- **Background service**: Threading, caching, priority settings
|
||||
- **Team preferences**: Favorite teams, filtering options
|
||||
|
||||
## Configuration Validation
|
||||
- **Type checking**: Ensure numeric values are numbers, lists are lists
|
||||
- **Range validation**: Check that intervals are reasonable
|
||||
- **Dependency checking**: Verify required services are available
|
||||
- **Fallback values**: Provide defaults when config is missing or invalid
|
||||
|
||||
## Best Practices
|
||||
- **Documentation**: Comment complex configuration options
|
||||
- **Examples**: Provide working examples in templates
|
||||
- **Migration**: Handle configuration changes between versions
|
||||
- **Testing**: Validate configuration in test environments
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
globs: src/*.py
|
||||
---
|
||||
|
||||
# Error Handling and Logging
|
||||
|
||||
## Logging Standards
|
||||
- **Structured prefixes**: Use consistent tags like `[NHL Recent]`, `[NFL Live]`
|
||||
- **Context information**: Include relevant details (team names, game status, dates)
|
||||
- **Appropriate levels**:
|
||||
- `info`: Normal operations and status updates
|
||||
- `debug`: Detailed information for troubleshooting
|
||||
- `warning`: Non-critical issues that should be noted
|
||||
- `error`: Problems that need attention
|
||||
|
||||
## Error Handling Patterns
|
||||
```python
|
||||
try:
|
||||
data = self._fetch_data()
|
||||
if not data or 'events' not in data:
|
||||
self.logger.warning("[Manager] No events found in API response")
|
||||
return
|
||||
except requests.exceptions.RequestException as e:
|
||||
self.logger.error(f"[Manager] API error: {e}")
|
||||
return None
|
||||
```
|
||||
|
||||
## User-Friendly Messages
|
||||
- **Explain the situation**: "No games available during off-season"
|
||||
- **Provide context**: "NHL season typically runs October-June"
|
||||
- **Suggest solutions**: "Check back when season starts"
|
||||
- **Distinguish issues**: API problems vs no data vs filtering results
|
||||
|
||||
## Graceful Degradation
|
||||
- **Fallback content**: Show alternative games when favorites unavailable
|
||||
- **Cached data**: Use cached data when API fails
|
||||
- **Service continuity**: Continue operation when non-critical features fail
|
||||
- **Clear communication**: Explain what's happening to users
|
||||
|
||||
## Debugging Support
|
||||
- **Comprehensive logging**: Log API responses, filtering results, display updates
|
||||
- **State tracking**: Log current state and transitions
|
||||
- **Performance monitoring**: Track timing and resource usage
|
||||
- **Error context**: Include stack traces for debugging
|
||||
|
||||
## Off-Season Awareness
|
||||
- **Seasonal messaging**: Different messages for different times of year
|
||||
- **Helpful context**: Explain why no games are available
|
||||
- **Future planning**: Mention when season starts
|
||||
- **Realistic expectations**: Set appropriate expectations during off-season
|
||||
@@ -1,51 +0,0 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Git Workflow and Branching
|
||||
|
||||
## Branch Naming Conventions
|
||||
- **Features**: `feature/description-of-feature` (e.g., `feature/weather-forecast-improvements`)
|
||||
- **Bug fixes**: `fix/description-of-bug` (e.g., `fix/nhl-manager-improvements`)
|
||||
- **Hotfixes**: `hotfix/critical-issue-description`
|
||||
- **Refactoring**: `refactor/description-of-refactor`
|
||||
|
||||
## Commit Message Format
|
||||
```
|
||||
type(scope): description
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer]
|
||||
```
|
||||
|
||||
**Types**: feat, fix, docs, style, refactor, test, chore
|
||||
**Examples**:
|
||||
- `feat(nhl): Add enhanced logging for data visibility`
|
||||
- `fix(display): Resolve rendering performance issue`
|
||||
- `docs(api): Update ESPN API integration guide`
|
||||
|
||||
## Pull Request Guidelines
|
||||
- **Self-review**: Review your own PR before requesting review
|
||||
- **Testing**: Test thoroughly on Raspberry Pi hardware
|
||||
- **Documentation**: Update relevant documentation if needed
|
||||
- **Clean history**: Squash commits if necessary for clean history
|
||||
|
||||
## Code Review Checklist
|
||||
- **Code Quality**: Proper error handling, logging, type hints
|
||||
- **Architecture**: Follows project patterns, doesn't break existing functionality
|
||||
- **Performance**: No negative impact on display performance
|
||||
- **Testing**: Works on Raspberry Pi hardware
|
||||
- **Documentation**: Comments added for complex logic
|
||||
|
||||
## Merge Strategies
|
||||
- **Squash and Merge**: Preferred for feature branches and bug fixes
|
||||
- **Merge Commit**: For complex features with multiple logical commits
|
||||
- **Rebase and Merge**: For simple, single-commit changes
|
||||
|
||||
## Best Practices
|
||||
- **Keep branches small and focused**
|
||||
- **Commit frequently with meaningful messages**
|
||||
- **Update branch regularly with main**
|
||||
- **Test changes incrementally**
|
||||
- **Delete feature branches after merge**
|
||||
@@ -1,213 +0,0 @@
|
||||
---
|
||||
description: GitHub branching and pull request best practices for LEDMatrix project
|
||||
globs: ["**/*.py", "**/*.md", "**/*.json", "**/*.sh"]
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# GitHub Branching and Pull Request Guidelines
|
||||
|
||||
## Branch Naming Conventions
|
||||
|
||||
### Feature Branches
|
||||
- **Format**: `feature/description-of-feature`
|
||||
- **Examples**:
|
||||
- `feature/weather-forecast-improvements`
|
||||
- `feature/stock-api-integration`
|
||||
- `feature/nba-live-scores`
|
||||
|
||||
### Bug Fix Branches
|
||||
- **Format**: `fix/description-of-bug`
|
||||
- **Examples**:
|
||||
- `fix/leaderboard-scrolling-performance`
|
||||
- `fix/weather-api-timeout`
|
||||
- `fix/display-rendering-issue`
|
||||
|
||||
### Hotfix Branches
|
||||
- **Format**: `hotfix/critical-issue-description`
|
||||
- **Examples**:
|
||||
- `hotfix/display-crash-fix`
|
||||
- `hotfix/api-rate-limit-fix`
|
||||
|
||||
### Refactoring Branches
|
||||
- **Format**: `refactor/description-of-refactor`
|
||||
- **Examples**:
|
||||
- `refactor/sports-manager-architecture`
|
||||
- `refactor/cache-management-system`
|
||||
|
||||
## Branch Management Rules
|
||||
|
||||
### Main Branch Protection
|
||||
- **`main`** branch is protected and requires PR reviews
|
||||
- Never commit directly to `main`
|
||||
- All changes must go through pull requests
|
||||
|
||||
### Branch Lifecycle
|
||||
1. **Create** branch from `main` when starting work
|
||||
2. **Keep** branch up-to-date with `main` regularly
|
||||
3. **Test** thoroughly before creating PR
|
||||
4. **Delete** branch after successful merge
|
||||
|
||||
### Branch Updates
|
||||
```bash
|
||||
# Before starting new work
|
||||
git checkout main
|
||||
git pull origin main
|
||||
|
||||
# Create new branch
|
||||
git checkout -b feature/your-feature-name
|
||||
|
||||
# Keep branch updated during development
|
||||
git checkout main
|
||||
git pull origin main
|
||||
git checkout feature/your-feature-name
|
||||
git merge main
|
||||
```
|
||||
|
||||
## Pull Request Guidelines
|
||||
|
||||
### PR Title Format
|
||||
- **Feature**: `feat: Add weather forecast improvements`
|
||||
- **Fix**: `fix: Resolve leaderboard scrolling performance issue`
|
||||
- **Refactor**: `refactor: Improve sports manager architecture`
|
||||
- **Docs**: `docs: Update API integration guide`
|
||||
- **Test**: `test: Add unit tests for weather manager`
|
||||
|
||||
### PR Description Template
|
||||
```markdown
|
||||
## Description
|
||||
Brief description of changes and motivation.
|
||||
|
||||
## Type of Change
|
||||
- [ ] Bug fix (non-breaking change)
|
||||
- [ ] New feature (non-breaking change)
|
||||
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
|
||||
- [ ] Documentation update
|
||||
- [ ] Performance improvement
|
||||
- [ ] Refactoring
|
||||
|
||||
## Testing
|
||||
- [ ] Tested on Raspberry Pi hardware
|
||||
- [ ] Verified display rendering works correctly
|
||||
- [ ] Checked API integration functionality
|
||||
- [ ] Tested error handling scenarios
|
||||
|
||||
## Screenshots/Videos
|
||||
(If applicable, add screenshots or videos of the changes)
|
||||
|
||||
## Checklist
|
||||
- [ ] Code follows project style guidelines
|
||||
- [ ] Self-review completed
|
||||
- [ ] Comments added for complex logic
|
||||
- [ ] No hardcoded values or API keys
|
||||
- [ ] Error handling implemented
|
||||
- [ ] Logging added where appropriate
|
||||
```
|
||||
|
||||
### PR Review Requirements
|
||||
|
||||
#### For Reviewers
|
||||
- **Code Quality**: Check for proper error handling, logging, and type hints
|
||||
- **Architecture**: Ensure changes follow project patterns and don't break existing functionality
|
||||
- **Performance**: Verify changes don't negatively impact display performance
|
||||
- **Testing**: Confirm changes work on Raspberry Pi hardware
|
||||
- **Documentation**: Check if documentation needs updates
|
||||
|
||||
#### For Authors
|
||||
- **Self-Review**: Review your own PR before requesting review
|
||||
- **Testing**: Test thoroughly on Pi hardware before submitting
|
||||
- **Documentation**: Update relevant documentation if needed
|
||||
- **Clean History**: Squash commits if necessary for clean history
|
||||
|
||||
## Commit Message Guidelines
|
||||
|
||||
### Format
|
||||
```
|
||||
type(scope): description
|
||||
|
||||
[optional body]
|
||||
|
||||
[optional footer]
|
||||
```
|
||||
|
||||
### Types
|
||||
- **feat**: New feature
|
||||
- **fix**: Bug fix
|
||||
- **docs**: Documentation changes
|
||||
- **style**: Code style changes (formatting, etc.)
|
||||
- **refactor**: Code refactoring
|
||||
- **test**: Adding or updating tests
|
||||
- **chore**: Maintenance tasks
|
||||
|
||||
### Examples
|
||||
```
|
||||
feat(weather): Add hourly forecast display
|
||||
fix(nba): Resolve live score update issue
|
||||
docs(api): Update ESPN API integration guide
|
||||
refactor(sports): Improve base class architecture
|
||||
```
|
||||
|
||||
## Merge Strategies
|
||||
|
||||
### Squash and Merge (Preferred)
|
||||
- Use for feature branches and bug fixes
|
||||
- Creates clean, linear history
|
||||
- Combines all commits into single commit
|
||||
|
||||
### Merge Commit
|
||||
- Use for complex features with multiple logical commits
|
||||
- Preserves commit history
|
||||
- Use when commit messages are meaningful
|
||||
|
||||
### Rebase and Merge
|
||||
- Use sparingly for simple, single-commit changes
|
||||
- Creates linear history without merge commits
|
||||
|
||||
## Release Management
|
||||
|
||||
### Version Tags
|
||||
- Use semantic versioning: `v1.2.3`
|
||||
- Tag releases on `main` branch
|
||||
- Create release notes with technical details
|
||||
|
||||
### Release Branches
|
||||
- **Format**: `release/v1.2.3`
|
||||
- Use for release preparation
|
||||
- Include version bumps and final testing
|
||||
|
||||
## Emergency Procedures
|
||||
|
||||
### Hotfix Process
|
||||
1. Create `hotfix/` branch from `main`
|
||||
2. Make minimal fix
|
||||
3. Test thoroughly
|
||||
4. Create PR with expedited review
|
||||
5. Merge to `main` and tag release
|
||||
6. Cherry-pick to other branches if needed
|
||||
|
||||
### Rollback Process
|
||||
1. Identify last known good commit
|
||||
2. Create revert PR if possible
|
||||
3. Use `git revert` for clean rollback
|
||||
4. Tag rollback release
|
||||
5. Document issue and resolution
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Before Creating PR
|
||||
- [ ] Run all tests locally
|
||||
- [ ] Test on Raspberry Pi hardware
|
||||
- [ ] Check for linting errors
|
||||
- [ ] Update documentation if needed
|
||||
- [ ] Ensure commit messages are clear
|
||||
|
||||
### During Development
|
||||
- [ ] Keep branches small and focused
|
||||
- [ ] Commit frequently with meaningful messages
|
||||
- [ ] Update branch regularly with main
|
||||
- [ ] Test changes incrementally
|
||||
|
||||
### After PR Approval
|
||||
- [ ] Delete feature branch after merge
|
||||
- [ ] Update local main branch
|
||||
- [ ] Verify changes work in production
|
||||
- [ ] Update any related documentation
|
||||
@@ -1,23 +0,0 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# LEDMatrix Project Structure
|
||||
|
||||
## Core Architecture
|
||||
- **Main entry point**: [run.py](mdc:run.py) - Primary application launcher
|
||||
- **Configuration**: [config/config.json](mdc:config/config.json) - Main configuration file
|
||||
- **Display management**: [src/display_controller.py](mdc:src/display_controller.py) - Core display logic
|
||||
- **Web interface**: [web_interface_v2.py](mdc:web_interface_v2.py) - Modern web UI
|
||||
|
||||
## Source Code Organization
|
||||
- **Managers**: [src/](mdc:src/) - All sports/weather/stock managers
|
||||
- **Assets**: [assets/](mdc:assets/) - Logos, fonts, and static resources
|
||||
- **Tests**: [test/](mdc:test/) - Unit and integration tests
|
||||
- **Documentation**: [LEDMatrix.wiki/](mdc:LEDMatrix.wiki/) - Comprehensive guides
|
||||
|
||||
## Key Design Principles
|
||||
- **Single Responsibility**: Each manager handles one sport/domain
|
||||
- **Consistent Patterns**: All managers follow similar structure
|
||||
- **Configuration-Driven**: Behavior controlled via [config/config.json](mdc:config/config.json)
|
||||
- **Raspberry Pi Focus**: Optimized for Pi hardware, not Windows development
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Raspberry Pi Development Guidelines
|
||||
|
||||
## Hardware Constraints
|
||||
- **Pi-only execution**: Code must run on Raspberry Pi, not Windows development machine
|
||||
- **LED matrix library**: Uses [rpi-rgb-led-matrix-master/](mdc:rpi-rgb-led-matrix-master/) for hardware control
|
||||
- **Memory limitations**: Optimize for Pi's limited RAM
|
||||
- **Performance**: Consider Pi's CPU capabilities in design
|
||||
|
||||
## Development Workflow
|
||||
- **Local development**: Write and test code on Windows
|
||||
- **Pi deployment**: Deploy and test on actual Pi hardware
|
||||
- **SSH access**: Use SSH for Pi-based testing and debugging
|
||||
- **Service management**: Use systemd services for production deployment
|
||||
|
||||
## Testing Strategy
|
||||
- **Unit tests**: Test logic without hardware dependencies
|
||||
- **Integration tests**: Test with mock display managers
|
||||
- **Hardware tests**: Validate on actual Pi with LED matrix
|
||||
- **Performance tests**: Monitor memory and CPU usage
|
||||
|
||||
## Deployment Considerations
|
||||
- **Service files**: [ledmatrix.service](mdc:ledmatrix.service), [ledmatrix-web.service](mdc:ledmatrix-web.service)
|
||||
- **Installation scripts**: [first_time_install.sh](mdc:first_time_install.sh), [install_service.sh](mdc:install_service.sh)
|
||||
- **Dependencies**: [requirements.txt](mdc:requirements.txt) for Pi environment
|
||||
- **Permissions**: Handle file permissions for Pi user
|
||||
|
||||
## Performance Optimization
|
||||
- **Caching**: Use [src/cache_manager.py](mdc:src/cache_manager.py) for data persistence
|
||||
- **Background services**: Non-blocking data fetching
|
||||
- **Memory management**: Clean up resources regularly
|
||||
- **Display optimization**: Minimize unnecessary redraws
|
||||
|
||||
## Debugging on Pi
|
||||
- **Logging**: Comprehensive logging for remote debugging
|
||||
- **Error reporting**: Clear error messages for troubleshooting
|
||||
- **Status monitoring**: Health checks and status reporting
|
||||
- **Remote access**: Web interface for configuration and monitoring
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
globs: src/*_managers.py
|
||||
---
|
||||
|
||||
# Sports Manager Development
|
||||
|
||||
## Manager Architecture
|
||||
All sports managers inherit from base classes and follow consistent patterns:
|
||||
- **Base classes**: [src/nhl_managers.py](mdc:src/nhl_managers.py), [src/nfl_managers.py](mdc:src/nfl_managers.py)
|
||||
- **Common functionality**: Data fetching, caching, display rendering
|
||||
- **Configuration-driven**: Behavior controlled via config sections
|
||||
|
||||
## Required Methods
|
||||
```python
|
||||
def __init__(self, config, display_manager, cache_manager)
|
||||
def update(self) # Fetch fresh data
|
||||
def display(self, force_clear=False) # Render current data
|
||||
```
|
||||
|
||||
## Data Flow Pattern
|
||||
1. **Fetch**: Get data from API (with caching)
|
||||
2. **Process**: Extract relevant game information
|
||||
3. **Filter**: Apply favorite team preferences
|
||||
4. **Display**: Render to LED matrix
|
||||
|
||||
## Logging Standards
|
||||
- **Structured prefixes**: `[NHL Recent]`, `[NFL Live]`, etc.
|
||||
- **Context information**: Include team names, game status, dates
|
||||
- **Debug levels**: Use appropriate log levels (info, debug, warning, error)
|
||||
- **User-friendly messages**: Explain what's happening and why
|
||||
|
||||
## Error Handling
|
||||
- **API failures**: Log and continue with cached data if available
|
||||
- **No data scenarios**: Distinguish between API issues vs no games available
|
||||
- **Off-season awareness**: Provide helpful context during non-active periods
|
||||
- **Fallback behavior**: Show alternative content when preferred content unavailable
|
||||
|
||||
## Configuration Integration
|
||||
- **Required settings**: Validate on initialization
|
||||
- **Optional settings**: Provide sensible defaults
|
||||
- **Background service**: Use for non-blocking data fetching
|
||||
- **Caching strategy**: Implement intelligent cache management
|
||||
@@ -1,51 +0,0 @@
|
||||
---
|
||||
globs: test/*.py,src/*.py
|
||||
---
|
||||
|
||||
# Testing Standards
|
||||
|
||||
## Test Organization
|
||||
- **Test directory**: [test/](mdc:test/) - All test files
|
||||
- **Unit tests**: Test individual components in isolation
|
||||
- **Integration tests**: Test component interactions
|
||||
- **Hardware tests**: Validate on Raspberry Pi with actual LED matrix
|
||||
|
||||
## Testing Principles
|
||||
- **Test behavior, not implementation**: Focus on what the code does, not how
|
||||
- **Mock external dependencies**: Use mocks for APIs, display managers, cache
|
||||
- **Test edge cases**: Empty data, API failures, configuration errors
|
||||
- **Pi-specific testing**: Validate hardware integration
|
||||
|
||||
## Test Structure
|
||||
```python
|
||||
def test_manager_initialization():
|
||||
"""Test that manager initializes with valid config"""
|
||||
config = {"sport_scoreboard": {"enabled": True}}
|
||||
manager = ManagerClass(config, mock_display, mock_cache)
|
||||
assert manager.enabled == True
|
||||
|
||||
def test_api_failure_handling():
|
||||
"""Test graceful handling of API failures"""
|
||||
# Test that system continues when API fails
|
||||
# Verify fallback to cached data
|
||||
# Check appropriate error logging
|
||||
```
|
||||
|
||||
## Mock Patterns
|
||||
- **Display Manager**: Mock for testing without hardware
|
||||
- **Cache Manager**: Mock for testing data persistence
|
||||
- **API responses**: Mock for consistent test data
|
||||
- **Configuration**: Use test-specific configs
|
||||
|
||||
## Test Categories
|
||||
- **Unit tests**: Individual manager methods
|
||||
- **Integration tests**: Manager interactions with services
|
||||
- **Configuration tests**: Validate config loading and validation
|
||||
- **Error handling tests**: API failures, invalid data, edge cases
|
||||
|
||||
## Testing Best Practices
|
||||
- **Descriptive names**: Test names should explain what they test
|
||||
- **Single responsibility**: Each test should verify one thing
|
||||
- **Independent tests**: Tests should not depend on each other
|
||||
- **Clean setup/teardown**: Reset state between tests
|
||||
- **Pi compatibility**: Ensure tests work in Pi environment
|
||||
@@ -1 +0,0 @@
|
||||
# Add directories or file patterns to ignore during indexing (e.g. foo/ or *.csv)
|
||||
@@ -1,364 +0,0 @@
|
||||
# LEDMatrix Plugin Development Rules
|
||||
|
||||
## Plugin System Overview
|
||||
|
||||
The LEDMatrix project uses a plugin-based architecture. All display
|
||||
functionality (except core calendar) is implemented as plugins that are
|
||||
dynamically loaded from the directory configured by
|
||||
`plugin_system.plugins_directory` in `config.json` — the default is
|
||||
`plugin-repos/` (per `config/config.template.json:130`).
|
||||
|
||||
> **Fallback note (scoped):** `PluginManager.discover_plugins()`
|
||||
> (`src/plugin_system/plugin_manager.py:154`) only scans the
|
||||
> configured directory — there is no fallback to `plugins/` in the
|
||||
> main discovery path. A fallback to `plugins/` does exist in two
|
||||
> narrower places:
|
||||
> - `store_manager.py:1700-1718` — store operations (install/update/
|
||||
> uninstall) check `plugins/` if the plugin isn't found in the
|
||||
> configured directory, so plugin-store flows work even when your
|
||||
> dev symlinks live in `plugins/`.
|
||||
> - `schema_manager.py:70-80` — `get_schema_path()` probes both
|
||||
> `plugins/` and `plugin-repos/` for `config_schema.json` so the
|
||||
> web UI form generation finds the schema regardless of where the
|
||||
> plugin lives.
|
||||
>
|
||||
> The dev workflow in `scripts/dev/dev_plugin_setup.sh` creates
|
||||
> symlinks under `plugins/`, which is why the store and schema
|
||||
> fallbacks exist. For day-to-day development, set
|
||||
> `plugin_system.plugins_directory` to `plugins` so the main
|
||||
> discovery path picks up your symlinks.
|
||||
|
||||
## Plugin Structure
|
||||
|
||||
### Required Files
|
||||
- **manifest.json**: Plugin metadata, entry point, class name, dependencies
|
||||
- **manager.py**: Main plugin class (must inherit from `BasePlugin`)
|
||||
- **config_schema.json**: JSON schema for plugin configuration validation
|
||||
- **requirements.txt**: Python dependencies (if any)
|
||||
- **README.md**: Plugin documentation
|
||||
|
||||
### Plugin Class Requirements
|
||||
- Must inherit from `src.plugin_system.base_plugin.BasePlugin`
|
||||
- Must implement `update()` method for data fetching
|
||||
- Must implement `display()` method for rendering
|
||||
- Should implement `validate_config()` for configuration validation
|
||||
- Optional: Override `has_live_content()` for live priority features
|
||||
|
||||
## Plugin Development Workflow
|
||||
|
||||
### 1. Creating a New Plugin
|
||||
|
||||
**Option A: Use dev_plugin_setup.sh (Recommended)**
|
||||
```bash
|
||||
# Link from GitHub
|
||||
./scripts/dev/dev_plugin_setup.sh link-github <plugin-name>
|
||||
|
||||
# Link local repository
|
||||
./scripts/dev/dev_plugin_setup.sh link <plugin-name> <path-to-repo>
|
||||
```
|
||||
|
||||
**Option B: Manual Setup**
|
||||
1. Create directory in `plugin-repos/<plugin-id>/` (or `plugins/<plugin-id>/`
|
||||
if you're using the dev fallback location)
|
||||
2. Add `manifest.json` with required fields
|
||||
3. Create `manager.py` with plugin class
|
||||
4. Add `config_schema.json` for configuration
|
||||
5. Enable plugin in `config/config.json` under `"<plugin-id>": {"enabled": true}`
|
||||
|
||||
### 2. Plugin Configuration
|
||||
|
||||
Plugins are configured in `config/config.json`:
|
||||
```json
|
||||
{
|
||||
"<plugin-id>": {
|
||||
"enabled": true,
|
||||
"display_duration": 15,
|
||||
"live_priority": false,
|
||||
"high_performance_transitions": false,
|
||||
"transition": {
|
||||
"type": "redraw",
|
||||
"speed": 2,
|
||||
"enabled": true
|
||||
},
|
||||
// ... plugin-specific config
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Testing Plugins
|
||||
|
||||
**On Development Machine:**
|
||||
- Run the dev preview server: `python3 scripts/dev_server.py` (then
|
||||
open `http://localhost:5001`) — renders plugins in the browser
|
||||
without running the full display loop
|
||||
- Or run the full display in emulator mode:
|
||||
`python3 run.py --emulator` (or equivalently
|
||||
`EMULATOR=true python3 run.py`, or `./scripts/dev/run_emulator.sh`).
|
||||
The `-e`/`--emulator` CLI flag is defined in `run.py:19-20`.
|
||||
- Test plugin loading: Check logs for plugin discovery and loading
|
||||
- Validate configuration: Ensure config matches `config_schema.json`
|
||||
|
||||
**On Raspberry Pi:**
|
||||
- Deploy and test on actual hardware
|
||||
- Monitor logs: `journalctl -u ledmatrix -f` (if running as service)
|
||||
- Check plugin status in web interface
|
||||
|
||||
### 4. Plugin Development Best Practices
|
||||
|
||||
**Code Organization:**
|
||||
- Keep plugin code in `plugin-repos/<plugin-id>/` (or its dev-time
|
||||
symlink in `plugins/<plugin-id>/`)
|
||||
- Use shared assets from `assets/` directory when possible
|
||||
- Follow existing plugin patterns — canonical sources live in the
|
||||
[`ledmatrix-plugins`](https://github.com/ChuckBuilds/ledmatrix-plugins)
|
||||
repo (`plugins/hockey-scoreboard/`, `plugins/football-scoreboard/`,
|
||||
`plugins/clock-simple/`, etc.)
|
||||
- Place shared utilities in `src/common/` if reusable across plugins
|
||||
|
||||
**Configuration Management:**
|
||||
- Use `config_schema.json` for validation
|
||||
- Store secrets in `config/config_secrets.json` under the same plugin
|
||||
id namespace as the main config — they're deep-merged into the main
|
||||
config at load time (`src/config_manager.py:162-172`), so plugin
|
||||
code reads them directly from `config.get(...)` like any other key
|
||||
- There is no separate `config_secrets` reference field
|
||||
- Validate all required fields in `validate_config()`
|
||||
|
||||
**Error Handling:**
|
||||
- Use plugin's logger: `self.logger.info/error/warning()`
|
||||
- Handle API failures gracefully
|
||||
- Cache data to avoid excessive API calls
|
||||
- Provide fallback displays when data unavailable
|
||||
|
||||
**Performance:**
|
||||
- Use `cache_manager` for API response caching
|
||||
- Implement background data fetching if needed
|
||||
- Use `high_performance_transitions` for smoother animations
|
||||
- Optimize rendering for Pi's limited resources
|
||||
|
||||
**Display Rendering:**
|
||||
- Use `display_manager` for all drawing operations
|
||||
- Support different display sizes (check `display_manager.width/height`)
|
||||
- Use `apply_transition()` for smooth transitions between displays
|
||||
- Clear display before rendering: `display_manager.clear()`
|
||||
- Always call `display_manager.update_display()` after rendering
|
||||
|
||||
## Plugin API Reference
|
||||
|
||||
### BasePlugin Class
|
||||
Located in: `src/plugin_system/base_plugin.py`
|
||||
|
||||
**Required Methods:**
|
||||
- `update()`: Fetch/update data (called based on `update_interval` in manifest)
|
||||
- `display(force_clear=False)`: Render plugin content
|
||||
|
||||
**Optional Methods:**
|
||||
- `validate_config()`: Validate plugin configuration
|
||||
- `has_live_content()`: Return True if plugin has live/urgent content
|
||||
- `get_live_modes()`: Return list of modes for live priority
|
||||
- `cleanup()`: Clean up resources on unload
|
||||
- `on_config_change(new_config)`: Handle config updates
|
||||
- `on_enable()`: Called when plugin enabled
|
||||
- `on_disable()`: Called when plugin disabled
|
||||
|
||||
**Available Properties:**
|
||||
- `self.plugin_id`: Plugin identifier
|
||||
- `self.config`: Plugin configuration dict
|
||||
- `self.display_manager`: Display manager instance
|
||||
- `self.cache_manager`: Cache manager instance
|
||||
- `self.plugin_manager`: Plugin manager reference
|
||||
- `self.logger`: Plugin-specific logger
|
||||
- `self.enabled`: Boolean enabled status
|
||||
- `self.transition_manager`: Transition system (if available)
|
||||
|
||||
### Display Manager
|
||||
Located in: `src/display_manager.py`
|
||||
|
||||
**Key Methods:**
|
||||
- `clear()`: Clear the display
|
||||
- `draw_text(text, x, y, color, font, small_font, centered)`: Draw text
|
||||
- `update_display()`: Push the buffer to the physical display
|
||||
- `draw_weather_icon(condition, x, y, size)`: Draw a weather icon
|
||||
- `width`, `height`: Display dimensions
|
||||
|
||||
**Image rendering**: there is no `draw_image()` helper. Paste directly
|
||||
onto the underlying PIL Image:
|
||||
```python
|
||||
self.display_manager.image.paste(pil_image, (x, y))
|
||||
self.display_manager.update_display()
|
||||
```
|
||||
For transparency, paste with a mask: `image.paste(rgba, (x, y), rgba)`.
|
||||
|
||||
### Cache Manager
|
||||
Located in: `src/cache_manager.py`
|
||||
|
||||
**Key Methods:**
|
||||
- `get(key, max_age=300)`: Get cached value (returns None if missing/stale)
|
||||
- `set(key, value, ttl=None)`: Cache a value
|
||||
- `delete(key)` / `clear_cache(key=None)`: Remove a single cache entry,
|
||||
or (for `clear_cache` with no argument) every cached entry. `delete`
|
||||
is an alias for `clear_cache(key)`.
|
||||
- `get_cached_data_with_strategy(key, data_type)`: Cache get with
|
||||
data-type-aware TTL strategy
|
||||
- `get_background_cached_data(key, sport_key)`: Cache get for the
|
||||
background-fetch service path
|
||||
|
||||
## Plugin Manifest Schema
|
||||
|
||||
Required fields in `manifest.json`:
|
||||
- `id`: Unique plugin identifier (matches directory name)
|
||||
- `name`: Human-readable plugin name
|
||||
- `version`: Semantic version (e.g., "1.0.0")
|
||||
- `entry_point`: Python file (usually "manager.py")
|
||||
- `class_name`: Plugin class name (must match class in entry_point)
|
||||
- `display_modes`: Array of mode names this plugin provides
|
||||
|
||||
Common optional fields:
|
||||
- `description`: Plugin description
|
||||
- `author`: Plugin author
|
||||
- `homepage`: Plugin homepage URL
|
||||
- `category`: Plugin category (e.g., "sports", "weather")
|
||||
- `tags`: Array of tags
|
||||
- `update_interval`: Seconds between update() calls (default: 60)
|
||||
- `default_duration`: Default display duration (default: 15)
|
||||
- `requires`: Python version, display size requirements
|
||||
- `config_schema`: Path to config schema file
|
||||
- `api_requirements`: API dependencies and rate limits
|
||||
|
||||
## Plugin Loading Process
|
||||
|
||||
1. **Discovery**: PluginManager scans `plugins/` directory for directories containing `manifest.json`
|
||||
2. **Validation**: Validates manifest structure and required fields
|
||||
3. **Loading**: Imports plugin module and instantiates plugin class
|
||||
4. **Configuration**: Loads plugin config from `config/config.json`
|
||||
5. **Validation**: Calls `validate_config()` on plugin instance
|
||||
6. **Registration**: Adds plugin to available modes and stores instance
|
||||
7. **Enablement**: Calls `on_enable()` if plugin is enabled
|
||||
|
||||
## Common Plugin Patterns
|
||||
|
||||
### Sports Scoreboard Plugin
|
||||
- Use `background_data_service.py` pattern for API fetching
|
||||
- Implement live/recent/upcoming game modes
|
||||
- Use `scoreboard_renderer.py` for consistent rendering
|
||||
- Support team filtering and game filtering
|
||||
- Use shared sports logos from `assets/sports/`
|
||||
|
||||
### Data Display Plugin
|
||||
- Fetch data in `update()` method
|
||||
- Cache API responses using `cache_manager`
|
||||
- Render in `display()` method
|
||||
- Handle API errors gracefully
|
||||
- Provide configuration for refresh intervals
|
||||
|
||||
### Real-time Content Plugin
|
||||
- Implement `has_live_content()` for live priority
|
||||
- Use `get_live_modes()` to specify which modes are live
|
||||
- Set `live_priority: true` in config to enable live takeover
|
||||
- Update data frequently when live content exists
|
||||
|
||||
## Debugging Plugins
|
||||
|
||||
**Check Plugin Loading:**
|
||||
- Review logs for plugin discovery messages
|
||||
- Verify manifest.json syntax is valid JSON
|
||||
- Check that class_name matches actual class name
|
||||
- Ensure entry_point file exists and is importable
|
||||
|
||||
**Check Plugin Execution:**
|
||||
- Add logging statements in `update()` and `display()`
|
||||
- Use `self.logger` for plugin-specific logging
|
||||
- Check cache_manager for cached data
|
||||
- Verify display_manager is rendering correctly
|
||||
|
||||
**Common Issues:**
|
||||
- Import errors: Check Python path and dependencies
|
||||
- Config errors: Validate against config_schema.json
|
||||
- Display issues: Check display dimensions and coordinate calculations
|
||||
- Performance: Monitor CPU/memory usage on Pi
|
||||
|
||||
## Plugin Testing
|
||||
|
||||
**Unit Tests:**
|
||||
- Test plugin class instantiation
|
||||
- Test `update()` data fetching logic
|
||||
- Test `display()` rendering logic
|
||||
- Test `validate_config()` with various configs
|
||||
- Mock `display_manager` and `cache_manager` for testing
|
||||
|
||||
**Integration Tests:**
|
||||
- Test plugin loading via PluginManager
|
||||
- Test plugin with actual config
|
||||
- Test plugin with emulator display
|
||||
- Test plugin with cache_manager
|
||||
|
||||
**Hardware Tests:**
|
||||
- Test on Raspberry Pi with LED matrix
|
||||
- Verify display rendering on actual hardware
|
||||
- Test performance under load
|
||||
- Test with other plugins enabled
|
||||
|
||||
## File Organization
|
||||
|
||||
```
|
||||
plugins/
|
||||
<plugin-id>/
|
||||
manifest.json # Plugin metadata
|
||||
manager.py # Main plugin class
|
||||
config_schema.json # Config validation schema
|
||||
requirements.txt # Python dependencies
|
||||
README.md # Plugin documentation
|
||||
# Plugin-specific files
|
||||
data_manager.py
|
||||
renderer.py
|
||||
etc.
|
||||
```
|
||||
|
||||
## Git Workflow for Plugins
|
||||
|
||||
**Plugin Development:**
|
||||
- Plugins are typically separate repositories
|
||||
- Use `dev_plugin_setup.sh` to link plugins for development
|
||||
- Symlinks are used to connect plugin repos to `plugins/` directory
|
||||
- Plugin repos follow naming: `ledmatrix-<plugin-name>`
|
||||
|
||||
**Branching:**
|
||||
- Develop plugins in feature branches
|
||||
- Follow project branching conventions
|
||||
- Test plugins before merging to main
|
||||
|
||||
**Automatic Version Bumping:**
|
||||
- **Automatic Version Management**: Version bumping is handled automatically via the pre-push git hook - no manual version bumping is required for normal development workflows
|
||||
- **GitHub as Source of Truth**: Plugin store always fetches latest versions from GitHub (releases/tags/manifest/commit)
|
||||
- **Pre-Push Hook**: Automatically bumps patch version and creates git tags when pushing code changes
|
||||
- The hook is self-contained (no external dependencies) and works on any dev machine
|
||||
- Installation: Copy the hook from LEDMatrix repo to your plugin repo:
|
||||
```bash
|
||||
# From your plugin repository directory
|
||||
cp /path/to/LEDMatrix/scripts/git-hooks/pre-push-plugin-version .git/hooks/pre-push
|
||||
chmod +x .git/hooks/pre-push
|
||||
```
|
||||
- Or use the installer script from the main LEDMatrix repo (one-time setup)
|
||||
- The hook automatically:
|
||||
1. Bumps the patch version (x.y.Z) in manifest.json when code changes are detected
|
||||
2. Creates a git tag (v{version}) for the new version
|
||||
3. Stages manifest.json for commit
|
||||
- Skip auto-tagging: Set `SKIP_TAG=1` environment variable before pushing
|
||||
- **Manual Version Bumping (Edge Cases Only)**: Manual version bumps are only needed in rare circumstances:
|
||||
- CI/CD pipelines that bypass git hooks
|
||||
- Forked repositories without the pre-push hook installed
|
||||
- Major/minor version bumps (hook only handles patch versions)
|
||||
- When skipping auto-tagging but still needing a version bump
|
||||
- For manual bumps, use the standalone script: `scripts/bump_plugin_version.py`
|
||||
- **Registry**: The plugin registry (plugins.json) stores only metadata (name, description, repo URL) - no versions
|
||||
- **Version Priority**: Plugin store checks versions in this order: GitHub Releases → GitHub Tags → Manifest from branch → Git commit hash
|
||||
|
||||
## Resources
|
||||
|
||||
- Plugin System Docs: `docs/PLUGIN_ARCHITECTURE_SPEC.md`
|
||||
- Plugin Examples: `plugins/hockey-scoreboard/`, `plugins/football-scoreboard/`
|
||||
- Base Plugin: `src/plugin_system/base_plugin.py`
|
||||
- Plugin Manager: `src/plugin_system/plugin_manager.py`
|
||||
- Development Setup: `dev_plugin_setup.sh`
|
||||
- Example Config: `dev_plugins.json.example`
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
name: Claude Code Review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, ready_for_review, reopened]
|
||||
# Optional: Only run on specific file changes
|
||||
# paths:
|
||||
# - "src/**/*.ts"
|
||||
# - "src/**/*.tsx"
|
||||
# - "src/**/*.js"
|
||||
# - "src/**/*.jsx"
|
||||
|
||||
jobs:
|
||||
claude-review:
|
||||
# Optional: Filter by PR author
|
||||
# if: |
|
||||
# github.event.pull_request.user.login == 'external-contributor' ||
|
||||
# github.event.pull_request.user.login == 'new-developer' ||
|
||||
# github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code Review
|
||||
id: claude-review
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
plugin_marketplaces: 'https://github.com/anthropics/claude-code.git'
|
||||
plugins: 'code-review@claude-code-plugins'
|
||||
prompt: '/code-review:code-review ${{ github.repository }}/pull/${{ github.event.pull_request.number }}'
|
||||
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
|
||||
# or https://code.claude.com/docs/en/cli-reference for available options
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
actions: read # Required for Claude to read CI results on PRs
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
|
||||
# This is an optional setting that allows Claude to read CI results on PRs
|
||||
additional_permissions: |
|
||||
actions: read
|
||||
|
||||
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
|
||||
# prompt: 'Update the pull request description to include a summary of changes.'
|
||||
|
||||
# Optional: Add claude_args to customize behavior and configuration
|
||||
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
|
||||
# or https://code.claude.com/docs/en/cli-reference for available options
|
||||
# claude_args: '--allowed-tools Bash(gh pr *)'
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
name: Release version check
|
||||
|
||||
# A release tag, the CHANGELOG, and src.__version__ must agree. They have not
|
||||
# always: v3.1.0 was tagged while src/__init__.py still said "1.0.0", which
|
||||
# silently exempted every device installed from that release from plugin
|
||||
# compatibility warnings. See docs/SPORTS_UNIFICATION.md (phase B4).
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
release:
|
||||
types: [published]
|
||||
# Pre-flight: run this against the tag you are about to create.
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Tag to check (e.g. v3.2.0)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
version-matches-tag:
|
||||
name: Tag matches src.__version__
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
# No dependencies: the script reads src/__init__.py and CHANGELOG.md only.
|
||||
- name: Assert the tag, CHANGELOG and src.__version__ agree
|
||||
run: python scripts/check_release_version.py "${TAG}"
|
||||
env:
|
||||
TAG: ${{ inputs.tag || github.ref_name }}
|
||||
@@ -0,0 +1,89 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
# Both jobs only check out the repo and run pytest.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
plugin-safety:
|
||||
name: Plugin safety harness + unit tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt -r requirements-test.txt
|
||||
pip install RGBMatrixEmulator
|
||||
|
||||
- name: Run harness + visual rendering tests
|
||||
run: |
|
||||
pytest --no-cov \
|
||||
test/plugins/test_harness.py \
|
||||
test/plugins/test_visual_rendering.py \
|
||||
test/plugins/test_plugin_matrix.py
|
||||
|
||||
unit-tests:
|
||||
name: Core unit tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt -r requirements-test.txt
|
||||
pip install RGBMatrixEmulator
|
||||
|
||||
# Safety net for the shared sports/scroll/style infrastructure. These
|
||||
# suites existed but were not enrolled in CI, so a refactor of
|
||||
# src/base_classes or src/common could regress them silently. Enrolled
|
||||
# explicitly (not `pytest test/`) so known hardware-only suites don't
|
||||
# break CI; grow this list as more suites are made headless.
|
||||
- name: Run core unit suites
|
||||
run: |
|
||||
pytest --no-cov \
|
||||
test/test_skin_system.py \
|
||||
test/test_font_manager.py \
|
||||
test/test_data_sources.py \
|
||||
test/test_api_extractors.py \
|
||||
test/test_scroll_helper.py \
|
||||
test/test_scroll_helper_continuous.py \
|
||||
test/test_adaptive_layout.py \
|
||||
test/test_loader_compat_warning.py \
|
||||
test/test_sports_base_characterization.py \
|
||||
test/test_element_style.py \
|
||||
test/test_sports_core_promotions.py \
|
||||
test/test_sports_modes_promotions.py \
|
||||
test/test_sports_capabilities.py \
|
||||
test/test_sports_scroll.py \
|
||||
test/test_version_consistency.py \
|
||||
test/test_plugin_compatibility_gate.py \
|
||||
test/test_install_preserves_existing.py \
|
||||
test/test_core_owned_config_keys.py \
|
||||
test/test_async_plugin_updates.py \
|
||||
test/test_plugin_update_reservation.py \
|
||||
test/test_template_targets.py \
|
||||
test/test_widget_scripts.py \
|
||||
test/test_doc_links.py \
|
||||
test/web_interface/test_cache.py
|
||||
@@ -8,6 +8,7 @@ config/config_secrets.json
|
||||
config/config.json
|
||||
config/config.json.backup
|
||||
config/wifi_config.json
|
||||
config/uninstalled_plugins.json
|
||||
credentials.json
|
||||
token.pickle
|
||||
|
||||
@@ -47,3 +48,4 @@ config/backups/
|
||||
|
||||
# Starlark apps runtime storage (installed .star files and cached renders)
|
||||
/starlark-apps/
|
||||
skin_renders/
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
# Changelog
|
||||
|
||||
Notable changes to the LEDMatrix core. The version below is the value of
|
||||
`src.__version__`, which the plugin loader reports to compatibility checks and
|
||||
which plugin manifests reference via `ledmatrix_min_version`.
|
||||
|
||||
**Why this file exists:** the plugin monorepo bundles fallback copies of several
|
||||
core modules (see `docs/plugin-development/08-shared-sports-code.md` in
|
||||
[ledmatrix-plugins](https://github.com/ChuckBuilds/ledmatrix-plugins)). A plugin
|
||||
may delete its bundled copy only when its manifest floors on the first core
|
||||
release that ships the module — which requires module additions to be recorded
|
||||
here, against a version number. When you add a module plugins will import via
|
||||
`src.*`, note it in the Unreleased section and bump `src/__init__.py` in the
|
||||
release that ships it.
|
||||
|
||||
**Use `ledmatrix_min_version` in manifests, not `ledmatrix_min`.** The loader
|
||||
accepts both, but the store flags the old spelling as deprecated
|
||||
(`store_manager.py`) and only the new one is in `schema/manifest_schema.json`.
|
||||
|
||||
## 3.2.0
|
||||
|
||||
**The first release shipping the unified sports library.** This is the version
|
||||
a sports plugin floors `ledmatrix_min_version` at before deleting its bundled
|
||||
copy of `sports.py`, `scroll_display.py`, `data_sources.py` or
|
||||
`base_odds_manager.py` — the sunset rule in
|
||||
`docs/plugin-development/08-shared-sports-code.md` keys on exactly this number.
|
||||
|
||||
Adoption is deliberately staged: the modules below ship here, plugins adopt them
|
||||
behind guarded imports, and only then do the bundled copies go away. Nothing in
|
||||
this release changes what an existing plugin loads.
|
||||
|
||||
**This is also the first release that *enforces* `ledmatrix_min_version`.**
|
||||
Before it, the floor was advisory — the loader logged a warning and continued,
|
||||
and the plugin store never compared the core version at all, so an update could
|
||||
deliver a plugin that could not run. From 3.2.0 the store refuses such an
|
||||
install. That matters for the sunset rule: a plugin may only delete its bundled
|
||||
fallback once the cores in the field actually enforce the floor, which means
|
||||
waiting for 3.2.0 to be widely installed rather than merely released. See
|
||||
`docs/SPORTS_UNIFICATION.md`, phase B6.
|
||||
|
||||
One deliberate exception: a core reporting a version below `2.0.0` is treated as
|
||||
*unknown* rather than old and is never blocked. The v3.1.0 release ships
|
||||
`__version__ = "1.0.0"` (the tag was cut before the string was bumped), and
|
||||
nearly every published manifest floors at `2.0.0` — so blocking on that number
|
||||
would lock those users out of the plugin store entirely.
|
||||
|
||||
### Added
|
||||
- `src/element_style.py` — per-element style resolver backing the
|
||||
`x-style-elements` config-schema extension. Already consumed (behind guarded
|
||||
imports with classic fallbacks) by the `of-the-day`, `ledmatrix-music`, and
|
||||
`football-scoreboard` plugins.
|
||||
- Core unit-test CI job enrolling the previously unenrolled suites (skin
|
||||
system, data sources, API extractors, scroll helper, adaptive layout, loader
|
||||
compatibility warning) plus new characterization tests for
|
||||
`src/base_classes/sports.py` ahead of the shared sports-code unification.
|
||||
- `src/base_classes/sports/` — `sports.py` is now a package (`core.py` +
|
||||
`modes.py`). The import path is unchanged: `from src.base_classes.sports
|
||||
import SportsCore` still works.
|
||||
- Nine methods promoted onto the sports base classes from the plugins'
|
||||
bundled copies, plus the override points `_favorite_key`,
|
||||
`_config_schema_path` and `_font_root` and the class attributes
|
||||
`FINAL_PERIOD` / `CLOCK_COUNTS_DOWN`. See `docs/SPORTS_UNIFICATION.md`.
|
||||
A plugin may start calling these once its manifest floors
|
||||
`ledmatrix_min_version` at the release that ships them.
|
||||
|
||||
- `src/base_classes/sports/capabilities/` — opt-in capabilities for the sports
|
||||
scoreboards, composed by inheritance rather than gated by config branches
|
||||
inside the base classes:
|
||||
- `CelebrationMixin` — the score/win takeover, merging the goal and score
|
||||
dialects behind the `score_phrase()` / `win_phrase()` hooks, the
|
||||
`COALESCE_SCORING_SEQUENCE` class attribute and the `_favorite_key` seam.
|
||||
Reads both the `celebrate_opponent_goals` and `celebrate_opponent_scores`
|
||||
config spellings. Sports that do not mix it in have none of this code in
|
||||
their MRO.
|
||||
- `RotationStrategy` + a name registry (`swrr`, `weighted`, `simple`,
|
||||
plus `register_rotation_strategy` for plugin-supplied orderings). Each
|
||||
built-in is verified against a verbatim transcription of the plugin
|
||||
implementation it replaces. An unknown name degrades to `simple`.
|
||||
|
||||
- `src/common/sports_scroll.py` — `SportsScrollDisplay` and
|
||||
`SportsScrollDisplayManager`, the shared scroll **orchestration** layer for
|
||||
the sports scoreboards, plus native support for
|
||||
`global_config['target_fps']` (the bundled plugin copies hardcode ~100 FPS
|
||||
via `scroll_delay` and never consult the global target). Content building
|
||||
(`prepare_scroll_content`, `_load_separator_icons`) is per-sport and stays an
|
||||
override point — see `docs/SPORTS_UNIFICATION.md` for where the line falls
|
||||
and why.
|
||||
|
||||
- `src/plugin_system/compatibility.py` — the single place that answers "can this
|
||||
plugin run on this core?", shared by the loader (advisory, at load time) and
|
||||
the store (blocking, at install/update time) so the two cannot drift. Reads
|
||||
every spelling published manifests use, including the deprecated
|
||||
`versions[].ledmatrix_min`. It does **not** yet evaluate `compatible_versions`,
|
||||
which is the schema-required field and can express upper bounds; closing that
|
||||
is tracked in `docs/SPORTS_UNIFICATION.md` before B6.
|
||||
- `scripts/check_release_version.py` and a `Release version check` workflow —
|
||||
assert that a tag, the newest CHANGELOG heading and `src.__version__` agree,
|
||||
on pushed `v*` tags and published releases. Runnable via `workflow_dispatch`
|
||||
to check a tag *before* creating it. Added because `v3.1.0` was tagged six
|
||||
weeks before `src/__init__.py` was bumped to match, which is why devices
|
||||
installed from that release report `1.0.0`.
|
||||
|
||||
### Changed
|
||||
- `src/__init__.py` bumped to **3.2.0** — the number the sunset rule keys on.
|
||||
- **The plugin store refuses an incompatible install.**
|
||||
`StoreManager.install_plugin` now checks the downloaded manifest's declared
|
||||
floor against `src.__version__` and refuses when the plugin needs a newer
|
||||
core. The check sits in `install_plugin` because `_reinstall_with_rollback`
|
||||
calls it, so a refused *update* restores the version the user already had.
|
||||
Refusal requires evidence: an undeclared floor, an unparseable version on
|
||||
either side, or an untrustworthy core version all allow the install.
|
||||
- **A failed install no longer destroys the plugin it replaced.**
|
||||
`install_plugin` previously deleted the existing plugin directory before
|
||||
downloading, so any later failure — a dropped connection, a malformed
|
||||
manifest, or the new compatibility refusal — left the user with nothing. The
|
||||
existing copy is now set aside and restored if the install fails, matching
|
||||
the protection `_reinstall_with_rollback` already gave the update path.
|
||||
- `web_interface.__version__` re-exports `src.__version__` instead of carrying
|
||||
its own hardcoded `"3.0.0"`, which had drifted two majors from the core.
|
||||
- **Live games are no longer dropped when the feed omits a game clock.**
|
||||
`SportsLive._is_game_really_over` previously (in the baseball and UFC
|
||||
plugin lineages) coerced a missing or non-string clock to the literal
|
||||
`"0:00"` and then treated the game as finished once `period >= 4`. Baseball
|
||||
has no game clock and `period` is the inning, so live MLB games disappeared
|
||||
from the scoreboard from the 5th inning onward; UFC was affected the same
|
||||
way. The clock check is now skipped when the clock is unusable, and the
|
||||
period threshold is the per-sport `FINAL_PERIOD` (hockey ends in P3).
|
||||
Sports whose clocks count up — soccer, AFL, NRL — set
|
||||
`CLOCK_COUNTS_DOWN = False` and never run the check at all, since `0:00`
|
||||
there means kickoff rather than expiry.
|
||||
|
||||
### Fixed
|
||||
- **Plugin updates could hang the web request thread.** The per-plugin reinstall
|
||||
locks were non-reentrant, and `_reinstall_with_rollback` holds one across its
|
||||
call to `install_plugin` — which now takes the same lock to protect the
|
||||
set-aside/restore above. That nesting deadlocked
|
||||
`update_plugin → _reinstall_with_rollback → install_plugin`, the standard
|
||||
path for every monorepo plugin update. The locks are now `RLock`s.
|
||||
- `FontManager` resolves `assets/fonts` against the core install root instead
|
||||
of the process working directory, so font loading works when the process
|
||||
starts elsewhere (e.g. the plugin safety harness on CI).
|
||||
- Hockey events whose competitors carry no `statistics` array are no longer
|
||||
discarded. The extractor read `competitor["statistics"]` unguarded, so a
|
||||
`KeyError` inside the generator dropped the entire event despite valid
|
||||
scores and status; shot counts now fall back to `0`.
|
||||
- Live baseball events that populate status only at the competition level are
|
||||
no longer discarded. The extractor read the event top-level
|
||||
`game_event["status"]` for the inning; real ESPN events duplicate it, but
|
||||
MiLB events synthesized from the MLB Stats API do not, so the lookup raised
|
||||
a bare `KeyError`. It now reads the already-validated competition-level
|
||||
status.
|
||||
- `SportsLive._is_game_really_over` no longer crashes the live-update pass when
|
||||
a feed sends an explicit null `period`. `None >= FINAL_PERIOD` raised
|
||||
`TypeError`, and the only caller (`_detect_stale_games`) has no `try/except`
|
||||
— the same failure shape as the already-fixed null `period_text`.
|
||||
- An expired clock spelled `"00:00"` now ends the game. The check compared the
|
||||
colon-stripped clock against a hand-listed set of literals, which `"0000"` is
|
||||
not a member of, so a finished game with a two-digit-minute clock stayed on
|
||||
the scoreboard indefinitely. The comparison is now numeric.
|
||||
- `SportsCore._load_fonts` resolves `assets/fonts` through the `_font_root()`
|
||||
seam instead of the process working directory. Started outside the install
|
||||
root, every scoreboard font silently degraded to PIL's default bitmap face.
|
||||
- `SportsCore._should_log` no longer raises `AttributeError` on the first
|
||||
warning of a run; `_last_warning_time` is initialized in `__init__` rather
|
||||
than lazily by an unrelated method.
|
||||
- `SportsCore._resolve_project_path` resolved relative logo directories
|
||||
against `<root>/src` instead of the repo root after `sports.py` became a
|
||||
package — the class bodies moved byte-identically but `__file__` gained a
|
||||
directory. Both it and `_font_root` now derive from one `_INSTALL_ROOT`
|
||||
constant.
|
||||
|
||||
## 3.1.0
|
||||
|
||||
Baseline for this changelog. Highlights already shipped at this version:
|
||||
skin system for sports scoreboards (#419), Vegas continuous-scroll overhaul
|
||||
(#423), plugin update surfacing (#421).
|
||||
@@ -6,12 +6,16 @@
|
||||
- `config/config.json` — User plugin configuration (persists across plugin reinstalls)
|
||||
- `plugin-repos/` — **Default** plugin install directory used by the
|
||||
Plugin Store, set by `plugin_system.plugins_directory` in
|
||||
`config.json` (default per `config/config.template.json:130`).
|
||||
`config.json` (default per `config/config.template.json:167`).
|
||||
Not gitignored.
|
||||
- `plugins/` — Legacy/dev plugin location. Gitignored (`plugins/*`).
|
||||
Used by `scripts/dev/dev_plugin_setup.sh` for symlinks. The plugin
|
||||
loader falls back to it when something isn't found in `plugin-repos/`
|
||||
(`src/plugin_system/schema_manager.py:77`).
|
||||
loader does NOT fall back to it — `PluginManager.discover_plugins()`
|
||||
(`src/plugin_system/plugin_manager.py`) scans only the configured
|
||||
directory. Fallbacks exist in two narrower places: store operations
|
||||
(`StoreManager._find_plugin_path()` in `store_manager.py`) and schema
|
||||
lookup (`SchemaManager.get_schema_path()` in `schema_manager.py`,
|
||||
which probes `plugins/` *before* `plugin-repos/`).
|
||||
|
||||
## Plugin System
|
||||
- Plugins inherit from `BasePlugin` in `src/plugin_system/base_plugin.py`
|
||||
@@ -20,6 +24,16 @@
|
||||
- Plugin instantiation args: `plugin_id, config, display_manager, cache_manager, plugin_manager`
|
||||
- Config schemas use JSON Schema Draft-7
|
||||
- Display dimensions: always read dynamically from `self.display_manager.matrix.width/height`
|
||||
- Secrets: namespaced by plugin id in `config/config_secrets.json`, declared
|
||||
via `"x-secret": true` in the plugin's config schema, and deep-merged into
|
||||
the plugin's config dict at load time — plugins read them with plain
|
||||
`config.get(...)`, never a separate accessor
|
||||
|
||||
## Dev Workflow
|
||||
- Link a plugin for development: `./scripts/dev/dev_plugin_setup.sh link-github <name>` (or `link <name> <path>`); symlinks land in `plugins/` — set `plugin_system.plugins_directory` to `plugins` so discovery picks them up
|
||||
- Browser preview without the display loop: `python3 scripts/dev_server.py` → http://localhost:5001
|
||||
- Full display in emulator mode: `python3 run.py -e` (or `EMULATOR=true python3 run.py`)
|
||||
- Validate one plugin headlessly: `python3 scripts/check_plugin.py --plugin <id>`
|
||||
|
||||
## Plugin Store Architecture
|
||||
- Official plugins live in the `ledmatrix-plugins` monorepo (not individual repos)
|
||||
@@ -31,7 +45,18 @@
|
||||
- Plugin configs stored in `config/config.json`, NOT in plugin directories — safe across reinstalls
|
||||
- Third-party plugins can use their own repo URL with empty `plugin_path`
|
||||
|
||||
## Skin System (visual overlays for sports scoreboards)
|
||||
- Skins live in `skins/<skin-id>/` (skin.json + skin.py), NOT in plugin dirs — plugin reinstall deletes plugin dirs
|
||||
- Core: `src/skin_system/` (ScoreboardSkin, SkinContext, runtime); hook: `SportsCore._render_game()` in `src/base_classes/sports/core.py`
|
||||
- Skins render onto `ctx.canvas` only; fallback to built-in renderer on `False`/exception (3 strikes disables for session)
|
||||
- View-model guaranteed keys are frozen (see `test/test_skin_system.py::TestViewModelContract`) — renaming keys in `_extract_game_details_common` or sport extractors breaks published skins
|
||||
- Validate skins headlessly: `python scripts/validate_skin.py --skin <id>`; docs: `docs/SKIN_SYSTEM.md`, `docs/CREATING_SKINS.md`
|
||||
- Skins are NOT monorepo plugins: no manifest bump / update_registry.py needed
|
||||
|
||||
## Common Pitfalls
|
||||
- paho-mqtt 2.x needs `callback_api_version=mqtt.CallbackAPIVersion.VERSION1` for v1 compat
|
||||
- BasePlugin uses `get_logger()` from `src.logging_config`, not standard `logging.getLogger()`
|
||||
- `DisplayManager` has no `draw_image()` — paste onto the PIL image directly:
|
||||
`self.display_manager.image.paste(img, (x, y))` then `update_display()`
|
||||
(use a mask for transparency: `image.paste(rgba, (x, y), rgba)`)
|
||||
- When modifying a plugin in the monorepo, you MUST bump `version` in its `manifest.json` and run `python update_registry.py` — otherwise users won't receive the update
|
||||
|
||||
@@ -40,7 +40,7 @@ improvements, and code changes.
|
||||
## Running the tests
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
pip install -r requirements.txt -r requirements-test.txt
|
||||
pytest
|
||||
```
|
||||
|
||||
@@ -57,9 +57,12 @@ integration tests.
|
||||
`docs/<short-description>`.
|
||||
3. **Keep PRs focused.** One conceptual change per PR. If you find
|
||||
adjacent bugs while working, fix them in a separate PR.
|
||||
4. **Follow the existing code style.** Python code uses standard
|
||||
`black`/`ruff` conventions; HTML/JS in `web_interface/` follows the
|
||||
patterns already in `templates/v3/` and `static/v3/`.
|
||||
4. **Follow the existing code style.** The pre-commit hooks run
|
||||
`flake8` (E9, F63, F7, F82 plus bugbear `B` checks), `mypy` on
|
||||
`src/`, `bandit`, and `gitleaks` — install them with
|
||||
`pre-commit install` so they run on every commit; HTML/JS in
|
||||
`web_interface/` follows the patterns already in `templates/v3/`
|
||||
and `static/v3/`.
|
||||
5. **Update documentation** alongside code changes. If you add a
|
||||
config key, document it in the relevant `*.md` file (or, for
|
||||
plugins, in `config_schema.json` so the form is auto-generated).
|
||||
|
||||
@@ -50,7 +50,15 @@ I'm trying to be open to constructive criticism and support, as long as it's a r
|
||||
|
||||
<details>
|
||||
<summary>Core Features</summary>
|
||||
The following plugins are available inside of the LEDMatrix project. These modular, rotating Displays that can be individually enabled or disabled per the user's needs with some configuration around display durations, teams, stocks, weather, timezones, and more. Displays include:
|
||||
LEDMatrix is a plugin platform: the displays below are plugins installed
|
||||
from the built-in Plugin Store (web interface → Plugins), where each can be
|
||||
individually enabled, ordered, and configured — display durations, teams,
|
||||
stocks, weather, timezones, and more. The core repo ships with just two
|
||||
bundled plugins (`starlark-apps` and `web-ui-info`); the official plugins
|
||||
live in the [ledmatrix-plugins](https://github.com/ChuckBuilds/ledmatrix-plugins)
|
||||
monorepo and install with one click, and third-party plugins can be
|
||||
installed from their own GitHub repositories. Displays available in the
|
||||
store include:
|
||||
|
||||
### Time and Weather
|
||||
- Real-time clock display (2x 64x32 Displays 4mm Pixel Pitch)
|
||||
@@ -141,6 +149,7 @@ The system supports live, recent, and upcoming game information for multiple spo
|
||||
sudo RPI_RGB_FORCE_REBUILD=1 ./first_time_install.sh
|
||||
```
|
||||
- Pi 5 config: leave `rp1_rio` at `0` (PIO mode, default) and set `gpio_slowdown` to `1` or `2`.
|
||||
- **1GB models (Pi 3B / 3B+) and other low-memory boards**: supported, but the `rpi-rgb-led-matrix` C++ build needs more memory than the Pi has. The installer detects this automatically, compiles with fewer parallel jobs, and adds a temporary swapfile for the build which it removes afterwards. Expect that step to take 15-25 minutes instead of 2-5, and leave at least **3GB free** on the SD card. If you manage swap yourself, opt out with `--skip-swap`. To pin the compiler down further, use `--build-jobs 1`.
|
||||
|
||||
|
||||
### RGB Matrix Bonnet / HAT
|
||||
@@ -314,12 +323,12 @@ curl -fsSL https://raw.githubusercontent.com/ChuckBuilds/LEDMatrix/main/scripts/
|
||||
```
|
||||
|
||||
This one-shot installer will automatically:
|
||||
- Check system prerequisites (network, disk space, sudo access)
|
||||
- Check system prerequisites (network, disk space, memory, sudo access)
|
||||
- Install required system packages (git, python3, build tools, etc.)
|
||||
- Clone or update the LEDMatrix repository
|
||||
- Run the complete first-time installation script
|
||||
|
||||
The installation process typically takes 10-30 minutes depending on your internet connection and Pi model. All errors are reported explicitly with actionable fixes.
|
||||
The installation process typically takes 10-30 minutes depending on your internet connection and Pi model. Pi 3B/3B+ and other 1GB boards land at the top of that range, because the C++ library is compiled serially to stay within available memory. All errors are reported explicitly with actionable fixes.
|
||||
|
||||
**Note:** The script is safe to run multiple times and will handle existing installations gracefully.
|
||||
|
||||
@@ -371,6 +380,10 @@ This single script installs services, dependencies, configures permissions and s
|
||||
|
||||
### Initial Setup
|
||||
|
||||
For a complete list of every key in `config.json` and
|
||||
`config_secrets.json`, see
|
||||
[docs/CONFIG_REFERENCE.md](docs/CONFIG_REFERENCE.md).
|
||||
|
||||
For most settings I recommend using the web interface:
|
||||
Edit the project via the web interface at http://[IP ADDRESS or HOSTNAME]:5000 or http://ledpi:5000 .
|
||||
|
||||
@@ -416,7 +429,7 @@ I recommend using the web-ui "Quick Actions" to control the Display.
|
||||
## Plugins
|
||||
|
||||
<details>
|
||||
LEDMatrix uses a plugin-based architecture where all display functionality (except the core calendar) is implemented as plugins. All managers that were previously built into the core system are now available as plugins through the Plugin Store.
|
||||
LEDMatrix uses a plugin-based architecture where all display functionality is implemented as plugins. All managers that were previously built into the core system are now available as plugins through the Plugin Store.
|
||||
|
||||
### Plugin Store
|
||||
See the [Plugin Store documentation](https://github.com/ChuckBuilds/ledmatrix-plugins) for detailed installation instructions.
|
||||
@@ -440,6 +453,16 @@ See the [Plugin Store documentation](https://github.com/ChuckBuilds/ledmatrix-pl
|
||||
|
||||
For plugin development, check out the [Hello World Plugin](https://github.com/ChuckBuilds/ledmatrix-hello-world) repository as a starter template.
|
||||
|
||||
### Visual Skins for Scoreboards
|
||||
|
||||
Want a different look for a sports scoreboard without forking the plugin?
|
||||
**Skins** restyle the live/recent/upcoming screens while the plugin keeps
|
||||
handling data, scheduling, caching, and vegas mode. Install one with
|
||||
`git clone <skin repo> skins/<skin-id>`, select it in the plugin's config,
|
||||
and you're done — see [docs/SKIN_SYSTEM.md](docs/SKIN_SYSTEM.md) (how it
|
||||
works) and [docs/CREATING_SKINS.md](docs/CREATING_SKINS.md) (build your own,
|
||||
including a ready-made Claude Code prompt).
|
||||
|
||||
2. **Built-in Managers Deprecated**: The built-in managers (hockey, football, stocks, etc.) are now deprecated and have been moved to the plugin system. **You must install replacement plugins from the Plugin Store** in the web interface instead. The plugin system provides the same functionality with better maintainability and extensibility.
|
||||
</details>
|
||||
|
||||
@@ -599,12 +622,7 @@ These settings control runtime behavior and GPIO timing:
|
||||
|
||||
### Display Durations (`display.display_durations`)
|
||||
|
||||
Controls how long each display module stays visible in seconds before switching to the next one.
|
||||
|
||||
- **`calendar`** (integer, default: 30)
|
||||
- Duration in seconds for the calendar display
|
||||
- Increase for more time to read dates/events
|
||||
- Decrease to cycle through other displays faster
|
||||
Controls how long each installed plugin stays visible in seconds before switching to the next one, keyed by plugin id.
|
||||
|
||||
- **Plugin-specific durations**
|
||||
- Each plugin can have its own duration setting
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# assets/
|
||||
|
||||
Static assets bundled with LEDMatrix. **Do not delete these directories** —
|
||||
several look unused from core code alone but are resolved at runtime by
|
||||
installed store plugins.
|
||||
|
||||
| Directory | Used by |
|
||||
|---|---|
|
||||
| `fonts/` | Core (`FontManager`, `DisplayManager`) and most plugins |
|
||||
| `sports/` | Core logo tooling (`src/logo_downloader.py`) and the sports scoreboard plugins; team logos are downloaded here on demand |
|
||||
| `stocks/` | `ledmatrix-stocks` plugin (`crypto_icons/`, `ticker_icons/`) |
|
||||
| `weather/` | `ledmatrix-weather` plugin (weather icons) |
|
||||
| `news_logos/` | `news` plugin |
|
||||
| `broadcast_logos/` | `news` and `odds-ticker` plugins |
|
||||
| `static_images/` | Legacy examples referenced in the `static-image` plugin's docs; the plugin itself stores uploads under `assets/plugins/<plugin-id>/uploads/` |
|
||||
| `plugins/` | Per-plugin uploaded files (`assets/plugins/<plugin-id>/uploads/`), served by the web interface |
|
||||
|
||||
Plugins resolve these paths relative to the LEDMatrix install directory, so
|
||||
the directories are part of the de-facto plugin API even where no file in
|
||||
this repo references them. New plugins should bundle their own assets or
|
||||
use the per-plugin upload directory instead of adding top-level
|
||||
directories here.
|
||||
|
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 111 KiB |
|
Before Width: | Height: | Size: 76 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 43 KiB After Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 93 KiB |
|
Before Width: | Height: | Size: 69 KiB After Width: | Height: | Size: 120 KiB |
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 70 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 105 KiB |
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 50 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 87 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 140 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 153 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 91 KiB |
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 9.8 KiB After Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 92 KiB After Width: | Height: | Size: 93 KiB |
|
Before Width: | Height: | Size: 59 KiB After Width: | Height: | Size: 60 KiB |
|
Before Width: | Height: | Size: 80 KiB After Width: | Height: | Size: 41 KiB |
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 77 KiB |
|
Before Width: | Height: | Size: 111 KiB After Width: | Height: | Size: 140 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1,29 @@
|
||||
# bandit.yaml — LEDMatrix bandit configuration
|
||||
# https://bandit.readthedocs.io/en/latest/config.html
|
||||
#
|
||||
# Skips are justified by the specific codebase context documented below.
|
||||
# Do not remove skips without updating the justification comment.
|
||||
|
||||
skips:
|
||||
# B104: Binding to all interfaces (0.0.0.0)
|
||||
# Intentional — the Flask server binds 0.0.0.0 for LAN access on a Raspberry Pi.
|
||||
# This is not internet-facing and is documented in web_interface/app.py.
|
||||
- B104
|
||||
|
||||
# B603: subprocess call without shell=True
|
||||
# All subprocess.run() calls in this codebase use list arguments (confirmed by
|
||||
# grep — zero uses of shell=True in src/ or web_interface/). List args prevent
|
||||
# shell injection. See src/common/permission_utils.py for the primary usage.
|
||||
- B603
|
||||
|
||||
# B607: Starting a process with a partial executable path
|
||||
# The subprocess calls invoke system utilities (systemctl, sudo, git) by name.
|
||||
# These are fixed-list invocations, not user-controlled, and rely on PATH.
|
||||
- B607
|
||||
|
||||
exclude_dirs:
|
||||
- tests
|
||||
- test
|
||||
- venv
|
||||
- .venv
|
||||
- rpi-rgb-led-matrix-master
|
||||
@@ -88,6 +88,7 @@
|
||||
}
|
||||
},
|
||||
"timezone": "America/New_York",
|
||||
"target_fps": 100,
|
||||
"location": {
|
||||
"city": "Tampa",
|
||||
"state": "Florida",
|
||||
@@ -109,13 +110,23 @@
|
||||
"inverse_colors": false,
|
||||
"show_refresh_rate": false,
|
||||
"led_rgb_sequence": "RGB",
|
||||
"limit_refresh_rate_hz": 100
|
||||
"limit_refresh_rate_hz": 100,
|
||||
"pixel_mapper_config": "",
|
||||
"row_address_type": 0,
|
||||
"multiplexing": 0,
|
||||
"panel_type": ""
|
||||
},
|
||||
"runtime": {
|
||||
"gpio_slowdown": 3,
|
||||
"rp1_rio": 0
|
||||
},
|
||||
"double_sided": {
|
||||
"enabled": false,
|
||||
"copies": 2,
|
||||
"axis": "horizontal"
|
||||
},
|
||||
"display_durations": {},
|
||||
"plugin_rotation_order": [],
|
||||
"use_short_date_format": true,
|
||||
"vegas_scroll": {
|
||||
"enabled": false,
|
||||
@@ -124,7 +135,27 @@
|
||||
"plugin_order": [],
|
||||
"excluded_plugins": [],
|
||||
"target_fps": 125,
|
||||
"buffer_ahead": 2
|
||||
"buffer_ahead": 2,
|
||||
"intra_plugin_gap": 8,
|
||||
"render_width_pct": 100,
|
||||
"min_content_separation": 24,
|
||||
"min_cut_gap": 6,
|
||||
"continuous_scroll": true,
|
||||
"smooth_scroll": true,
|
||||
"extend_threshold_screens": 2.0,
|
||||
"auto_trim": true,
|
||||
"trim_threshold": 10,
|
||||
"content_padding": 8,
|
||||
"min_plugin_width": 8,
|
||||
"lead_in_width": 0,
|
||||
"plugins_per_cycle": 6,
|
||||
"max_plugin_width_ratio": 3.0,
|
||||
"overflow_mode": "rotate",
|
||||
"dynamic_duration_enabled": true,
|
||||
"min_cycle_duration": 60,
|
||||
"max_cycle_duration": 240,
|
||||
"frame_based_scrolling": true,
|
||||
"scroll_delay": 0.02
|
||||
}
|
||||
},
|
||||
"sync": {
|
||||
@@ -135,7 +166,8 @@
|
||||
"plugin_system": {
|
||||
"plugins_directory": "plugin-repos",
|
||||
"auto_discover": true,
|
||||
"auto_load_enabled": true
|
||||
"auto_load_enabled": true,
|
||||
"development_mode": false
|
||||
},
|
||||
"web-ui-info": {
|
||||
"enabled": true,
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
{
|
||||
"youtube": {
|
||||
"api_key": "YOUR_YOUTUBE_API_KEY",
|
||||
"channel_id": "YOUR_YOUTUBE_CHANNEL_ID"
|
||||
},
|
||||
"github": {
|
||||
"api_token": "YOUR_GITHUB_PERSONAL_ACCESS_TOKEN"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
# Adaptive Layout & Font Scaling
|
||||
|
||||
`src/adaptive_layout.py` lets a plugin render legibly on **any** panel size
|
||||
(64x32, 128x32, 96x48, 128x64, 256x64, ...) without hand-tuned per-display
|
||||
layouts. It is **opt-in**: nothing changes for plugins that don't use it.
|
||||
|
||||
It generalizes three patterns proven in the plugin ecosystem:
|
||||
|
||||
| Pattern | Origin | Core API |
|
||||
|---|---|---|
|
||||
| Geometry scale factor vs. a design size | f1-scoreboard | `ctx.px(base)` / `ctx.scale` |
|
||||
| Breakpoint tiers | masters-tournament | `ctx.tier` / `ctx.by_tier({...})` |
|
||||
| "Largest crisp font that fits" ladder | baseball-scoreboard | `ctx.fit_text(...)` and friends |
|
||||
|
||||
## Quick start
|
||||
|
||||
Every `BasePlugin` has a lazy `self.layout` (a `LayoutContext` for the
|
||||
current logical display size, rebuilt automatically if the size changes)
|
||||
and a one-liner `self.draw_fit(...)`:
|
||||
|
||||
```python
|
||||
def display(self, force_clear=False):
|
||||
from src.adaptive_layout import LADDER_ARCADE
|
||||
|
||||
b = self.layout.bounds.inset(1) # Region(0,0,W,H) minus 1px margin
|
||||
rows = b.split_v(3, 1, 1, gap=1) # 3/5 for time, 1/5 each for the rest
|
||||
|
||||
self.draw_fit(self.time_str, rows[0], ladder=LADDER_ARCADE)
|
||||
self.draw_fit(self.weekday, rows[1]) # default LADDER_GRID
|
||||
self.draw_fit(self.date_str, rows[2])
|
||||
self.display_manager.update_display()
|
||||
```
|
||||
|
||||
On 128x64 the time renders at press_start 24px; on 64x32 it steps down to
|
||||
8px. The rows partition the height, so bands can never overlap — no more
|
||||
`y = height - 7` magic numbers.
|
||||
|
||||
## Region — rect algebra
|
||||
|
||||
`Region(x, y, w, h)` is a frozen dataclass. All carving clamps to
|
||||
non-negative dimensions, so degenerate panels behave.
|
||||
|
||||
- Carving: `inset(dx, dy)`, `top_band(h)`, `bottom_band(h)`,
|
||||
`middle(top_h, bottom_h)`, `left_col(w)`, `right_col(w)`,
|
||||
`split_h(*weights, gap=0)`, `split_v(*weights, gap=0)`
|
||||
- Placement: `align_xy(w, h, align, valign)`, `center_xy(w, h)`,
|
||||
`contains(w, h)`, `.center`, `.right`, `.bottom`
|
||||
|
||||
Scoreboard-style layout:
|
||||
|
||||
```python
|
||||
b = self.layout.bounds
|
||||
status = b.top_band(self.layout.px(7))
|
||||
detail = b.bottom_band(self.layout.px(7))
|
||||
score_area = b.middle(status.h, detail.h)
|
||||
away_slot, home_slot = b.left_col(b.h), b.right_col(b.h)
|
||||
```
|
||||
|
||||
## Font ladders — discrete, never fractional
|
||||
|
||||
Pixel fonts (BDF, PressStart2P) only look right at native/integer sizes, so
|
||||
fonts are never scaled continuously. A `FontLadder` is an ordered tuple of
|
||||
`FontStep(family, size_px)` rungs, largest first; fitting walks down until
|
||||
the measured text fits.
|
||||
|
||||
- `LADDER_GRID` (default): X11 BDFs at native sizes — 10x20 → 9x18 → 9x15 →
|
||||
8x13 → 7x13 → 6x13 → 6x12 → 6x10 → 6x9 → 5x8 → 5x7 → 4x6 → tom-thumb.
|
||||
Body text, labels, multi-row content.
|
||||
- `LADDER_ARCADE`: PressStart2P at 32/24/16/8 (integer multiples of its 8px
|
||||
grid). Headline text: clocks, scores.
|
||||
|
||||
Custom ladders are just tuples — e.g. to add your plugin's registered font
|
||||
on top: `(FontStep("myplugin::digits", 16),) + LADDER_GRID`.
|
||||
|
||||
## LayoutContext
|
||||
|
||||
Built per (width, height); exposes facts and fit queries:
|
||||
|
||||
- `bounds`, `width`, `height`, `aspect`
|
||||
- `tier` by height (`xs`≤16, `sm`≤32, `md`≤48, `lg`≤64, `xl`) and
|
||||
`width_tier` (`narrow`≤64, `normal`≤128, `wide`≤256, `ultrawide`)
|
||||
- `is_wide_short` — aspect ≥ 2.5 and height ≤ 32 (the classic 128x32 shape)
|
||||
- `scale` — `min(w/design_w, h/design_h)` vs. your manifest's
|
||||
`display.design_size` (default 128x32). **Geometry only** — gaps, icon
|
||||
and logo sizes via `px(base, minimum, maximum)`; fonts use ladders.
|
||||
- `by_tier({"sm": 10, "lg": 18})` — value for the nearest defined tier
|
||||
at-or-below the panel's tier.
|
||||
- `fit_text(text, box, ladder, ellipsis=True)` → `FitResult` — largest rung
|
||||
that fits; ellipsizes as a last resort. Cached per (text, box, ladder).
|
||||
- `fit_text_proportional(text, box, base_size_px, ladder, ellipsis=True, scale=None)` —
|
||||
rung closest to (not exceeding) `base_size_px * scale`, still capped to
|
||||
what fits the box. Use this instead of `fit_text` when several
|
||||
independently-fitted elements need to stay visually harmonious as the
|
||||
panel grows — `fit_text` maximizes *each one* within its own region,
|
||||
which can make one element (e.g. a score with a generous box) balloon
|
||||
out of proportion to a neighbor that scales by geometry (e.g. logos
|
||||
sized via `px()`), even though each individual pick is "correct" in
|
||||
isolation. `base_size_px` is normally the element's existing classic/
|
||||
fixed font size. `scale` defaults to `self.scale` (the conservative
|
||||
min-of-both-axes factor `px()` uses); pass an axis-specific value when
|
||||
the surrounding composition already scales that way — e.g. a scoreboard
|
||||
whose logo slots track height alone (`min(height, width // 2)`) should
|
||||
size its text by `height / design_height` too, or the text reads as
|
||||
under-scaled next to bigger logos on a panel that only grew taller.
|
||||
- `fit_lines(lines, box, ladder, spacing)` — every line fits the width and
|
||||
the stack fits the height (measures the actual strings).
|
||||
- `font_for_rows(rows, box_h, ladder)` — largest rung whose line height
|
||||
fits `rows` rows.
|
||||
|
||||
`FitResult` carries the ready-to-use `font` (drops straight into
|
||||
`display_manager.draw_text(font=...)`), the possibly-ellipsized `text`,
|
||||
ink `width`/`height`, `baseline`, `y_offset`, `line_height`, and `fits`.
|
||||
|
||||
## Adaptive images
|
||||
|
||||
`src/adaptive_images.py` is the image counterpart to `fit_text`, exposed as
|
||||
`self.layout.fit_image(...)` (cached per panel size) and the one-liner
|
||||
`self.draw_image(...)`:
|
||||
|
||||
```python
|
||||
# Team logo: trim its transparent padding, fill the slot height (the
|
||||
# football/hockey pattern), cached across frames by a stable key
|
||||
self.draw_image(logo, regs.away_slot, mode="fill_height",
|
||||
crop_to_ink=True, cache_key=f"logo:{abbr}")
|
||||
|
||||
# Album art: cover-crop a square, faces kept by the top anchor
|
||||
self.draw_image(art, row.art, mode="cover", anchor="top")
|
||||
|
||||
# Pixel flags / sprite icons: NEAREST keeps hard edges
|
||||
from src.adaptive_images import RESAMPLE_NEAREST
|
||||
self.draw_image(flag, box, resample=RESAMPLE_NEAREST)
|
||||
```
|
||||
|
||||
Modes: `contain` (letterbox, default), `cover` (crop-to-fill),
|
||||
`fill_height` (logo-style), `stretch`. Unlike PIL's `thumbnail()`
|
||||
(downscale-only — why imagery stays tiny on big panels) fitting **upscales
|
||||
by default**; pass `upscale=False` for the legacy behavior. Results are
|
||||
cached per (image, box size, options) with a bounded LRU — always pass a
|
||||
stable `cache_key` (e.g. `"logo:KC"`) for images you reload. The module
|
||||
also exports the Pillow-compat `RESAMPLE_LANCZOS`/`RESAMPLE_NEAREST`
|
||||
constants so plugins can drop their local shims.
|
||||
|
||||
## Composite layouts
|
||||
|
||||
Pre-carved Region arrangements for the layouts plugins keep rebuilding:
|
||||
|
||||
```python
|
||||
from src.adaptive_layout import scoreboard_regions, media_row
|
||||
|
||||
regs = scoreboard_regions(self.layout.bounds, ctx=self.layout)
|
||||
# regs.away_slot / home_slot — logo slots (logo_slot = min(H, W // 2),
|
||||
# capped so a center reserve always exists —
|
||||
# see below)
|
||||
# regs.status_band — top band (replaces the magic y = 1)
|
||||
# regs.score_area — center gap, plus a controlled bleed into
|
||||
# each logo slot (replaces y = H//2 - 3)
|
||||
# regs.detail_band — bottom band (replaces y = H - 7)
|
||||
# regs.bottom_left / bottom_right — record/timeout corners
|
||||
|
||||
row = media_row(self.layout.bounds, ctx=self.layout) # art left, text right
|
||||
```
|
||||
|
||||
Both work on the full panel or on a scroll-mode card Region. They return
|
||||
Regions and never draw — compose them with `draw_fit`/`draw_image`.
|
||||
|
||||
**`scoreboard_regions`'s center reserve.** The raw `logo_slot = min(H, W//2)`
|
||||
formula has a blind spot: at exactly 2:1 aspect ratio (width = 2×height —
|
||||
two, four, or more square modules stacked into a taller panel, e.g.
|
||||
96x48, 128x64, 256x128) the two logo slots mathematically claim the
|
||||
*entire* width, leaving zero pixels for a center column no matter how
|
||||
big the panel gets. Wide panels (the 128x32 design baseline, 192x48,
|
||||
256x32) never hit this, since height is already the tighter constraint
|
||||
there. Two parameters fix it without any plugin-side code:
|
||||
`min_center_fraction`/`min_center_design_px` guarantee a real minimum
|
||||
center reserve at any aspect ratio, and `score_bleed_fraction` lets the
|
||||
score's *fit box* extend a controlled amount into each logo slot — the
|
||||
same way a real broadcast scoreboard's numbers cross slightly into the
|
||||
team marks flanking them — so a short score string never has to truncate
|
||||
even on the tightest aspect ratios. All three have sane defaults; override
|
||||
them per call if a plugin's card proportions genuinely differ.
|
||||
|
||||
## Preserving user customization
|
||||
|
||||
Adaptive layout supplies *defaults*; explicit user configuration wins:
|
||||
|
||||
- **User-set fonts win.** If the plugin's config has an explicit
|
||||
`font`/`font_size` for an element, load it as before and skip the ladder —
|
||||
fit only when the user hasn't overridden (see the football-scoreboard
|
||||
`_resolve_element_fit` pattern).
|
||||
- **Offsets apply on top.** `customization.layout.<element>.{x_offset,y_offset}`
|
||||
style knobs translate the *computed* region as a final step:
|
||||
`region.offset(user_dx, user_dy)`. `draw_image(..., offset=(dx, dy))`
|
||||
does the same for images.
|
||||
- **Colors pass through.** `draw_fit`/`draw_fitted_text` take explicit
|
||||
`color=` params; adaptive mode never repaints semantic or user-chosen
|
||||
colors.
|
||||
|
||||
## Manifest declaration
|
||||
|
||||
Declare the size your layout was authored against so `ctx.scale` means
|
||||
something:
|
||||
|
||||
```json
|
||||
"display": { "design_size": { "width": 128, "height": 32 } }
|
||||
```
|
||||
|
||||
Also available under `requires.display_size`: `min_width`, `min_height`,
|
||||
`max_width`, `max_height`.
|
||||
|
||||
## Performance notes (Pi)
|
||||
|
||||
Fit queries are cached, so cost is O(unique strings). For per-second text
|
||||
(clocks, live scores), fit on a **shape placeholder** and reuse the font:
|
||||
|
||||
```python
|
||||
fit = self.layout.fit_text("00:00", box, ladder=LADDER_ARCADE) # cached once
|
||||
self.display_manager.draw_text(current_time, font=fit.font, ...)
|
||||
```
|
||||
|
||||
## Testing across sizes
|
||||
|
||||
The harness already renders every plugin at a spread of sizes (now
|
||||
including 96x48):
|
||||
|
||||
```bash
|
||||
python scripts/check_plugin.py <plugin-dir> --sizes 64x32,128x32,96x48,128x64,256x64
|
||||
python scripts/render_plugin.py <plugin-dir> --width 96 --height 48
|
||||
```
|
||||
|
||||
`BoundsCheckingDisplayManager` flags right/bottom overflow and now records
|
||||
mediated draw calls with negative coordinates in
|
||||
`negative_coordinate_calls` (raw-PIL draws remain uncovered).
|
||||
|
||||
Reference migration: the **text-display** plugin's `font_mode: "auto"`.
|
||||
@@ -47,6 +47,11 @@ Enable Vegas mode in `config/config.json`:
|
||||
}
|
||||
```
|
||||
|
||||
Vegas mode can also be configured entirely from the web UI — the
|
||||
**Display** tab has a Vegas Scroll Mode section (enable toggle, scroll
|
||||
speed, separator width, dynamic duration, and more), so hand-editing
|
||||
JSON is optional.
|
||||
|
||||
**Configuration Options:**
|
||||
|
||||
| Setting | Default | Description |
|
||||
@@ -57,7 +62,11 @@ Enable Vegas mode in `config/config.json`:
|
||||
| `plugin_order` | `[]` | Plugin display order (empty = auto) |
|
||||
| `excluded_plugins` | `[]` | Plugins to exclude from Vegas mode |
|
||||
| `target_fps` | `125` | Target frame rate |
|
||||
| `buffer_ahead` | `2` | Number of panels to render ahead |
|
||||
| `buffer_ahead` | `2` | Number of plugins buffered ahead |
|
||||
|
||||
This table is a subset — `display.vegas_scroll` supports 26 keys in
|
||||
total. See the full list in
|
||||
[CONFIG_REFERENCE.md](CONFIG_REFERENCE.md#displayvegas_scroll--continuous-scroll-mode).
|
||||
|
||||
### Per-Plugin Configuration
|
||||
|
||||
@@ -79,9 +88,13 @@ Override Vegas behavior for specific plugins:
|
||||
| Setting | Values | Description |
|
||||
|---------|--------|-------------|
|
||||
| `vegas_mode` | `scroll`, `fixed`, `static` | Display mode for this plugin |
|
||||
| `vegas_panel_count` | `1-10` | Width in panels (1 panel = display width) |
|
||||
| `vegas_panel_count` | any positive integer | Width in panels (1 panel = display width) |
|
||||
| `display_duration` | seconds | Pause duration for STATIC mode |
|
||||
|
||||
Plugins may also set `vegas_overflow` and `vegas_max_width_screens` in
|
||||
their config section to control how oversized content is handled (see
|
||||
`PluginManager` in `src/plugin_system/plugin_manager.py`).
|
||||
|
||||
### Plugin Integration (Developer Guide)
|
||||
|
||||
**1. Implement Content Method:**
|
||||
@@ -451,7 +464,7 @@ time when something is active.
|
||||
|
||||
### REST API Reference
|
||||
|
||||
The API is mounted at `/api/v3` (`web_interface/app.py:144`).
|
||||
The API is mounted at `/api/v3` (`web_interface/app.py:199`).
|
||||
|
||||
#### Start On-Demand Display
|
||||
|
||||
@@ -518,13 +531,15 @@ curl http://localhost:5000/api/v3/display/on-demand/status
|
||||
|
||||
> There is no public Python on-demand API. The display controller's
|
||||
> on-demand machinery is internal — drive it through the REST endpoints
|
||||
> above (or the web UI buttons), which write a request into the cache
|
||||
> manager under the `display_on_demand_request` key
|
||||
> (`web_interface/blueprints/api_v3.py:1622,1687`) that the controller
|
||||
> polls at `src/display_controller.py:921`. A separate
|
||||
> above (or the web UI buttons). The API handlers
|
||||
> (`start_on_demand_display()` / `stop_on_demand_display()` in
|
||||
> `web_interface/blueprints/api_v3.py`) write a request into the cache
|
||||
> manager under the `display_on_demand_request` key, which
|
||||
> `DisplayController._poll_on_demand_requests()`
|
||||
> (`src/display_controller.py`) picks up. A separate
|
||||
> `display_on_demand_config` key is used by the controller itself
|
||||
> during activation to track what's currently running (written at
|
||||
> `display_controller.py:1195`, cleared at `:1221`).
|
||||
> during activation (`_activate_on_demand()`) to track what's
|
||||
> currently running, and is cleared by `_clear_on_demand()`.
|
||||
|
||||
### Duration Modes
|
||||
|
||||
@@ -646,13 +661,13 @@ keys helps troubleshoot stuck states.
|
||||
**When Set:** Every display loop iteration
|
||||
**Auto-Cleared:** Never (continuously updated)
|
||||
|
||||
**4. display_on_demand_processed_id** (TTL: 5 minutes)
|
||||
**4. display_on_demand_processed_id** (TTL: 1 hour)
|
||||
```
|
||||
"uuid-string-of-last-processed-request"
|
||||
```
|
||||
**Purpose:** Prevents duplicate request processing
|
||||
**When Set:** After processing request
|
||||
**Auto-Cleared:** After 5 minutes TTL
|
||||
**Auto-Cleared:** After 1 hour TTL
|
||||
|
||||
### When Manual Clearing is Needed
|
||||
|
||||
@@ -685,9 +700,9 @@ keys helps troubleshoot stuck states.
|
||||
The cache is stored as JSON files under one of:
|
||||
|
||||
- `/var/cache/ledmatrix/` (preferred when the service has permission)
|
||||
- `~/.cache/ledmatrix/`
|
||||
- `~/.ledmatrix_cache/`
|
||||
- `/opt/ledmatrix/cache/`
|
||||
- `/tmp/ledmatrix-cache/` (fallback)
|
||||
- `$TMPDIR/ledmatrix_cache/` (fallback)
|
||||
|
||||
```bash
|
||||
# Find the cache dir actually in use
|
||||
@@ -711,8 +726,9 @@ cache.clear_cache('display_on_demand_request')
|
||||
cache.clear_cache('display_on_demand_processed_id')
|
||||
```
|
||||
|
||||
> The actual public method is `clear_cache(key=None)` — there is no
|
||||
> `delete()` method on `CacheManager`.
|
||||
> `CacheManager` also has a `delete(key)` method — a thin wrapper over
|
||||
> `clear_cache(key)` — so `cache.delete('display_on_demand_config')`
|
||||
> works equally well.
|
||||
|
||||
### Cache Impact on Running Service
|
||||
|
||||
@@ -730,7 +746,7 @@ The display controller automatically handles cleanup:
|
||||
- **Config key**: Cleared when on-demand stops
|
||||
- **State key**: Updated every display loop iteration
|
||||
- **Request key**: Expires after 1 hour TTL (or after processing)
|
||||
- **Processed ID**: Expires after 5 minutes TTL
|
||||
- **Processed ID**: Expires after 1 hour TTL
|
||||
|
||||
---
|
||||
|
||||
@@ -821,9 +837,6 @@ same shape as the example above.
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Run background service test
|
||||
python test_background_service.py
|
||||
|
||||
# Check logs for background operations
|
||||
sudo journalctl -u ledmatrix -f | grep "background"
|
||||
```
|
||||
@@ -832,9 +845,10 @@ sudo journalctl -u ledmatrix -f | grep "background"
|
||||
|
||||
**View Statistics:**
|
||||
```python
|
||||
from src.background_data_service import BackgroundDataService
|
||||
from src.background_data_service import get_background_service
|
||||
from src.cache_manager import CacheManager
|
||||
|
||||
service = BackgroundDataService()
|
||||
service = get_background_service(CacheManager())
|
||||
stats = service.get_statistics()
|
||||
print(f"Active tasks: {stats['active_tasks']}")
|
||||
print(f"Completed: {stats['completed']}")
|
||||
@@ -875,6 +889,7 @@ from src.common.permission_utils import (
|
||||
ensure_file_permissions,
|
||||
get_config_file_mode,
|
||||
get_assets_file_mode,
|
||||
get_assets_dir_mode,
|
||||
get_plugin_file_mode,
|
||||
get_cache_dir_mode
|
||||
)
|
||||
@@ -883,7 +898,10 @@ from src.common.permission_utils import (
|
||||
ensure_directory_permissions(Path("assets/sports"), get_assets_dir_mode())
|
||||
|
||||
# Set file permissions after writing
|
||||
ensure_file_permissions(Path("config/config.json"), get_config_file_mode())
|
||||
# (get_config_file_mode requires the file path — secrets files get a
|
||||
# stricter mode than the main config)
|
||||
config_path = Path("config/config.json")
|
||||
ensure_file_permissions(config_path, get_config_file_mode(config_path))
|
||||
```
|
||||
|
||||
### When to Use Utilities
|
||||
@@ -938,7 +956,7 @@ from src.common.permission_utils import ensure_file_permissions, get_config_file
|
||||
config_path = Path("config/config.json")
|
||||
with open(config_path, 'w') as f:
|
||||
json.dump(data, f)
|
||||
ensure_file_permissions(config_path, get_config_file_mode())
|
||||
ensure_file_permissions(config_path, get_config_file_mode(config_path))
|
||||
```
|
||||
|
||||
**Pattern 3: Downloading Logo**
|
||||
@@ -984,8 +1002,11 @@ These core utilities **already handle permissions** - you don't need to call per
|
||||
If you encounter permission issues:
|
||||
|
||||
```bash
|
||||
# Fix all permissions at once
|
||||
sudo ./scripts/fix_permissions.sh
|
||||
# Targeted permission fixes (see scripts/fix_perms/README.md)
|
||||
sudo ./scripts/fix_perms/fix_assets_permissions.sh # assets/ tree (logos, fonts)
|
||||
sudo ./scripts/fix_perms/fix_cache_permissions.sh # all cache directories
|
||||
sudo ./scripts/fix_perms/fix_plugin_permissions.sh # plugin directories
|
||||
sudo ./scripts/fix_perms/fix_web_permissions.sh # web interface files
|
||||
|
||||
# Fix specific directory
|
||||
sudo chown -R ledpi:ledpi /home/ledpi/LEDMatrix/config
|
||||
@@ -1017,7 +1038,7 @@ stat -c "%a %n" config/config.json
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [PLUGIN_DEVELOPMENT.md](PLUGIN_DEVELOPMENT.md) - Creating plugins with Vegas/on-demand support
|
||||
- [PLUGIN_DEVELOPMENT_GUIDE.md](PLUGIN_DEVELOPMENT_GUIDE.md) - Creating plugins with Vegas/on-demand support
|
||||
- [WEB_INTERFACE_GUIDE.md](WEB_INTERFACE_GUIDE.md) - Using on-demand controls in web UI
|
||||
- [PLUGIN_API_REFERENCE.md](PLUGIN_API_REFERENCE.md) - Complete API documentation
|
||||
- [DEVELOPMENT.md](DEVELOPMENT.md) - Development environment and testing
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
Advanced patterns, examples, and best practices for developing LEDMatrix plugins.
|
||||
|
||||
> **Adaptive layout:** for plugins that should render legibly on any panel
|
||||
> size (fonts that grow on big panels, layouts that degrade gracefully on
|
||||
> small ones), use the adaptive layout system — `self.layout`, `draw_fit`,
|
||||
> `draw_image`, `scoreboard_regions` — documented in
|
||||
> [ADAPTIVE_LAYOUT.md](ADAPTIVE_LAYOUT.md).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Using Weather Icons](#using-weather-icons)
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
# Configuration Reference
|
||||
|
||||
Every key in `config/config.json`, what it does, its default, and where the
|
||||
code reads it. The file is created from `config/config.template.json` on
|
||||
first run, and `ConfigManager._migrate_config()` merges any template keys
|
||||
added by later releases into your existing config (your values are never
|
||||
overwritten). Secrets live in `config/config_secrets.json` and are merged
|
||||
into the config at load time.
|
||||
|
||||
Most settings are editable from the web interface; this page documents the
|
||||
underlying keys for people editing `config.json` directly or writing
|
||||
tooling against it.
|
||||
|
||||
## Top level
|
||||
|
||||
| Key | Type / default | Meaning | Read by |
|
||||
|---|---|---|---|
|
||||
| `web_display_autostart` | bool, `true` | Whether the web interface service starts with the system | `scripts/utils/start_web_conditionally.py` |
|
||||
| `timezone` | string, `"America/New_York"` | IANA timezone for schedules and displays | `ConfigManager.get_timezone()` |
|
||||
| `target_fps` | int, `100` | Frame-rate ceiling for plugin rendering | `src/plugin_system/base_plugin.py`, `src/common/sports_scroll.py` |
|
||||
| `location` | object | `city` / `state` / `country`, offered to plugins that need a location (weather, etc.) | plugins via merged config |
|
||||
|
||||
## `schedule` — display on/off hours
|
||||
|
||||
| Key | Type / default | Meaning |
|
||||
|---|---|---|
|
||||
| `enabled` | bool, `false` | Master switch for scheduled display on/off |
|
||||
| `mode` | `"global"` or `"per-day"`, template uses `"per-day"` | Whether one time range applies to all days or each day has its own |
|
||||
| `start_time` / `end_time` | `"HH:MM"`, `07:00`–`23:00` | Global-mode on/off times |
|
||||
| `days.<weekday>.{enabled,start_time,end_time}` | per-day objects | Per-day-mode overrides |
|
||||
|
||||
Read by `DisplayController` (`src/display_controller.py`, `_check_schedule`
|
||||
around line 603). Managed in the web UI under Schedule.
|
||||
|
||||
## `dim_schedule` — scheduled brightness dimming
|
||||
|
||||
Same shape as `schedule`, plus:
|
||||
|
||||
| Key | Type / default | Meaning |
|
||||
|---|---|---|
|
||||
| `dim_brightness` | int, `30` | Brightness percentage applied while the dim window is active |
|
||||
|
||||
Read by `DisplayController` (`src/display_controller.py` around line 770;
|
||||
saved via `POST /api/v3/config/dim-schedule`). The display returns to
|
||||
`display.hardware.brightness` outside the window.
|
||||
|
||||
## `display.hardware` — matrix panel hardware
|
||||
|
||||
All keys map to the corresponding `rpi-rgb-led-matrix` options and are read
|
||||
in `DisplayManager` (`src/display_manager.py`, ~lines 270–295).
|
||||
|
||||
| Key | Type / default |
|
||||
|---|---|
|
||||
| `rows` / `cols` | int, `32` / `64` |
|
||||
| `chain_length` | int, `2` |
|
||||
| `parallel` | int, `1` |
|
||||
| `brightness` | int, `90` |
|
||||
| `hardware_mapping` | string, `"adafruit-hat"` (code default `"adafruit-hat-pwm"`) |
|
||||
| `scan_mode` | int, `0` |
|
||||
| `pwm_bits` | int, `9` (code default 10) |
|
||||
| `pwm_dither_bits` | int, `1` |
|
||||
| `pwm_lsb_nanoseconds` | int, `130` (code default 150) |
|
||||
| `disable_hardware_pulsing` | bool, `false` |
|
||||
| `inverse_colors` | bool, `false` |
|
||||
| `show_refresh_rate` | bool, `false` |
|
||||
| `led_rgb_sequence` | string, `"RGB"` |
|
||||
| `limit_refresh_rate_hz` | int, `100` (code default 90) |
|
||||
| `pixel_mapper_config` | string, `""` — e.g. `"U-mapper"` / `"Rotate:90"` |
|
||||
| `row_address_type` | int, `0` — non-standard panel row addressing |
|
||||
| `multiplexing` | int, `0` — panel multiplexing scheme |
|
||||
| `panel_type` | string, `""` — set to `"FM6126A"` or `"FM6127"` for panels needing init |
|
||||
|
||||
Where "code default" differs from the template value, the code default only
|
||||
applies if the key is missing entirely from your config.
|
||||
|
||||
## `display.runtime`
|
||||
|
||||
| Key | Type / default | Meaning |
|
||||
|---|---|---|
|
||||
| `gpio_slowdown` | int, `3` | GPIO timing slowdown for faster Pis |
|
||||
| `rp1_rio` | int, `0` | RP1 RIO mode on Pi 5 (applied only if the installed matrix library supports it) |
|
||||
|
||||
## `display.double_sided`
|
||||
|
||||
Drives `_LogicalMatrix` in `src/display_manager.py` — renders the same
|
||||
logical image to multiple chained physical panels.
|
||||
|
||||
| Key | Type / default | Meaning |
|
||||
|---|---|---|
|
||||
| `enabled` | bool, `false` | Mirror output across panel copies |
|
||||
| `copies` | int, `2` | Number of physical copies in the chain |
|
||||
| `axis` | `"horizontal"`, default | Axis along which panels are chained |
|
||||
|
||||
## `display` — other keys
|
||||
|
||||
| Key | Type / default | Meaning | Read by |
|
||||
|---|---|---|---|
|
||||
| `display_durations` | object, `{}` | Per-plugin display duration in seconds, keyed by plugin id (e.g. `"clock": 15`) | `src/display_controller.py:1030` |
|
||||
| `plugin_rotation_order` | array, `[]` | Explicit rotation order of plugin ids; empty = all enabled plugins in discovery order | `src/display_controller.py:2894` |
|
||||
| `use_short_date_format` | bool, `true` | Compact date rendering in sports scoreboards | `src/base_classes/sports/core.py` |
|
||||
| `dynamic_duration.max_duration_seconds` | int, optional | Cap for plugins that request dynamic display time | `src/display_controller.py:405` |
|
||||
|
||||
## `display.vegas_scroll` — continuous scroll mode
|
||||
|
||||
Read by `src/vegas_mode/config.py` (`VegasScrollConfig.from_config`). See
|
||||
[ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) for behavior details.
|
||||
|
||||
| Key | Type / default |
|
||||
|---|---|
|
||||
| `enabled` | bool, `false` |
|
||||
| `scroll_speed` | int, `50` (px/s) |
|
||||
| `separator_width` | int, `32` |
|
||||
| `plugin_order` | array, `[]` |
|
||||
| `excluded_plugins` | array, `[]` |
|
||||
| `target_fps` | int, `125` |
|
||||
| `buffer_ahead` | int, `2` |
|
||||
| `intra_plugin_gap` | int, `8` |
|
||||
| `render_width_pct` | int, `100` |
|
||||
| `min_content_separation` | int, `24` |
|
||||
| `min_cut_gap` | int, `6` |
|
||||
| `continuous_scroll` | bool, `true` |
|
||||
| `smooth_scroll` | bool, `true` |
|
||||
| `extend_threshold_screens` | float, `2.0` |
|
||||
| `auto_trim` | bool, `true` |
|
||||
| `trim_threshold` | int, `10` |
|
||||
| `content_padding` | int, `8` |
|
||||
| `min_plugin_width` | int, `8` |
|
||||
| `lead_in_width` | int, `0` |
|
||||
| `plugins_per_cycle` | int, `6` |
|
||||
| `max_plugin_width_ratio` | float, `3.0` |
|
||||
| `overflow_mode` | string, `"rotate"` |
|
||||
| `dynamic_duration_enabled` | bool, `true` |
|
||||
| `min_cycle_duration` | int, `60` |
|
||||
| `max_cycle_duration` | int, `240` |
|
||||
| `frame_based_scrolling` | bool, `true` — frame-count-based scroll stepping |
|
||||
| `scroll_delay` | float, `0.02` — seconds between scroll updates (~50 FPS) |
|
||||
|
||||
## `sync` — multi-display synchronization
|
||||
|
||||
Read by `src/common/sync_manager.py` and `src/display_controller.py`.
|
||||
|
||||
| Key | Type / default | Meaning |
|
||||
|---|---|---|
|
||||
| `role` | `"standalone"` (default), `"leader"`, or `"follower"` | This device's role in a synced pair |
|
||||
| `port` | int, `5765` | TCP port used for sync traffic |
|
||||
| `follower_position` | `"left"` (default) or `"right"` | Which half of the combined image this follower renders (`src/display_controller.py:522`) |
|
||||
|
||||
## `plugin_system`
|
||||
|
||||
Read by the plugin loader/manager (`src/plugin_system/`).
|
||||
|
||||
| Key | Type / default | Meaning |
|
||||
|---|---|---|
|
||||
| `plugins_directory` | string, `"plugin-repos"` | Where the Plugin Store installs plugins |
|
||||
| `auto_discover` | bool, `true` | Scan the plugins directory at startup |
|
||||
| `auto_load_enabled` | bool, `true` | Load discovered plugins automatically |
|
||||
| `development_mode` | bool, `false` | Development conveniences in the web UI (editable under General settings) |
|
||||
|
||||
## Plugin config blocks
|
||||
|
||||
Every installed plugin stores its settings under a top-level key equal to
|
||||
its plugin id (the template ships one for the bundled `web-ui-info`
|
||||
plugin). The shape of each block is defined by that plugin's
|
||||
`config_schema.json`; common keys are `enabled` and `display_duration`.
|
||||
See [PLUGIN_CONFIG_CORE_PROPERTIES.md](PLUGIN_CONFIG_CORE_PROPERTIES.md).
|
||||
|
||||
## `config/config_secrets.json`
|
||||
|
||||
| Key | Meaning |
|
||||
|---|---|
|
||||
| `github.api_token` | Optional GitHub token the Plugin Store uses to avoid API rate limits (`src/plugin_system/store_manager.py:348`) |
|
||||
| `<plugin-id>.*` | Secrets a plugin declares with `"x-secret": true` in its config schema; merged into that plugin's config at load time |
|
||||
@@ -0,0 +1,242 @@
|
||||
# Creating Skins
|
||||
|
||||
A skin restyles a sports scoreboard (live / recent / upcoming) without
|
||||
forking the plugin: the plugin keeps fetching data, scheduling, caching, and
|
||||
doing vegas mode; your skin only draws. Architecture background:
|
||||
[SKIN_SYSTEM.md](SKIN_SYSTEM.md).
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cp -r skins/example-classic-baseball skins/my-skin
|
||||
# edit skins/my-skin/skin.json -> set id ("my-skin"), name, author, class_name
|
||||
# edit skins/my-skin/skin.py -> rename the class, start restyling
|
||||
python scripts/validate_skin.py --skin my-skin
|
||||
```
|
||||
|
||||
The validator renders your skin against bundled fixture games at several
|
||||
panel sizes with **no hardware, no network, no running service**, saves PNGs
|
||||
(plus 4x previews) to `skin_renders/`, and fails loudly on errors. Iterate:
|
||||
edit → validate → look at the PNGs.
|
||||
|
||||
To see it on your matrix, add to your plugin's section in `config/config.json`:
|
||||
|
||||
```json
|
||||
"baseball-scoreboard": {
|
||||
"skin": "my-skin",
|
||||
"skin_options": { }
|
||||
}
|
||||
```
|
||||
|
||||
or pick it from the **Visual Skin** dropdown in the web UI (it appears once a
|
||||
matching skin is installed). `"skin"` also accepts a per-mode mapping:
|
||||
`{"live": "my-skin", "recent": "built-in"}`.
|
||||
|
||||
## The manifest (`skin.json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-skin",
|
||||
"name": "My Skin",
|
||||
"version": "1.0.0",
|
||||
"author": "you",
|
||||
"description": "What it looks like",
|
||||
"skin_api_version": "1.0.0",
|
||||
"targets": {
|
||||
"sports": ["baseball"],
|
||||
"sport_keys": ["mlb", "milb"],
|
||||
"plugins": []
|
||||
},
|
||||
"entry_point": "skin.py",
|
||||
"class_name": "MySkin",
|
||||
"modes": ["live", "recent", "upcoming"],
|
||||
"preview": "preview.png"
|
||||
}
|
||||
```
|
||||
|
||||
Field notes: `id` must equal the directory name; `skin_api_version`'s major
|
||||
version must match the host's `SKIN_API_VERSION` or the skin is refused at
|
||||
load; `targets` takes sport families (`sports`), exact sport keys
|
||||
(`sport_keys`), and/or exact plugin ids (`plugins`) — any match applies.
|
||||
|
||||
## The renderer (`skin.py`)
|
||||
|
||||
```python
|
||||
from src.skin_system.skin_base import ScoreboardSkin, SkinContext
|
||||
|
||||
class MySkin(ScoreboardSkin):
|
||||
def render_live(self, ctx: SkinContext, game: dict) -> bool:
|
||||
score = f"{game.get('away_score', '0')}-{game.get('home_score', '0')}"
|
||||
fit = ctx.layout.fit_text(score, ctx.layout.bounds)
|
||||
ctx.draw_fit(fit, ctx.layout.bounds)
|
||||
return True # True = "I drew it"; False = use the built-in layout
|
||||
```
|
||||
|
||||
Implement only the modes you care about — anything else falls back to the
|
||||
plugin's built-in rendering. Return `False` to decline a specific game (e.g.
|
||||
a layout that only makes sense while a game is live).
|
||||
|
||||
### The rules (they keep your skin from breaking the display)
|
||||
|
||||
1. **Draw only onto `ctx.canvas`** (via the helpers or `ctx.draw`). Never
|
||||
reassign `ctx.canvas`, never touch the display or call any update method.
|
||||
2. **No I/O in render paths.** No network, no file loads per frame —
|
||||
`render_live` runs every display pass, and a slow render stalls the whole
|
||||
matrix (the host warns at >150 ms). Use `ctx.load_logo` (cached) and
|
||||
`cache_key=` for images.
|
||||
3. **Derive everything from `(ctx, game)`.** Skins must be stateless: the
|
||||
live/recent/upcoming modes each get their own instance.
|
||||
4. **Always `.get()` optional keys.** Only the guaranteed keys below are
|
||||
promised to exist.
|
||||
5. **Never hardcode pixel positions for the panel.** Use `ctx.width`/
|
||||
`ctx.height`, `ctx.layout` regions and `fit_text` — your skin will be run
|
||||
at sizes you didn't test (64x32, 128x64, vegas cards).
|
||||
6. **No third-party dependencies.** Stdlib + PIL + what `ctx` provides.
|
||||
|
||||
A skin that raises 3 renders in a row is disabled until the service restarts
|
||||
(the built-in layout takes over), so a bug is cosmetic — but check your logs.
|
||||
|
||||
## SkinContext reference
|
||||
|
||||
| Member | What it is |
|
||||
|---|---|
|
||||
| `ctx.canvas` / `ctx.draw` | Fresh RGB `PIL.Image` at display size + its `ImageDraw` (raw-PIL escape hatch) |
|
||||
| `ctx.width`, `ctx.height` | Canvas size — the only size truth |
|
||||
| `ctx.layout` | `LayoutContext` (see [ADAPTIVE_LAYOUT.md](ADAPTIVE_LAYOUT.md)): `bounds`, `fit_text`, `fit_text_proportional`, `fit_image`, `px`, `by_tier` |
|
||||
| `ctx.draw_fit(fit, box, color, align, valign)` | Draw a `fit_text` result aligned in a `Region` (handles BDF fonts) |
|
||||
| `ctx.draw_text(text, x, y, color, font)` | Positioned text (handles BDF fonts) |
|
||||
| `ctx.draw_image(img, box, mode, align, valign, cache_key)` | Fit + paste an image with alpha; no-ops on `None` |
|
||||
| `ctx.load_logo("home" \| "away")` | Team logo as RGBA, or `None` (always handle `None`). Cached after first use; see note below |
|
||||
| `ctx.draw_text_outlined(text, (x, y), font, fill, outline_color)` | The classic scorebug outlined text (TTF fonts only) |
|
||||
| `ctx.fonts` | The host's font dict — keys `score`, `time`, `team`, `status`, `detail`, `rank` |
|
||||
| `ctx.options` | Your user's `skin_options` from config |
|
||||
| `ctx.sport`, `ctx.view_model_version`, `ctx.logger` | Context metadata + logger |
|
||||
|
||||
**A note on `ctx.load_logo` vs the no-I/O rule:** `load_logo` is the one
|
||||
sanctioned exception. It goes through the host's logo cache — after the
|
||||
first call per team it's a pure in-memory lookup. If a logo file is missing
|
||||
on disk, the *first* call may download it, exactly like the built-in
|
||||
renderer does for the same game (a skin is never worse than built-in here).
|
||||
Always pass a stable `cache_key` when drawing it, never load image files
|
||||
yourself in a render path, and always handle `None`.
|
||||
|
||||
The default layout idiom — carve regions, then fit text into them:
|
||||
|
||||
```python
|
||||
from src.adaptive_layout import scoreboard_regions
|
||||
|
||||
regions = scoreboard_regions(ctx.layout.bounds, ctx=ctx.layout)
|
||||
ctx.draw_image(ctx.load_logo("away"), regions.away_slot, cache_key=f"logo:{game.get('away_abbr')}")
|
||||
ctx.draw_image(ctx.load_logo("home"), regions.home_slot, cache_key=f"logo:{game.get('home_abbr')}")
|
||||
fit = ctx.layout.fit_text("3-5", regions.score_area)
|
||||
ctx.draw_fit(fit, regions.score_area)
|
||||
```
|
||||
|
||||
`Region` supports `split_h`/`split_v`/`inset`/`top_band`/`bottom_band`/
|
||||
`left_col`/`right_col` for custom carves. Raw `ctx.draw.rectangle/polygon/
|
||||
ellipse/...` is always available for custom marks (see the bases diamond in
|
||||
the example skin).
|
||||
|
||||
## The game view model
|
||||
|
||||
Guaranteed for every sport (view model v1.0 — renaming these breaks skins and
|
||||
is treated as a breaking change upstream):
|
||||
|
||||
| Key | Notes |
|
||||
|---|---|
|
||||
| `id` | Event id (string) |
|
||||
| `status_text` | Display-ready status, e.g. `"Final"`, `"7:30 PM"`, `"Bot 7th"` |
|
||||
| `is_live`, `is_final`, `is_upcoming`, `is_halftime` | Booleans |
|
||||
| `game_date`, `game_time` | Pre-formatted local date/time strings |
|
||||
| `start_time_utc` | UTC `datetime` |
|
||||
| `home_abbr`, `away_abbr` | Team abbreviations (can be 2–5 chars — fit, don't assume) |
|
||||
| `home_id`, `away_id` | Team ids |
|
||||
| `home_score`, `away_score` | **Strings**, not ints |
|
||||
| `home_record`, `away_record` | `"58-33"` or `""` (0-0 records are blanked) |
|
||||
| `home_logo_path`, `away_logo_path` | Prefer `ctx.load_logo` over touching these |
|
||||
|
||||
Sport extras (present for that sport, still `.get()` defensively):
|
||||
|
||||
- **baseball**: `inning` (int), `inning_half` (`"top"`/`"bottom"`), `balls`,
|
||||
`strikes`, `outs` (ints), `bases_occupied` (`[first, second, third]`
|
||||
booleans), `series_summary` (str)
|
||||
- **football**: `period`, `period_text`, `clock`, `home_timeouts`,
|
||||
`away_timeouts`, `down_distance_text`, `down_distance_text_long`,
|
||||
`is_redzone`, `possession`, `possession_indicator` (`"home"`/`"away"`),
|
||||
`scoring_event`
|
||||
- **basketball**: `period`, `period_text`, `clock`
|
||||
- **hockey**: `period`, `period_text`, `clock`, `power_play`, `penalties`,
|
||||
`home_shots`, `away_shots`
|
||||
|
||||
Optional everywhere (only when the user enabled the feature): `odds` (dict),
|
||||
`series_summary`, rankings-related fields.
|
||||
|
||||
Fixture copies of these dicts live in `src/skin_system/fixtures/` — that's
|
||||
exactly what the validator feeds your skin.
|
||||
|
||||
## Vegas mode
|
||||
|
||||
You get vegas support for free: vegas captures the normal display output,
|
||||
which is already your skin's rendering. Optionally implement
|
||||
`render_vegas_card(ctx, game)` to return a purpose-built card at
|
||||
`ctx.width x ctx.height` (sizes vary — never assume 128x32).
|
||||
|
||||
## Building a skin with Claude Code
|
||||
|
||||
Skins are ideal Claude Code projects: small, isolated, and verifiable with
|
||||
one command. Paste this to start:
|
||||
|
||||
> You are building a **display skin** for LEDMatrix — a visual overlay for a
|
||||
> sports scoreboard on a small LED matrix (commonly 128x32 or 64x32 pixels).
|
||||
> First read `docs/CREATING_SKINS.md` and the reference skin in
|
||||
> `skins/example-classic-baseball/`.
|
||||
>
|
||||
> Rules:
|
||||
> - Create/modify files ONLY under `skins/<my-skin-id>/`. Do NOT modify
|
||||
> anything in `src/`, `scripts/`, the plugins, or any other skin.
|
||||
> - Render only from the `game` dict and `ctx` helpers. No network calls, no
|
||||
> per-frame file I/O, no new pip dependencies, no touching the display —
|
||||
> draw onto `ctx.canvas` and return True.
|
||||
> - Use `ctx.layout` regions and `fit_text` for positioning so the skin works
|
||||
> at any panel size; use `.get()` for every optional game key.
|
||||
> - After every change run
|
||||
> `python scripts/validate_skin.py --skin <my-skin-id>` and LOOK at the
|
||||
> PNGs it writes to `skin_renders/` (the `_x4.png` files are easiest to
|
||||
> read). Iterate until it passes and looks right at both 128x32 and 64x32.
|
||||
>
|
||||
> What I want it to look like: <describe your layout — where logos, score,
|
||||
> status go; colors; what shows during live vs upcoming vs final>
|
||||
|
||||
Tips that keep Claude (and you) out of trouble:
|
||||
|
||||
- One mode at a time: get `render_live` right before touching the others —
|
||||
unimplemented modes automatically use the built-in look.
|
||||
- Ask for edge-case renders: long team abbreviations, missing logos
|
||||
(`ctx.load_logo` returning `None`), 0-0 records, extra innings/OT.
|
||||
- If the render looks cramped at 64x32, ask Claude to use
|
||||
`ctx.layout.by_tier(...)` to drop elements on small panels rather than
|
||||
shrinking everything.
|
||||
- Never let it "fix" a problem by editing `src/` — if the skin can't do
|
||||
something within its directory, that's a feature request, not a workaround.
|
||||
|
||||
## Pre-publish checklist
|
||||
|
||||
- [ ] `python scripts/validate_skin.py --skin <id> --size 128x32 --size 64x32 --size 128x64` passes
|
||||
- [ ] Looked at every PNG in `skin_renders/` — nothing clipped or overlapping
|
||||
- [ ] Handles a missing logo (`None`) without crashing — temporarily point a
|
||||
fixture's logo path at a nonexistent file to test
|
||||
- [ ] Long abbreviations (`"TA&M"`, 4–5 chars) don't overflow
|
||||
- [ ] No render warning above the time budget
|
||||
- [ ] `skin.json`: `id` matches the directory, `version` set,
|
||||
`skin_api_version` matches the host, targets correct
|
||||
- [ ] `preview.png` added (grab your favorite `_x4` render)
|
||||
- [ ] Tested on real hardware if you have it — a Pi is much slower than your
|
||||
dev machine
|
||||
|
||||
Distribute by publishing the directory as a git repo (users
|
||||
`git clone <repo> skins/<id>`), or submit it to the plugin registry as an
|
||||
entry with `"type": "skin"` (see [SKIN_SYSTEM.md](SKIN_SYSTEM.md) §Distribution).
|
||||
|
||||
**Trust note:** a skin is Python running inside the display service — the
|
||||
same trust level as a plugin. Review code before installing skins from
|
||||
others.
|
||||
@@ -31,7 +31,7 @@ POST /api/v3/system/action
|
||||
|
||||
**Base URL**: `http://your-pi-ip:5000/api/v3`
|
||||
|
||||
See [API_REFERENCE.md](API_REFERENCE.md) for complete documentation.
|
||||
See [REST_API_REFERENCE.md](REST_API_REFERENCE.md) for complete documentation.
|
||||
|
||||
## Display Manager Quick Methods
|
||||
|
||||
@@ -48,6 +48,12 @@ display_manager.draw_text("Centered", centered=True) # Auto-center
|
||||
width = display_manager.get_text_width("Text", font)
|
||||
height = display_manager.get_font_height(font)
|
||||
|
||||
# Adaptive layout (recommended for multi-size support — text and images
|
||||
# that scale to any panel; see docs/ADAPTIVE_LAYOUT.md)
|
||||
rows = self.layout.bounds.inset(1).split_v(3, 1, gap=1)
|
||||
self.draw_fit("12:34", rows[0]) # largest crisp font that fits
|
||||
self.draw_image(logo, rows[1], mode="fill_height", crop_to_ink=True)
|
||||
|
||||
# Weather icons
|
||||
display_manager.draw_weather_icon("rain", x=10, y=10, size=16)
|
||||
|
||||
@@ -184,12 +190,13 @@ def display(self, force_clear=False):
|
||||
|
||||
```
|
||||
LEDMatrix/
|
||||
├── plugins/ # Installed plugins
|
||||
├── plugin-repos/ # Installed plugins (default; plugins/ is only
|
||||
│ # for dev symlinks via scripts/dev/dev_plugin_setup.sh)
|
||||
├── config/
|
||||
│ ├── config.json # Main configuration
|
||||
│ └── config_secrets.json # API keys and secrets
|
||||
├── docs/ # Documentation
|
||||
│ ├── API_REFERENCE.md
|
||||
│ ├── REST_API_REFERENCE.md
|
||||
│ ├── PLUGIN_API_REFERENCE.md
|
||||
│ └── ...
|
||||
└── src/
|
||||
@@ -201,7 +208,7 @@ LEDMatrix/
|
||||
|
||||
## Quick Links
|
||||
|
||||
- [Complete API Reference](API_REFERENCE.md)
|
||||
- [Complete REST API Reference](REST_API_REFERENCE.md)
|
||||
- [Plugin API Reference](PLUGIN_API_REFERENCE.md)
|
||||
- [Plugin Development Guide](PLUGIN_DEVELOPMENT_GUIDE.md)
|
||||
- [Advanced Patterns](ADVANCED_PLUGIN_DEVELOPMENT.md)
|
||||
|
||||
@@ -6,6 +6,12 @@ Tools for rapid plugin development without deploying to the RPi.
|
||||
|
||||
Interactive web UI for tweaking plugin configs and seeing the rendered display in real time.
|
||||
|
||||
The size inputs have a preset dropdown with the harness's standard panel
|
||||
sizes, and the **All Sizes** button renders the current config at every
|
||||
harness size in a side-by-side gallery (`POST /api/render-matrix`) — the
|
||||
quickest way to eyeball adaptive-layout behavior across panels
|
||||
(see [ADAPTIVE_LAYOUT.md](ADAPTIVE_LAYOUT.md)).
|
||||
|
||||
### Quick Start
|
||||
|
||||
```bash
|
||||
|
||||
@@ -69,23 +69,24 @@ default configuration as it ships in the repo:
|
||||
```json
|
||||
{
|
||||
"pixel_outline": 0,
|
||||
"pixel_size": 5,
|
||||
"pixel_size": 16,
|
||||
"pixel_style": "square",
|
||||
"pixel_glow": 6,
|
||||
"display_adapter": "pygame",
|
||||
"display_adapter": "browser",
|
||||
"allow_adapter_fallback": true,
|
||||
"icon_path": null,
|
||||
"emulator_title": null,
|
||||
"suppress_font_warnings": false,
|
||||
"suppress_adapter_load_errors": false,
|
||||
"browser": {
|
||||
"_comment": "For use with the browser adapter only.",
|
||||
"port": 8888,
|
||||
"target_fps": 24,
|
||||
"target_fps": 60,
|
||||
"fps_display": false,
|
||||
"quality": 70,
|
||||
"image_border": true,
|
||||
"debug_text": false,
|
||||
"image_format": "JPEG"
|
||||
"image_format": "JPEG",
|
||||
"open_immediately": false
|
||||
},
|
||||
"log_level": "info"
|
||||
}
|
||||
@@ -96,13 +97,13 @@ default configuration as it ships in the repo:
|
||||
| Option | Description | Default | Values |
|
||||
|--------|-------------|---------|--------|
|
||||
| `pixel_outline` | Pixel border thickness | 0 | 0-5 |
|
||||
| `pixel_size` | Size of each pixel | 5 | 1-64 (8–16 is typical for testing) |
|
||||
| `pixel_size` | Size of each pixel | 16 | 1-64 (8–16 is typical for testing) |
|
||||
| `pixel_style` | Pixel shape | "square" | "square", "circle" |
|
||||
| `pixel_glow` | Glow effect intensity | 6 | 0-20 |
|
||||
| `display_adapter` | Display backend | "pygame" | "pygame", "browser" |
|
||||
| `display_adapter` | Display backend | "browser" | "browser", "pygame" |
|
||||
| `allow_adapter_fallback` | Fall back to another adapter if the configured one fails to load | true | true/false |
|
||||
| `emulator_title` | Window title | null | Any string |
|
||||
| `suppress_font_warnings` | Hide font warnings | false | true/false |
|
||||
| `suppress_adapter_load_errors` | Hide adapter errors | false | true/false |
|
||||
|
||||
### 3. Browser Adapter Configuration
|
||||
|
||||
@@ -111,18 +112,32 @@ When using the browser adapter, additional options are available:
|
||||
| Option | Description | Default |
|
||||
|--------|-------------|---------|
|
||||
| `port` | Web server port | 8888 |
|
||||
| `target_fps` | Target frames per second | 24 |
|
||||
| `target_fps` | Target frames per second | 60 |
|
||||
| `fps_display` | Show FPS counter | false |
|
||||
| `quality` | Image compression quality | 70 |
|
||||
| `image_border` | Show image border | true |
|
||||
| `debug_text` | Show debug information | false |
|
||||
| `image_format` | Image format | "JPEG" |
|
||||
| `open_immediately` | Open the browser page automatically on start | false |
|
||||
|
||||
## Running the Emulator
|
||||
|
||||
### 1. Set Environment Variable
|
||||
### 1. Use the `-e` Flag (Recommended)
|
||||
|
||||
Enable emulator mode by setting the `EMULATOR` environment variable:
|
||||
`run.py` accepts exactly two flags: `-e`/`--emulator` and
|
||||
`-d`/`--debug`.
|
||||
|
||||
```bash
|
||||
python3 run.py -e
|
||||
|
||||
# With verbose logging
|
||||
python3 run.py -e -d
|
||||
```
|
||||
|
||||
### 2. Alternative: Set the Environment Variable
|
||||
|
||||
You can also enable emulator mode via the `EMULATOR` environment
|
||||
variable:
|
||||
|
||||
**Windows (Command Prompt):**
|
||||
```cmd
|
||||
@@ -137,15 +152,6 @@ python run.py
|
||||
```
|
||||
|
||||
**Linux/macOS:**
|
||||
```bash
|
||||
export EMULATOR=true
|
||||
python3 run.py
|
||||
```
|
||||
|
||||
### 2. Alternative: Direct Python Execution
|
||||
|
||||
You can also run the emulator directly:
|
||||
|
||||
```bash
|
||||
EMULATOR=true python3 run.py
|
||||
```
|
||||
@@ -153,7 +159,8 @@ EMULATOR=true python3 run.py
|
||||
### 3. Verify Emulator Mode
|
||||
|
||||
When running in emulator mode, you should see:
|
||||
- A window displaying the LED matrix simulation
|
||||
- The emulated matrix — a web page at `http://localhost:8888` with the
|
||||
default browser adapter, or a desktop window with the pygame adapter
|
||||
- Console output indicating emulator mode
|
||||
- No hardware initialization errors
|
||||
|
||||
@@ -161,7 +168,36 @@ When running in emulator mode, you should see:
|
||||
|
||||
LEDMatrix supports two display adapters for the emulator:
|
||||
|
||||
### 1. Pygame Adapter (Default)
|
||||
### 1. Browser Adapter (Default)
|
||||
|
||||
The browser adapter runs a web server and displays the matrix as a web
|
||||
page at `http://localhost:8888`. This is the adapter the shipped
|
||||
`emulator_config.json` uses.
|
||||
|
||||
**Features:**
|
||||
- Web-based interface
|
||||
- Remote access capability
|
||||
- Mobile-friendly
|
||||
- Screenshot capture
|
||||
|
||||
**Configuration:**
|
||||
```json
|
||||
{
|
||||
"display_adapter": "browser",
|
||||
"browser": {
|
||||
"port": 8888,
|
||||
"target_fps": 60,
|
||||
"quality": 70
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
1. Start the emulator (`python3 run.py -e`)
|
||||
2. Open browser to `http://localhost:8888`
|
||||
3. View the LED matrix display
|
||||
|
||||
### 2. Pygame Adapter (Alternative)
|
||||
|
||||
The pygame adapter provides a native desktop window with real-time display.
|
||||
|
||||
@@ -186,33 +222,6 @@ The pygame adapter provides a native desktop window with real-time display.
|
||||
- `+/-` - Zoom in/out
|
||||
- `R` - Reset zoom
|
||||
|
||||
### 2. Browser Adapter
|
||||
|
||||
The browser adapter runs a web server and displays the matrix in a web browser.
|
||||
|
||||
**Features:**
|
||||
- Web-based interface
|
||||
- Remote access capability
|
||||
- Mobile-friendly
|
||||
- Screenshot capture
|
||||
|
||||
**Configuration:**
|
||||
```json
|
||||
{
|
||||
"display_adapter": "browser",
|
||||
"browser": {
|
||||
"port": 8888,
|
||||
"target_fps": 24,
|
||||
"quality": 70
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
1. Start the emulator with browser adapter
|
||||
2. Open browser to `http://localhost:8888`
|
||||
3. View the LED matrix display
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
@@ -299,17 +308,18 @@ Modify the display dimensions in your main config:
|
||||
|
||||
### 2. Plugin Development
|
||||
|
||||
For plugin development with the emulator:
|
||||
`run.py` always runs the full rotation — it has no single-plugin flag.
|
||||
To preview or check one plugin in isolation, use the dev tools:
|
||||
|
||||
```bash
|
||||
# Enable emulator mode
|
||||
export EMULATOR=true
|
||||
# Run the full display in emulator mode (optionally with debug logging)
|
||||
python3 run.py -e -d
|
||||
|
||||
# Run with specific plugin
|
||||
python run.py --plugin my-plugin
|
||||
# Live single-plugin preview in the browser (port 5001)
|
||||
python3 scripts/dev_server.py
|
||||
|
||||
# Debug mode
|
||||
python run.py --debug
|
||||
# Headless render/validation of one plugin
|
||||
python3 scripts/check_plugin.py --plugin my-plugin
|
||||
```
|
||||
|
||||
### 3. Performance Tuning
|
||||
@@ -344,11 +354,10 @@ The emulator can work alongside the web interface:
|
||||
|
||||
```bash
|
||||
# Terminal 1: Start emulator
|
||||
export EMULATOR=true
|
||||
python run.py
|
||||
python3 run.py -e
|
||||
|
||||
# Terminal 2: Start web interface
|
||||
python web_interface/app.py
|
||||
# Terminal 2: Start web interface (supported entry point)
|
||||
python3 web_interface/start.py
|
||||
```
|
||||
|
||||
Access the web interface at `http://localhost:5000` while the emulator runs.
|
||||
@@ -365,13 +374,14 @@ Access the web interface at `http://localhost:5000` while the emulator runs.
|
||||
### 2. Plugin Testing
|
||||
|
||||
```bash
|
||||
# Test specific plugin
|
||||
export EMULATOR=true
|
||||
python run.py --plugin clock-simple
|
||||
# Test a specific plugin (headless check)
|
||||
python3 scripts/check_plugin.py --plugin clock-simple
|
||||
|
||||
# Test all plugins
|
||||
export EMULATOR=true
|
||||
python run.py --test-plugins
|
||||
# Preview a single plugin live in the browser (port 5001)
|
||||
python3 scripts/dev_server.py
|
||||
|
||||
# Test the full rotation in the emulator
|
||||
python3 run.py -e
|
||||
```
|
||||
|
||||
### 3. Configuration Management
|
||||
@@ -385,9 +395,8 @@ python run.py --test-plugins
|
||||
### Basic Clock Display
|
||||
|
||||
```bash
|
||||
# Start emulator with clock
|
||||
export EMULATOR=true
|
||||
python run.py
|
||||
# Start emulator with clock enabled in config.json
|
||||
python3 run.py -e
|
||||
```
|
||||
|
||||
### Sports Scores
|
||||
@@ -395,16 +404,16 @@ python run.py
|
||||
```bash
|
||||
# Configure for sports display
|
||||
# Edit config/config.json to enable sports plugins
|
||||
export EMULATOR=true
|
||||
python run.py
|
||||
python3 run.py -e
|
||||
```
|
||||
|
||||
### Custom Text Display
|
||||
|
||||
```bash
|
||||
# Use text display plugin
|
||||
export EMULATOR=true
|
||||
python run.py --plugin text-display --text "Hello World"
|
||||
# Preview the text display plugin on its own
|
||||
python3 scripts/check_plugin.py --plugin text-display
|
||||
# or use the live dev preview server
|
||||
python3 scripts/dev_server.py
|
||||
```
|
||||
|
||||
## Support
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
# FontManager Usage Guide
|
||||
|
||||
> **Picking a size automatically:** if you want the *largest font that fits
|
||||
> a given area* rather than a fixed size, use the adaptive layout system's
|
||||
> font ladders, which resolve through this FontManager. `BasePlugin`
|
||||
> subclasses get this as `self.layout.fit_text(...)`; other code can build
|
||||
> a `LayoutContext(width, height, font_manager)` directly — see
|
||||
> [ADAPTIVE_LAYOUT.md](ADAPTIVE_LAYOUT.md).
|
||||
|
||||
## Overview
|
||||
|
||||
The enhanced FontManager provides comprehensive font management for the LEDMatrix application with support for:
|
||||
|
||||
@@ -21,18 +21,30 @@ This guide will help you set up your LEDMatrix display for the first time and ge
|
||||
|
||||
---
|
||||
|
||||
## Quick Start (5 Minutes)
|
||||
## Quick Start
|
||||
|
||||
### 1. First Boot
|
||||
### 1. Install LEDMatrix
|
||||
|
||||
1. Insert the MicroSD card with LEDMatrix installed
|
||||
2. Connect the LED matrix to your Raspberry Pi
|
||||
3. Plug in the power supply
|
||||
4. Wait for the Pi to boot (about 60 seconds)
|
||||
There is no prebuilt SD card image — you install LEDMatrix onto stock
|
||||
Raspberry Pi OS Lite yourself:
|
||||
|
||||
**Expected Behavior:**
|
||||
1. Flash Raspberry Pi OS Lite to the MicroSD card (Raspberry Pi Imager)
|
||||
2. Connect the LED matrix to your Raspberry Pi, insert the card, and
|
||||
power on
|
||||
3. SSH into the Pi and run the one-shot installer:
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/ChuckBuilds/LEDMatrix/main/scripts/install/one-shot-install.sh | bash
|
||||
```
|
||||
or clone the repo and run `sudo ./first_time_install.sh` — see the
|
||||
[README Installation Steps / Quick Install](../README.md#installation-steps)
|
||||
for full details
|
||||
|
||||
**Expected Behavior after install:**
|
||||
- LED matrix will light up
|
||||
- Display will show default plugins (clock, weather, etc.)
|
||||
- A fresh install ships only the bundled `starlark-apps` and
|
||||
`web-ui-info` plugins — clock, weather, sports, etc. must be
|
||||
installed from the Plugin Store (web UI → Plugin Manager) before
|
||||
anything else displays
|
||||
- Pi creates WiFi network "LEDMatrix-Setup" if not connected
|
||||
|
||||
### 2. Connect to WiFi
|
||||
@@ -73,7 +85,7 @@ You should see:
|
||||
2. Set your matrix configuration:
|
||||
- **Rows**: 32 or 64 (match your hardware)
|
||||
- **Columns**: commonly 64 or 96; the web UI accepts any integer
|
||||
in the 16–128 range, but 64 and 96 are the values the bundled
|
||||
in the 1–128 range, but 64 and 96 are the values the bundled
|
||||
panel hardware ships with
|
||||
- **Chain Length**: Number of panels chained horizontally
|
||||
- **Hardware Mapping**: usually `adafruit-hat-pwm` (with the PWM jumper
|
||||
@@ -115,11 +127,16 @@ You can also install community plugins straight from a GitHub URL using the
|
||||
|
||||
1. Each installed plugin gets its own tab in the second navigation row
|
||||
2. Open that plugin's tab to edit its settings (favorite teams, API keys,
|
||||
update intervals, display duration, etc.)
|
||||
update intervals, etc.)
|
||||
3. Click **Save**
|
||||
4. Restart the display service from **Overview** so the new settings take
|
||||
effect
|
||||
|
||||
**Note:** how long each plugin stays on screen is not set in the
|
||||
plugin's own tab — use the **Rotation** tab's **Screen Durations**
|
||||
section instead (saved to `display.display_durations` in
|
||||
`config.json`).
|
||||
|
||||
**Example: Weather Plugin**
|
||||
- Set your location (city, state, country)
|
||||
- Add an API key from OpenWeatherMap (free signup) to
|
||||
@@ -208,12 +225,14 @@ The fastest way to verify a plugin works without waiting for the rotation:
|
||||
### Customize Your Display
|
||||
|
||||
**Adjust display durations:**
|
||||
- Each plugin's tab has a **Display Duration (seconds)** field — set how
|
||||
long that plugin stays on screen each rotation.
|
||||
- Open the **Rotation** tab and use the **Screen Durations** section to
|
||||
set how long each plugin stays on screen per rotation (saved to
|
||||
`display.display_durations`).
|
||||
|
||||
**Organize plugin order:**
|
||||
- Use the **Plugin Manager** tab to enable/disable plugins. The display
|
||||
cycles through enabled plugins in the order they appear.
|
||||
- The **Rotation** tab also has a drag-and-drop **Rotation Order** list
|
||||
(saved to `display.plugin_rotation_order`). Enable/disable plugins
|
||||
from the **Plugin Manager** tab.
|
||||
|
||||
**Add more plugins:**
|
||||
- Check the **Plugin Store** section of **Plugin Manager** for new plugins.
|
||||
@@ -280,10 +299,14 @@ sudo journalctl -u ledmatrix-web -f
|
||||
│ ├── config_secrets.json # API keys and secrets
|
||||
│ └── wifi_config.json # WiFi settings
|
||||
├── plugin-repos/ # Installed plugins (default location)
|
||||
├── cache/ # Cached data
|
||||
└── web_interface/ # Web interface files
|
||||
```
|
||||
|
||||
> Cached data does not live in the project directory — the cache manager
|
||||
> uses the first writable location among `/var/cache/ledmatrix`,
|
||||
> `~/.ledmatrix_cache`, `/opt/ledmatrix/cache`, and
|
||||
> `$TMPDIR/ledmatrix_cache`.
|
||||
|
||||
> The plugin install location is configurable via
|
||||
> `plugin_system.plugins_directory` in `config.json`. The default is
|
||||
> `plugin-repos/`. Plugin discovery (`PluginManager.discover_plugins()`)
|
||||
@@ -303,11 +326,14 @@ System tabs:
|
||||
- WiFi Network selection and AP-mode setup
|
||||
- Schedule Power and dim schedules
|
||||
- Display Matrix hardware configuration
|
||||
- Rotation Rotation order (drag-and-drop) and screen durations
|
||||
- Config Editor Raw config.json editor
|
||||
- Backup & Restore Config backup and restore
|
||||
- Fonts Upload and manage fonts
|
||||
- Logs Real-time log viewing
|
||||
- Cache Cached data inspection and cleanup
|
||||
- Operation History Recent service operations
|
||||
- Tools System diagnostics, updates, dependencies, maintenance
|
||||
|
||||
Plugin tabs (second row):
|
||||
- Plugin Manager Browse the Plugin Store, install/enable plugins
|
||||
|
||||
@@ -10,10 +10,7 @@ Make sure you have the testing packages installed:
|
||||
|
||||
```bash
|
||||
# Install all dependencies including test packages
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Or install just the test dependencies
|
||||
pip install pytest pytest-cov pytest-mock
|
||||
pip install -r requirements.txt -r requirements-test.txt
|
||||
```
|
||||
|
||||
### 2. Set Environment Variables
|
||||
@@ -248,13 +245,11 @@ test/
|
||||
├── test_config_service.py # Config service tests
|
||||
├── test_config_validation_edge_cases.py # Config edge cases
|
||||
├── test_font_manager.py # Font manager tests
|
||||
├── test_layout_manager.py # Layout manager tests
|
||||
├── test_text_helper.py # Text helper tests
|
||||
├── test_error_handling.py # Error handling tests
|
||||
├── test_error_aggregator.py # Error aggregation tests
|
||||
├── test_schema_manager.py # Schema manager tests
|
||||
├── test_web_api.py # Web API tests
|
||||
├── test_nba_*.py # NBA-specific test suites
|
||||
├── plugins/ # Per-plugin test suites
|
||||
│ ├── test_clock_simple.py
|
||||
│ ├── test_calendar.py
|
||||
@@ -304,7 +299,7 @@ If tests fail due to missing packages:
|
||||
|
||||
```bash
|
||||
# Install all dependencies
|
||||
pip install -r requirements.txt
|
||||
pip install -r requirements.txt -r requirements-test.txt
|
||||
|
||||
# Or install specific missing package
|
||||
pip install <package-name>
|
||||
@@ -336,15 +331,15 @@ pytest --cov=src --cov-report=html
|
||||
|
||||
## Continuous Integration
|
||||
|
||||
The repo runs
|
||||
[`.github/workflows/security-audit.yml`](../.github/workflows/security-audit.yml)
|
||||
(bandit + semgrep) on every push. A pytest CI workflow at
|
||||
`.github/workflows/tests.yml` is queued to land alongside this
|
||||
PR ([ChuckBuilds/LEDMatrix#307](https://github.com/ChuckBuilds/LEDMatrix/pull/307));
|
||||
the workflow file itself was held back from that PR because the
|
||||
push token lacked the GitHub `workflow` scope, so it needs to be
|
||||
committed separately by a maintainer. Once it's in, this section
|
||||
will be updated to describe what the job runs.
|
||||
The repo runs the pytest suite via
|
||||
[`.github/workflows/test.yml`](../.github/workflows/test.yml) on every
|
||||
push and pull request: a plugin-safety job (harness, visual rendering
|
||||
and plugin-matrix tests) plus a unit-test job that runs an explicit
|
||||
allowlist of suites — new test files must be added to that list to run
|
||||
in CI. Release version consistency is checked by
|
||||
[`.github/workflows/release-version-check.yml`](../.github/workflows/release-version-check.yml).
|
||||
Bandit, flake8, mypy and gitleaks run as pre-commit hooks (see
|
||||
`.pre-commit-config.yaml`), not in CI.
|
||||
|
||||
## Best Practices
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ The plugin system has been enhanced but remains backward compatible with existin
|
||||
|
||||
If you encounter issues during migration:
|
||||
|
||||
1. Check the [README.md](README.md) for current installation and usage instructions
|
||||
1. Check the [project root README](../README.md) for current installation and usage instructions
|
||||
2. Review script README files:
|
||||
- [`scripts/install/README.md`](../scripts/install/README.md) - Installation scripts documentation
|
||||
- [`scripts/fix_perms/README.md`](../scripts/fix_perms/README.md) - Permission scripts documentation
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
Complete API reference for plugin developers. This document describes all methods and properties available to plugins through the Display Manager, Cache Manager, and Plugin Manager.
|
||||
|
||||
> **Adaptive layout:** every `BasePlugin` also exposes `self.layout`,
|
||||
> `self.draw_fit(text, region)` and `self.draw_image(img, region, ...)` —
|
||||
> the recommended way to render text and images that scale to any panel
|
||||
> size. See [ADAPTIVE_LAYOUT.md](ADAPTIVE_LAYOUT.md).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [BasePlugin](#baseplugin)
|
||||
@@ -196,8 +201,9 @@ the mode selector for this plugin.
|
||||
|
||||
#### `get_vegas_segment_width() -> Optional[int]`
|
||||
|
||||
For `FIXED_SEGMENT` plugins, the width in pixels of the segment they
|
||||
occupy in the scroll. `None` lets the controller pick a default.
|
||||
For `FIXED_SEGMENT` plugins, the number of *panels* the segment
|
||||
occupies in the scroll (pixel width = panels × `single_panel_width`,
|
||||
from `display.hardware.cols`). `None` uses the default of 1 panel.
|
||||
|
||||
> The full source for `BasePlugin` lives in
|
||||
> `src/plugin_system/base_plugin.py`. If a method here disagrees with the
|
||||
|
||||
@@ -8,9 +8,12 @@
|
||||
> - Code paths reference `web_interface_v2.py`; the current web UI is
|
||||
> `web_interface/app.py` with v3 Blueprint-based templates.
|
||||
> - The example Flask routes use `/api/plugins/*`; the real API
|
||||
> blueprint is mounted at `/api/v3` (`web_interface/app.py:144`).
|
||||
> blueprint is mounted at `/api/v3` (`web_interface/app.py:199`).
|
||||
> - The default plugin location is `plugin-repos/` (configurable via
|
||||
> `plugin_system.plugins_directory`), not `./plugins/`.
|
||||
> - Example imports use `src/plugin_system/base_classes/*_plugin.py`;
|
||||
> the shipped base classes live in `src/base_classes/` (e.g.
|
||||
> `src.base_classes.sports.SportsCore`, `src.base_classes.hockey.Hockey`).
|
||||
> - The "Migration Strategy" and "Implementation Roadmap" sections
|
||||
> describe work that has now shipped.
|
||||
>
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# Plugin Configuration Tabs - Architecture
|
||||
|
||||
> This page covers internals (how the config system works under the
|
||||
> hood). For designing a plugin's config schema, the canonical guide is
|
||||
> [PLUGIN_CONFIGURATION_GUIDE.md](PLUGIN_CONFIGURATION_GUIDE.md); for
|
||||
> the user-facing tabs feature, see
|
||||
> [PLUGIN_CONFIGURATION_TABS.md](PLUGIN_CONFIGURATION_TABS.md).
|
||||
|
||||
## System Architecture
|
||||
|
||||
### Component Overview
|
||||
|
||||
@@ -296,7 +296,7 @@ Want to change icons programmatically? While not officially supported, you could
|
||||
## Related Documentation
|
||||
|
||||
- [Plugin Configuration Tabs](PLUGIN_CONFIGURATION_TABS.md) - Main plugin tabs documentation
|
||||
- [Plugin Development Guide](plugin_docs/) - How to create plugins
|
||||
- [Plugin Development Guide](PLUGIN_DEVELOPMENT_GUIDE.md) - How to create plugins
|
||||
- [Font Awesome Icons](https://fontawesome.com/icons) - Browse all available icons
|
||||
- [Emoji Reference](https://unicode.org/emoji/charts/full-emoji-list.html) - All emoji options
|
||||
|
||||
|
||||
@@ -169,6 +169,6 @@ If you continue to experience issues:
|
||||
## Related Documentation
|
||||
|
||||
- [Plugin Dependency Guide](PLUGIN_DEPENDENCY_GUIDE.md)
|
||||
- [Plugin Development Guide](docs/plugin_development.md)
|
||||
- [Troubleshooting Quick Start](TROUBLESHOOTING_QUICK_START.md)
|
||||
- [Plugin Development Guide](PLUGIN_DEVELOPMENT_GUIDE.md)
|
||||
- [Troubleshooting](TROUBLESHOOTING.md)
|
||||
|
||||
|
||||
@@ -2,6 +2,20 @@
|
||||
|
||||
This guide explains how to set up a development workflow for plugins that are maintained in separate Git repositories while still being able to test them within the LEDMatrix project.
|
||||
|
||||
> **Rendering guidance:** plugins should read the display size dynamically
|
||||
> (`self.display_manager.matrix.width/height`) rather than hardcoding one
|
||||
> panel. For plugins that want to *scale* their layout to any panel, the
|
||||
> opt-in adaptive layout system ([ADAPTIVE_LAYOUT.md](ADAPTIVE_LAYOUT.md))
|
||||
> provides the shared helpers — fonts, images, and composite layouts that
|
||||
> scale. Existing plugins keep their classic rendering unless they adopt
|
||||
> those APIs; nothing migrates automatically.
|
||||
|
||||
> **Just want a different look for an existing sports scoreboard?** You may
|
||||
> not need a plugin at all — a **skin** restyles the live/recent/upcoming
|
||||
> rendering while the plugin keeps handling data, scheduling, caching, and
|
||||
> vegas mode, in ~100 lines of drawing code. See
|
||||
> [CREATING_SKINS.md](CREATING_SKINS.md).
|
||||
|
||||
## Overview
|
||||
|
||||
When developing plugins in separate repositories, you need a way to:
|
||||
@@ -575,11 +589,24 @@ Your plugin must:
|
||||
### Versioning Best Practices
|
||||
|
||||
- **Use semantic versioning**: `MAJOR.MINOR.PATCH` (e.g., `1.2.3`)
|
||||
- **Automatic version bumping**: Use the pre-push git hook for automatic patch version bumps
|
||||
- **Manual versioning**: Only needed for major/minor bumps or special cases
|
||||
- **GitHub as source of truth**: Plugin store fetches versions from GitHub releases/tags/manifest
|
||||
- **GitHub as source of truth**: the plugin store resolves versions in this
|
||||
order: GitHub Releases → GitHub Tags → manifest from branch → git commit hash
|
||||
- **Automatic version bumping**: install the self-contained pre-push hook in
|
||||
your plugin repo and patch versions bump themselves on push (a git tag
|
||||
`v{version}` is created and `manifest.json` staged automatically):
|
||||
|
||||
See the [Git Workflow rules](../.cursorrules) for version management details.
|
||||
```bash
|
||||
# From your plugin repository directory
|
||||
cp /path/to/LEDMatrix/scripts/git-hooks/pre-push-plugin-version .git/hooks/pre-push
|
||||
chmod +x .git/hooks/pre-push
|
||||
```
|
||||
|
||||
Set `SKIP_TAG=1` in the environment to skip auto-tagging for one push.
|
||||
- **Manual versioning**: only needed for major/minor bumps, CI pipelines that
|
||||
bypass hooks, or forks without the hook — use
|
||||
`scripts/bump_plugin_version.py`.
|
||||
- **Registry stores no versions**: `plugins.json` holds only metadata (name,
|
||||
description, repo URL).
|
||||
|
||||
### Submitting to Official Registry
|
||||
|
||||
@@ -653,5 +680,5 @@ For your plugin to work well in the plugin store:
|
||||
- [Advanced Plugin Development](ADVANCED_PLUGIN_DEVELOPMENT.md) - Advanced patterns and examples
|
||||
- [Plugin Quick Reference](PLUGIN_QUICK_REFERENCE.md) - Quick development reference
|
||||
- [Plugin Configuration Guide](PLUGIN_CONFIGURATION_GUIDE.md) - Configuration setup
|
||||
- [Plugin Store User Guide](PLUGIN_STORE_USER_GUIDE.md) - Using the plugin store
|
||||
- [Plugin Store Guide](PLUGIN_STORE_GUIDE.md) - Using the plugin store
|
||||
|
||||
|
||||
@@ -14,8 +14,10 @@ and [PLUGIN_DEVELOPMENT_GUIDE.md](PLUGIN_DEVELOPMENT_GUIDE.md).
|
||||
✅ **GitHub Store**: Discovery from `ledmatrix-plugins` registry plus
|
||||
any GitHub URL
|
||||
✅ **Plugin Location**: configured by `plugin_system.plugins_directory`
|
||||
in `config.json` (default `plugin-repos/`; the loader also searches
|
||||
`plugins/` as a fallback)
|
||||
in `config.json` (default `plugin-repos/`). Plugin discovery scans
|
||||
only this directory — there is no loader fallback to `plugins/`
|
||||
(only Plugin Store operations and schema lookup additionally probe
|
||||
`plugins/`)
|
||||
|
||||
## File Structure
|
||||
|
||||
@@ -109,7 +111,7 @@ git push -u origin main
|
||||
git tag v1.0.0
|
||||
git push origin v1.0.0
|
||||
|
||||
# Submit to registry (PR to ChuckBuilds/ledmatrix-plugin-registry)
|
||||
# Submit to registry (PR to ChuckBuilds/ledmatrix-plugins)
|
||||
```
|
||||
|
||||
## Using Plugins
|
||||
@@ -120,12 +122,12 @@ git push origin v1.0.0
|
||||
2. **Install**: Click **Install** in the plugin's row
|
||||
3. **Configure**: open the plugin's tab in the second nav row
|
||||
4. **Enable/Disable**: toggle switch in the **Installed Plugins** list
|
||||
5. **Reorder**: order is set by the position in `display_modes` /
|
||||
plugin order; rearranging via drag-and-drop is not yet supported
|
||||
5. **Reorder**: use the drag-and-drop **Rotation Order** list in the
|
||||
**Rotation** tab (saved to `display.plugin_rotation_order`)
|
||||
|
||||
### REST API
|
||||
|
||||
The API is mounted at `/api/v3` (`web_interface/app.py:144`).
|
||||
The API is mounted at `/api/v3` (`web_interface/app.py:199`).
|
||||
|
||||
```bash
|
||||
# Install plugin from the registry
|
||||
|
||||
@@ -323,16 +323,22 @@ curl -X POST http://pi:5000/api/v3/plugins/install-from-url \
|
||||
### Regular Updates
|
||||
|
||||
```bash
|
||||
# Update stars/downloads counts
|
||||
python3 scripts/update_stats.py
|
||||
# Refresh local clones of all plugin repos
|
||||
python3 scripts/update_plugin_repos.py
|
||||
|
||||
# Validate all plugin entries
|
||||
python3 scripts/validate_registry.py
|
||||
# (Re-)create local plugin repo checkouts from the registry
|
||||
python3 scripts/setup_plugin_repos.py
|
||||
|
||||
# Check for plugin updates
|
||||
python3 scripts/check_updates.py
|
||||
# Audit installed plugins for manifest/schema problems
|
||||
python3 scripts/audit_plugins.py
|
||||
|
||||
# Validate a single plugin
|
||||
python3 scripts/check_plugin.py --plugin <plugin-id>
|
||||
```
|
||||
|
||||
Registry regeneration (`update_registry.py`) lives in the
|
||||
`ledmatrix-plugins` monorepo, not in this repo.
|
||||
|
||||
## Converting Existing Plugins
|
||||
|
||||
To convert your existing plugins (hello-world, clock-simple) to this system:
|
||||
@@ -400,7 +406,7 @@ print(f'Found {len(registry[\"plugins\"])} plugins')
|
||||
|
||||
## References
|
||||
|
||||
- Plugin Store Implementation: See `PLUGIN_STORE_IMPLEMENTATION_SUMMARY.md`
|
||||
- User Guide: See `PLUGIN_STORE_USER_GUIDE.md`
|
||||
- Plugin Store Implementation: See `PLUGIN_IMPLEMENTATION_SUMMARY.md`
|
||||
- User Guide: See `PLUGIN_STORE_GUIDE.md`
|
||||
- Architecture: See `PLUGIN_ARCHITECTURE_SPEC.md`
|
||||
|
||||
|
||||
@@ -481,13 +481,13 @@ A: Yes, if a plugin needs API keys, it can access them like core managers do.
|
||||
A: Most plugins are small (1-5MB). Check individual plugin documentation for specific requirements.
|
||||
|
||||
**Q: Can I create my own plugin?**
|
||||
A: Yes! See [PLUGIN_DEVELOPMENT.md](PLUGIN_DEVELOPMENT.md) for instructions.
|
||||
A: Yes! See [PLUGIN_DEVELOPMENT_GUIDE.md](PLUGIN_DEVELOPMENT_GUIDE.md) for instructions.
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [PLUGIN_DEVELOPMENT.md](PLUGIN_DEVELOPMENT.md) - Create your own plugins
|
||||
- [PLUGIN_DEVELOPMENT_GUIDE.md](PLUGIN_DEVELOPMENT_GUIDE.md) - Create your own plugins
|
||||
- [PLUGIN_API_REFERENCE.md](PLUGIN_API_REFERENCE.md) - Plugin API documentation
|
||||
- [PLUGIN_ARCHITECTURE.md](PLUGIN_ARCHITECTURE.md) - Plugin system architecture
|
||||
- [PLUGIN_ARCHITECTURE_SPEC.md](PLUGIN_ARCHITECTURE_SPEC.md) - Plugin system architecture (historical)
|
||||
- [REST_API_REFERENCE.md](REST_API_REFERENCE.md) - Complete REST API reference
|
||||
|
||||
@@ -29,15 +29,16 @@ Start here:
|
||||
Going deeper:
|
||||
|
||||
- [ADVANCED_PLUGIN_DEVELOPMENT.md](ADVANCED_PLUGIN_DEVELOPMENT.md) — advanced patterns
|
||||
- [PLUGIN_ARCHITECTURE_SPEC.md](PLUGIN_ARCHITECTURE_SPEC.md) — full plugin-system spec
|
||||
- [PLUGIN_ARCHITECTURE_SPEC.md](PLUGIN_ARCHITECTURE_SPEC.md) — original plugin-system design spec (historical; see its banner for what has drifted)
|
||||
- [PLUGIN_DEPENDENCY_GUIDE.md](PLUGIN_DEPENDENCY_GUIDE.md) /
|
||||
[PLUGIN_DEPENDENCY_TROUBLESHOOTING.md](PLUGIN_DEPENDENCY_TROUBLESHOOTING.md)
|
||||
- [PLUGIN_WEB_UI_ACTIONS.md](PLUGIN_WEB_UI_ACTIONS.md) (+ [example JSON](PLUGIN_WEB_UI_ACTIONS_EXAMPLE.json))
|
||||
- [PLUGIN_CUSTOM_ICONS.md](PLUGIN_CUSTOM_ICONS.md) /
|
||||
[PLUGIN_CUSTOM_ICONS_FEATURE.md](PLUGIN_CUSTOM_ICONS_FEATURE.md)
|
||||
- [PLUGIN_CUSTOM_ICONS.md](PLUGIN_CUSTOM_ICONS.md)
|
||||
- [PLUGIN_REGISTRY_SETUP_GUIDE.md](PLUGIN_REGISTRY_SETUP_GUIDE.md) (+ [registry template](plugin_registry_template.json))
|
||||
- [STARLARK_APPS_GUIDE.md](STARLARK_APPS_GUIDE.md) — Starlark-based mini-apps
|
||||
- [widget-guide.md](widget-guide.md) — widget development
|
||||
- [ADAPTIVE_LAYOUT.md](ADAPTIVE_LAYOUT.md) — render legibly on any panel size (opt-in font/layout scaling)
|
||||
- [plugin-safety-harness.md](plugin-safety-harness.md) — test a plugin across every screen and matrix size
|
||||
|
||||
## Configuring plugins
|
||||
|
||||
@@ -52,9 +53,12 @@ Going deeper:
|
||||
- [ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) — Vegas scroll, on-demand display,
|
||||
cache management, background services, permissions
|
||||
- [FONT_MANAGER.md](FONT_MANAGER.md) — font system
|
||||
- [SKIN_SYSTEM.md](SKIN_SYSTEM.md) — skin architecture for sports scoreboards
|
||||
- [CREATING_SKINS.md](CREATING_SKINS.md) — writing and validating a skin
|
||||
|
||||
## Reference
|
||||
|
||||
- [CONFIG_REFERENCE.md](CONFIG_REFERENCE.md) — every key in config.json and config_secrets.json
|
||||
- [REST_API_REFERENCE.md](REST_API_REFERENCE.md) — all web-interface HTTP endpoints
|
||||
- [PLUGIN_API_REFERENCE.md](PLUGIN_API_REFERENCE.md) — Python APIs available to plugins
|
||||
- [DEVELOPER_QUICK_REFERENCE.md](DEVELOPER_QUICK_REFERENCE.md) — common dev tasks
|
||||
@@ -66,6 +70,7 @@ Going deeper:
|
||||
- [HOW_TO_RUN_TESTS.md](HOW_TO_RUN_TESTS.md) — running the test suite
|
||||
- [MULTI_ROOT_WORKSPACE_SETUP.md](MULTI_ROOT_WORKSPACE_SETUP.md) — multi-repo workspace
|
||||
- [MIGRATION_GUIDE.md](MIGRATION_GUIDE.md) — breaking changes between releases
|
||||
- [SPORTS_UNIFICATION.md](SPORTS_UNIFICATION.md) — how the sports scoreboard base classes are organized
|
||||
|
||||
## Archive
|
||||
|
||||
|
||||
@@ -31,9 +31,9 @@ All endpoints return JSON responses with a standard format:
|
||||
- [Plugin-specific endpoints](#plugin-specific-endpoints)
|
||||
- [Starlark Apps](#starlark-apps)
|
||||
|
||||
> The API blueprint is mounted at `/api/v3` (`web_interface/app.py:144`).
|
||||
> The API blueprint is mounted at `/api/v3` (`web_interface/app.py:199`).
|
||||
> SSE stream endpoints (`/api/v3/stream/*`) are defined directly on the
|
||||
> Flask app at `app.py:607-615`. There are about 92 routes total — see
|
||||
> Flask app at `app.py:799-809`. There are 94 routes total — see
|
||||
> `web_interface/blueprints/api_v3.py` for the canonical list.
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# Skin System Architecture
|
||||
|
||||
Skins are user-installable **visual overlays** for the sports scoreboards.
|
||||
A skin replaces only the *look* of a scoreboard — the host plugin keeps doing
|
||||
data fetching, scheduling, caching, dedup, live-priority takeover, and vegas
|
||||
mode. If you only want to **build** a skin, read
|
||||
[CREATING_SKINS.md](CREATING_SKINS.md); this document explains how the system
|
||||
works and why it is shaped this way.
|
||||
|
||||
## Why skins instead of forks
|
||||
|
||||
Before skins, changing a scoreboard's layout meant forking the whole plugin
|
||||
(e.g. the community MLB scoreboard fork). The fork gets the new look but loses
|
||||
everything the maintained plugin keeps earning: duration/scheduling behavior,
|
||||
vegas mode support, caching and background-fetch improvements, bug fixes. It
|
||||
also silently drifts: every upstream improvement now has to be re-ported by
|
||||
hand.
|
||||
|
||||
A skin inverts that trade. The plugin remains stock and keeps updating through
|
||||
the store; the skin is ~100 lines of pure rendering code that receives the
|
||||
plugin's already-fetched data each frame. Uninstalling the skin (or the skin
|
||||
crashing) simply restores the built-in look.
|
||||
|
||||
```text
|
||||
(unchanged) (the skin seam)
|
||||
ESPN API ──► update() ──► game view model ──► _render_game() ──► display
|
||||
fetching (a dict) │ │
|
||||
caching │ └─ built-in
|
||||
scheduling └─ skin.render_<mode>(ctx, game)
|
||||
live priority draws onto ctx.canvas
|
||||
```
|
||||
|
||||
## The render funnel
|
||||
|
||||
Every sports scoreboard (baseball, football, basketball, hockey — anything
|
||||
built on the `src/base_classes/sports/` package, `core.py`) renders through exactly one seam:
|
||||
`SportsCore._render_game(game, force_clear)`.
|
||||
|
||||
1. The mode class's `display()` (live, `SportsUpcoming`, `SportsRecent`)
|
||||
picks `self.current_game` and calls `_render_game`.
|
||||
2. `_render_game` lazily loads the configured skin (once, on first render —
|
||||
a broken skin can never block plugin startup).
|
||||
3. If a skin is active, the host builds a `SkinContext` — a fresh black
|
||||
canvas at the current display size plus layout/font/logo helpers — and
|
||||
calls the skin's `render_live` / `render_recent` / `render_upcoming`
|
||||
with a **copy** of the game dict.
|
||||
4. If the skin returns `True`, the canvas is composited onto the display.
|
||||
If it returns `False`, isn't implemented for that mode, or raises, the
|
||||
built-in `_draw_scorebug_layout` runs instead.
|
||||
|
||||
Key properties that fall out of this design:
|
||||
|
||||
- **Per-mode fallback.** A skin that only implements `render_live` gets the
|
||||
stock recent/upcoming screens for free.
|
||||
- **Three strikes.** A skin that raises 3 times in a row is disabled for the
|
||||
rest of the session (one loud error log per failure); the display never
|
||||
goes dark. Restarting the service re-arms it.
|
||||
- **Copies, not references.** Skins receive a shallow copy of the game dict,
|
||||
so a buggy skin cannot corrupt the plugin's scheduling state.
|
||||
- **Vegas mode works untouched.** Vegas capture falls back to grabbing the
|
||||
regular `display()` output, which is already skin-rendered. Skins can
|
||||
additionally implement `render_vegas_card` for purpose-built scroll cards,
|
||||
and hosts can call `SportsCore.render_skin_card(game, size)` to use it.
|
||||
- **Hot-loop caution.** `render_live` runs every display-loop pass during a
|
||||
live game. The host logs a warning when a skin render exceeds 150 ms, and
|
||||
`scripts/validate_skin.py` enforces a budget at development time — but
|
||||
Python cannot forcibly time-out a stuck render, so a skin that blocks
|
||||
(network I/O, giant image ops) stalls the display. This is why the rules
|
||||
in CREATING_SKINS.md ban I/O in render paths.
|
||||
|
||||
## The view model contract
|
||||
|
||||
The `game` dict a skin receives is the plugin's already-extracted view model
|
||||
(`SportsCore._extract_game_details_common` plus per-sport extras from
|
||||
`src/base_classes/{baseball,basketball,football,hockey}.py`).
|
||||
|
||||
- **Guaranteed keys (view model v1.0)** — always present for every sport:
|
||||
`id`, `game_time`, `game_date`, `start_time_utc` (a UTC `datetime`),
|
||||
`status_text`, `is_live`, `is_final`, `is_upcoming`, `is_halftime`,
|
||||
`home_abbr`/`away_abbr`, `home_id`/`away_id`, `home_score`/`away_score`
|
||||
(**strings**), `home_logo_path`/`away_logo_path`, `home_record`/`away_record`.
|
||||
- **Sport extras** — documented per sport in CREATING_SKINS.md (e.g. baseball
|
||||
adds `inning`, `inning_half`, `balls`, `strikes`, `outs`, `bases_occupied`).
|
||||
- **Optional keys** (`odds`, rankings, `series_summary`, …) are present only
|
||||
when the feature is enabled — skins must always use `.get()`.
|
||||
|
||||
Versioning policy: additive changes bump the minor version
|
||||
(`VIEW_MODEL_VERSION` in `src/skin_system/skin_base.py`, surfaced to skins as
|
||||
`ctx.view_model_version`); renaming or removing a guaranteed key requires a
|
||||
major bump plus a compat shim. `test/test_skin_system.py::TestViewModelContract`
|
||||
fails CI if a guaranteed key disappears from the extractor.
|
||||
|
||||
Separately, `SKIN_API_VERSION` versions the Python API (`ScoreboardSkin`,
|
||||
`SkinContext`). The loader refuses a skin whose manifest declares a different
|
||||
major version and falls back to the built-in renderer with a clear
|
||||
"skin needs an update" log line.
|
||||
|
||||
## Package layout and lifecycle
|
||||
|
||||
```text
|
||||
skins/<skin-id>/
|
||||
skin.json # manifest (required)
|
||||
skin.py # ScoreboardSkin subclass (required)
|
||||
preview.png # optional, shown by the web UI
|
||||
assets/ # optional skin-local images
|
||||
helpers.py ... # optional extra modules (namespaced per skin at import)
|
||||
```
|
||||
|
||||
Skins live in the central `skins/` directory — deliberately **not** inside the
|
||||
plugin's directory, because plugin reinstall/update deletes the whole plugin
|
||||
directory and a skin must survive that. One skin can also target several
|
||||
plugins (mlb + milb).
|
||||
|
||||
Lifecycle: discovered lazily on first render → manifest validated → API major
|
||||
version gated → module imported under a namespaced `sys.modules` key (two
|
||||
skins can both ship a `helpers.py`, same scheme plugins use) → instantiated
|
||||
with `(manifest, options)`. Every failure logs and falls back to built-in.
|
||||
|
||||
Skins should be **stateless**: the live, recent, and upcoming mode classes
|
||||
each hold their own skin instance, so derive everything from `(ctx, game)`.
|
||||
|
||||
## Selection and configuration
|
||||
|
||||
Inside the plugin's own config section in `config/config.json`:
|
||||
|
||||
```json
|
||||
"baseball-scoreboard": {
|
||||
"skin": "retro-baseball",
|
||||
"skin_options": { "accent_color": [255, 80, 0] }
|
||||
}
|
||||
```
|
||||
|
||||
`"skin"` is either one id for all modes or a per-mode mapping
|
||||
(`{"live": "retro-baseball", "recent": "built-in"}`). Absent, empty, or
|
||||
`"built-in"` means the stock renderer. Because this rides the plugin's config
|
||||
section, it persists across plugin reinstalls like every other setting.
|
||||
|
||||
The web UI shows a **Visual Skin** dropdown for plugins that have matching
|
||||
skins installed: `SchemaManager.inject_skin_selector` adds an enum to the
|
||||
*served* schema only. Validation never sees the enum — so a config that
|
||||
references an uninstalled skin stays valid (rendering just falls back), and
|
||||
the currently-configured value is always kept selectable. `GET /api/v3/skins`
|
||||
lists installed skins (optionally filtered by `?plugin_id=`).
|
||||
|
||||
## Distribution
|
||||
|
||||
- **Manual:** `git clone <skin repo> skins/<skin-id>` — that's the whole
|
||||
install. No manifest bumps, no `update_registry.py`; skins are not monorepo
|
||||
plugins.
|
||||
- **Store:** registry entries with `"type": "skin"` install through the same
|
||||
`plugins.json` pipeline; `PluginStoreManager` routes them to `skins/`,
|
||||
validates `skin.json` (including the API major version) instead of
|
||||
`manifest.json`, and never installs dependencies — skins are render-only
|
||||
(stdlib + PIL + the provided context, no third-party packages in v1).
|
||||
|
||||
## Trust model
|
||||
|
||||
A skin is Python executing inside the display service — **exactly the same
|
||||
trust level as a plugin**, even though "skin" sounds cosmetic. Only install
|
||||
skins from sources you'd be willing to install a plugin from.
|
||||
|
||||
## v2 directions (not in v1)
|
||||
|
||||
- A generic `BasePlugin` opt-in (`render_with_skin()`) so non-sports plugins
|
||||
(weather, music) can offer skinnable layouts; `skin_runtime` is already
|
||||
sports-agnostic in anticipation.
|
||||
- Store UI: preview gallery, one-click install from the skin browser.
|
||||
- An update path for git-cloned skins (today: re-clone or store reinstall).
|
||||
- Animation support in skins (today the API is one frame per render call;
|
||||
stateful tricks work but are at-your-own-risk).
|
||||
@@ -0,0 +1,387 @@
|
||||
# Sports Code Unification — Architecture
|
||||
|
||||
How the nine sports scoreboard plugins converge onto shared core code **without**
|
||||
becoming nine clients of a god class.
|
||||
|
||||
## The problem
|
||||
|
||||
Nine plugins (`afl`, `baseball`, `basketball`, `football`, `hockey`, `lacrosse`,
|
||||
`nrl`, `soccer`, `ufc`) each ship a ~3,000-line `sports.py` descended from this
|
||||
repo's `src/base_classes/sports.py`. They have drifted into three lineages, and
|
||||
only 28 of the 66 methods appearing across them are present in all nine. One
|
||||
logical fix (the UTC start-time bug) cost 75 files.
|
||||
|
||||
Merging everything into one base class would fix the duplication and create a
|
||||
worse problem: a single 2,500-line class that all nine plugins inherit, where any
|
||||
change has a nine-plugin blast radius and per-sport behavior survives only as
|
||||
`if self.sport == "hockey"` branches.
|
||||
|
||||
## Three properties, three mechanisms
|
||||
|
||||
These are independent concerns. Conflating them is what produces god classes.
|
||||
|
||||
### Upgradability — a plugin keeps working across core versions
|
||||
|
||||
| Rule | Mechanism |
|
||||
|---|---|
|
||||
| Plugin loads on a core that predates a module | Guarded import with a bundled fallback (`try: from src.X import Y / except ModuleNotFoundError: from y import Y`) |
|
||||
| Plugin loads on a core that predates a *method* | Capability probing — `hasattr(SportsCore, "_detect_stale_games")` — never a version comparison. The loader's compat check is advisory-only (it logs and continues), so probing is the real protection. |
|
||||
| Core changes never break a plugin's rendering | The **view-model contract**: `_extract_game_details_common` returns a dict whose `GUARANTEED_KEYS` are frozen by `test/test_skin_system.py::TestViewModelContract`. Keys may be added, never renamed or removed. |
|
||||
| A plugin can drop its bundled copy safely | The **sunset rule**: its manifest must floor `ledmatrix_min_version` at the first core release shipping the module (recorded in `CHANGELOG.md`) — *necessary but not sufficient*. Nothing enforces that floor today, so the copy also waits for the B6 gate below. |
|
||||
|
||||
The core API is **additive-only**. A method the plugins call is never removed or
|
||||
given a new required parameter; new behavior arrives as new methods with
|
||||
defaults, or as capabilities they opt into.
|
||||
|
||||
### Reusability — write once, nine plugins benefit
|
||||
|
||||
Only code that is **identical in intent across all nine** moves into the base
|
||||
class. That set is small and knowable — it is exactly the methods present in every
|
||||
copy today (phase B1 below). Everything else stays where it is until it earns
|
||||
promotion.
|
||||
|
||||
### Modularity — a change to one feature cannot reach a plugin that doesn't use it
|
||||
|
||||
This is the property the naive merge destroys, and it is enforced structurally:
|
||||
|
||||
1. **Capabilities are separate modules composed by inheritance, not config
|
||||
branches inside the base class.** Hockey has no celebrations, so
|
||||
`HockeyLive` does not inherit `CelebrationMixin` — the celebration code is not
|
||||
merely disabled for hockey, it is *not in hockey's MRO at all*. No shared
|
||||
state, no dead branches, no risk. Contrast with
|
||||
`if self.celebrations_enabled:` inside `SportsLive`, where a bug in
|
||||
celebration code can still crash a plugin that never wanted the feature.
|
||||
|
||||
2. **Variant behavior is a strategy object chosen by name, not a branch.**
|
||||
Live rotation exists in three dialects across the lineages; core ships all
|
||||
three behind `rotation_strategy: "swrr" | "weighted" | "simple"` and a plugin
|
||||
may register its own. Core never learns sport names.
|
||||
|
||||
3. **Sport-specific behavior is a documented override point.** The base class
|
||||
declares the seam; the plugin fills it. Basketball's tournament-round parsing
|
||||
and baseball's BDF sizing stay in their plugins forever — they are not
|
||||
candidates for promotion, and core must never grow a branch for them.
|
||||
|
||||
4. **Files bound the blast radius.** Capabilities live in their own modules so a
|
||||
diff shows at a glance which plugins a change can reach.
|
||||
|
||||
## Layering
|
||||
|
||||
```
|
||||
src/base_classes/sports/
|
||||
__init__.py re-exports the public API (import path unchanged)
|
||||
core.py SportsCore — fetch, cache, config, logos, fonts, odds,
|
||||
view-model extraction, the skin seam
|
||||
modes.py SportsUpcoming / SportsRecent / SportsLive
|
||||
capabilities/
|
||||
celebrations.py CelebrationMixin (opt-in: 4 of 9 plugins)
|
||||
rotation.py RotationStrategy + registry
|
||||
|
||||
src/common/
|
||||
sports_scroll.py SportsScrollDisplay / …Manager — scroll orchestration
|
||||
(content building stays in the plugins)
|
||||
```
|
||||
|
||||
`from src.base_classes.sports import SportsCore` keeps working — the package
|
||||
`__init__` re-exports, so the conversion is invisible to every existing importer.
|
||||
|
||||
## Override points (the plugin-facing seam)
|
||||
|
||||
The base class calls these; plugins implement or override them. This table is the
|
||||
contract — additions require a default implementation, removals require a
|
||||
deprecation cycle.
|
||||
|
||||
| Hook | Purpose | Default |
|
||||
|---|---|---|
|
||||
| `_fetch_data()` | Sport's schedule source | abstract |
|
||||
| `_extract_game_details(event)` | Sport-specific view-model fields on top of the common ones | delegates to `_extract_game_details_common` |
|
||||
| `_draw_scorebug_layout(game, force_clear)` | Sport's card rendering | base layout |
|
||||
| `_custom_scorebug_layout(game, draw)` | Per-sport overlay on the base layout | no-op |
|
||||
| `render_skin_card(game, size)` | Skin-system entry point | built-in fallback |
|
||||
| `score_phrase(points, team_abbr)` | Celebration wording (`"GOOOOAAALLL!"` vs `"TOUCHDOWN!"`). `points` is the score delta, which sports with variable-value scores use to name the play | `"<abbr> SCORES!"` — only consulted when `CelebrationMixin` is present |
|
||||
| `win_phrase(team_abbr)` | Win-celebration wording | `"<abbr> WINS!"` — mixin only |
|
||||
| `_favorite_key(game, side)` | Which view-model field identifies a team for favorites matching | `game["<side>_abbr"]` |
|
||||
| `_config_schema_path()` | Plugin's `config_schema.json` — returning it routes `_get_layout_offset` through the `src.element_style` resolver (and gives it the defaults to compare against) | `None`, i.e. the classic inline `customization.layout` read |
|
||||
| `_font_root()` | Directory to resolve `assets/fonts` against | core install root |
|
||||
|
||||
Two class attributes serve the same purpose for values that are per-sport
|
||||
constants rather than behavior:
|
||||
|
||||
| Attribute | Meaning | Default |
|
||||
|---|---|---|
|
||||
| `FINAL_PERIOD` | Period at/after which a zero clock can mean "over" | `4` (hockey overrides to `3`) |
|
||||
| `CLOCK_COUNTS_DOWN` | Whether `0:00` means "expired" | `True` (soccer/afl/nrl override to `False` — their clocks count up, so `0:00` is kickoff) |
|
||||
| `COALESCE_SCORING_SEQUENCE` | Fold score increments arriving during an active celebration into that one celebration | `False` (football overrides to `True` — a touchdown lands as +6, then +1 for the extra point) |
|
||||
|
||||
### Why these are seams and not branches
|
||||
|
||||
`_favorite_key` exists because NRL abbreviations are **not unique** — "NEW" is both
|
||||
Newcastle Knights and New Zealand Warriors, "CAN" both Canberra and Canterbury —
|
||||
so NRL matches favorites on team ID. Flattening every plugin to abbreviations
|
||||
would silently select the wrong club for NRL users. The base declares the seam,
|
||||
NRL fills it, and core never learns the string `"nrl"`.
|
||||
|
||||
`CLOCK_COUNTS_DOWN` exists for the same reason in the opposite direction: a
|
||||
soccer clock reading `0:00` means the match has not kicked off, so running the
|
||||
clock-expiry branch there would evict live games.
|
||||
|
||||
`COALESCE_SCORING_SEQUENCE` is the third of the same kind. In football one
|
||||
scoring play arrives as two score updates, so the follow-up must be folded into
|
||||
the first celebration; in soccer two increments a few seconds apart are two real
|
||||
goals, and folding them would swallow one. Neither default is "right" — which is
|
||||
precisely why it is a declared per-sport constant rather than a hidden
|
||||
assumption baked into the shared body.
|
||||
|
||||
## Capabilities
|
||||
|
||||
```
|
||||
capabilities/
|
||||
celebrations.py CelebrationMixin opt-in: afl, nrl, soccer, football
|
||||
rotation.py RotationStrategy + registry
|
||||
```
|
||||
|
||||
**`CelebrationMixin`** merges the two dialects the lineages grew
|
||||
(`_check_for_goal`/`celebrate_opponent_goals` vs
|
||||
`_check_for_score`/`celebrate_opponent_scores`). Their bodies were identical
|
||||
apart from three things, each now a seam: wording (`score_phrase`), follow-up
|
||||
suppression (`COALESCE_SCORING_SEQUENCE`), and team identity (`_favorite_key`,
|
||||
so NRL matches on id). Both config spellings are read, so a plugin adopting the
|
||||
mixin keeps working with the keys already in its published schema.
|
||||
|
||||
Mix it in **before** the mode class — `class SoccerLive(CelebrationMixin,
|
||||
SportsLive)` — so the celebration `display()` runs first and falls through to
|
||||
the scorebug via `super()`.
|
||||
|
||||
**Rotation strategies.** The three "dialects" turned out to be one algorithm
|
||||
(Smooth Weighted Round-Robin) in two shapes: an incremental picker holding state
|
||||
across calls (afl/nrl/soccer) and a precomputed per-cycle list
|
||||
(football/baseball/basketball, and hockey with a different loop shape). They
|
||||
agree within a cycle and differ only at the boundary — the incremental form has
|
||||
no restart seam — so core ships both rather than declaring a winner:
|
||||
|
||||
```python
|
||||
self.rotation = get_rotation_strategy("swrr", weight_for=self._live_weight)
|
||||
```
|
||||
|
||||
`weight_for` is supplied by the host, so the *favorites* policy stays with the
|
||||
plugin and `rotation.py` never learns what a favorite is. An unknown strategy
|
||||
name degrades to `simple` rather than raising: the name comes from user config,
|
||||
and a typo should cost the boost, not the scoreboard. When a plugin needs an
|
||||
ordering that core does not ship, it calls `register_rotation_strategy` to add
|
||||
its own — rather than core growing a branch for it.
|
||||
|
||||
`test_sports_capabilities.py` checks each strategy against a **verbatim
|
||||
transcription** of the plugin code it replaces, over every live-game shape up to
|
||||
four games. That differential is what B5 deletes the bundled copies on the
|
||||
strength of.
|
||||
|
||||
## Scroll display — where the promotion line falls
|
||||
|
||||
`src/common/sports_scroll.py` is deliberately *not* a superset of the ten
|
||||
`scroll_display.py` copies. A method-level comparison of the eight that share a
|
||||
shape (f1 and ufc are genuine forks) found a sharp split:
|
||||
|
||||
| Layer | Evidence | Outcome |
|
||||
|---|---|---|
|
||||
| Orchestration — `get_all_vegas_content_items`, `clear_all`, `get_scroll_info`, `get_dynamic_duration`, `is_complete`, `display_frame` | identical to 96–100% similar across all eight | **promoted** |
|
||||
| Settings — `_get_scroll_settings` | one algorithm; the copies differ *only* in which league keys they walk | **promoted**, with the ladder as data (`SCROLL_LEAGUE_KEYS`) |
|
||||
| Content — `prepare_scroll_content`, `_load_separator_icons` | 8 distinct bodies across 8 plugins (145 lines, 53% similar at worst); icons 6% | **override point, permanently** |
|
||||
|
||||
Same name, different job: `prepare_scroll_content` draws *this sport's* game
|
||||
card. Merging the eight bodies would be the exact mistake the promotion rule
|
||||
exists to prevent, so the base class raises `NotImplementedError` rather than
|
||||
rendering something plausible — a base that rendered *something* would let a
|
||||
plugin ship a silently blank scroll.
|
||||
|
||||
The one behavior the upstreamed version adds is native
|
||||
`global_config['target_fps']` support. The bundled copies hardcode ~100 FPS via
|
||||
`scroll_delay = 0.01` and never consult the global smooth-scrolling target;
|
||||
Part A threaded it through each copy by hand, and this makes that threading
|
||||
legacy compatibility rather than the mechanism.
|
||||
|
||||
## Phases
|
||||
|
||||
B0–B3 are merged and shipping in core 3.2.0. Everything that remains is
|
||||
**rollout**, and it splits into three phases with very different risk profiles.
|
||||
The original plan folded the last two together; they are separated here because
|
||||
one of them is safe by construction and the other is not.
|
||||
|
||||
| Phase | Scope | Status | Gate |
|
||||
|---|---|---|---|
|
||||
| **B0** | Characterization tests, CI unit job, `element_style`, font cwd fix, CHANGELOG discipline | ✅ | — |
|
||||
| **B1** | Promote the nine universal methods; convert `sports.py` → package | ✅ | Characterization suite green; no behavior change intended |
|
||||
| **B2** | `CelebrationMixin` + rotation strategies as opt-in capabilities | ✅ | Non-adopters have zero new code in their MRO; strategies checked against verbatim plugin transcriptions |
|
||||
| **B3** | Upstream the scroll **orchestration** layer as `src/common/sports_scroll.py`, reading `global_config['target_fps']` natively | ✅ | Content building stays per-sport |
|
||||
| **B4** | Ship 3.2.0 *and* make version reporting trustworthy | ⏳ **next** | Tag, release, and `src.__version__` agree; compatibility gate merged |
|
||||
| **B5** | Adoption — guarded core imports: three pilots, then the remaining six. **Bundled copies stay.** | after B4 | Per plugin: harness + goldens byte-identical, then a device soak |
|
||||
| **B6** | Sunset — delete the bundled copies | **blocked** | B4's gate shipped *and* in users' hands (see below) |
|
||||
|
||||
### B4 — what "ship 3.2.0" actually requires
|
||||
|
||||
Cutting the tag is the small part. The version *number* has to become something
|
||||
a floor can be trusted against, and today it is not:
|
||||
|
||||
- **The tag and `src.__version__` have never agreed.** `v3.1.0` was tagged
|
||||
2026-05-31; `__version__` only became `"3.1.0"` on 2026-07-12 (`7f7f0d64`).
|
||||
The v3.1.0 release therefore reports `__version__ = "1.0.0"`.
|
||||
- **Which silences the compatibility warning entirely for that population.**
|
||||
`PluginLoader._warn_if_incompatible` skips the check when the parsed core
|
||||
version is below `(2, 0, 0)` — an anti-spam guard that, given the above,
|
||||
matches exactly the users most likely to be behind.
|
||||
- **Nothing enforces a floor anyway.** The check is advisory (it logs and
|
||||
continues), and neither `StoreManager.install_plugin` nor
|
||||
`StoreManager.update_plugin` compares the core version at all — `update_plugin`
|
||||
compares the plugin's manifest version against the registry's
|
||||
`latest_version` and nothing else.
|
||||
|
||||
So B4 is: tag and release 3.2.0; make the tag, the release, and `__version__`
|
||||
agree, and keep them agreeing; reconsider the `< 2.0.0` skip; migrate manifests
|
||||
from `ledmatrix_min` to `ledmatrix_min_version`; and add the install/update
|
||||
compatibility gate that B6 depends on.
|
||||
|
||||
#### Two fields express compatibility, and the gate only reads one
|
||||
|
||||
`compatible_versions` is the canonical contract: `schema/manifest_schema.json`
|
||||
**requires** it, all 42 published manifests carry it, and it holds semver
|
||||
*ranges* — `[">=2.0.0"]` in 41 of them, `[">=1.0.0"]` in `7-segment-clock`.
|
||||
`ledmatrix_min_version` is the optional per-release floor inside `versions[]`.
|
||||
|
||||
The gate as merged reads only the floor. Today that is harmless: no manifest
|
||||
uses an upper bound, and the two fields agree everywhere except
|
||||
`7-segment-clock` (`>=1.0.0` against a `2.0.0` floor). But the fields *can*
|
||||
disagree, and the range syntax the schema already permits includes upper bounds
|
||||
— a plugin declaring `["2.0.0 - 2.9.9"]` means "not compatible with 3.x" and
|
||||
the gate would install it on 3.2.0 regardless.
|
||||
|
||||
**Before B6, the gate must evaluate `compatible_versions` as well**, and the
|
||||
manifest migration must reconcile the two fields rather than only renaming the
|
||||
floor. Deciding which wins when they disagree is part of that work; the safe
|
||||
default is the more restrictive.
|
||||
|
||||
(The schema also deprecates a top-level `ledmatrix_version` in favour of
|
||||
`compatible_versions`. No manifest still carries it, so there is nothing to
|
||||
migrate there.)
|
||||
|
||||
### B5 — adoption is safe by construction
|
||||
|
||||
A plugin adopting core imports keeps its bundled copy and reaches it through the
|
||||
guarded import (see the Upgradability table above). On a core that ships the
|
||||
module the plugin uses core code; on one that doesn't it falls back and behaves
|
||||
exactly as it does today. There is no version of this step that breaks a user,
|
||||
which is why it does not wait for B6's gate.
|
||||
|
||||
The hockey scroll-display pilot is **already validated**: adopted against a core
|
||||
carrying 3.2.0, `scroll_display.py` went from 691 to 289 lines and all 16 harness
|
||||
renders (8 sizes × 2 screens) came out byte-for-byte identical to the
|
||||
pre-adoption run. That byte-comparison is the acceptance gate for every
|
||||
adoption. The recipe and its two gotchas are in the plugins repo's
|
||||
`docs/plugin-development/08-shared-sports-code.md`.
|
||||
|
||||
### B6 — why the sunset needs more than a version floor
|
||||
|
||||
Deleting a bundled copy removes the fallback, so the guarded import becomes a
|
||||
hard dependency. On a core without the module the plugin raises
|
||||
`ModuleNotFoundError` at load; `PluginManager.load_plugin` catches it, records
|
||||
`PluginState.ERROR`, logs one line, and continues. Nothing crashes — the user
|
||||
simply loses that scoreboard, with no visible explanation.
|
||||
|
||||
Verified against a `v3.1.0` worktree: `src/common/sports_scroll.py`,
|
||||
`src/element_style.py` and the `src/base_classes/sports/` package are all absent
|
||||
there, and the import fails with `exc.name == 'src.common.sports_scroll'`. Guard
|
||||
sets must name that exact dotted path — `{"src"}` alone does not match it.
|
||||
|
||||
Combined with the B4 findings, a plugin that deletes its copy today reaches an
|
||||
un-updated user through a normal store update, fails to load, and warns nobody.
|
||||
**B6 therefore waits for B4's compatibility gate to have shipped and to have
|
||||
been in users' hands long enough that the population running a core without it
|
||||
is small.** The bundled copies cost disk space; deleting them early costs
|
||||
scoreboards, silently. That trade is not close.
|
||||
|
||||
Before the first sunset, add a **compatibility regression test**. It has to
|
||||
cover four cases, not one — B5's safety claim and B6's failure mode are
|
||||
different propositions and only the second is obvious:
|
||||
|
||||
| | bundled copy present | bundled copy removed |
|
||||
|---|---|---|
|
||||
| **pinned old core** | **loads** — this is B5's whole guarantee, that the guarded import falls back | `PluginState.ERROR`, and the recorded error names the exact missing module |
|
||||
| **current core** | loads, using core code | loads, using core code |
|
||||
|
||||
The top-left cell is the one worth writing first: nothing in the suite currently
|
||||
proves that an adopted plugin still works on a core that predates the module,
|
||||
which is the entire basis for saying B5 is safe to run ahead of the gate.
|
||||
|
||||
Assert the old-core/removed-copy case as `PluginState.ERROR` **plus the missing
|
||||
module path**, not as an uncaught exception. `PluginManager.load_plugin` catches
|
||||
`ModuleNotFoundError`, so nothing propagates — a test expecting a raise would
|
||||
pass for the wrong reason on a core where the module is merely broken rather
|
||||
than absent. "Fails loudly" is aspirational, not what the code does today: it
|
||||
fails into `ERROR` state with one log line, which is precisely why B6 needs the
|
||||
gate rather than trusting the failure to be noticed.
|
||||
|
||||
The same suite should exercise the install/update gate, since it is the other
|
||||
half of the guarantee.
|
||||
|
||||
## What's next
|
||||
|
||||
In order. Each step is independently useful and independently revertible.
|
||||
|
||||
1. **Tag and publish v3.2.0.** The code is already on `main` (`21825cbf`).
|
||||
Nothing else blocks this, and it is what makes `ledmatrix_min_version:
|
||||
"3.2.0"` refer to something real.
|
||||
2. **Make the version number honest.** Have the release process assert that the
|
||||
tag, the GitHub release, and `src.__version__` agree — a check in CI is
|
||||
cheaper than the confusion of the last two releases. Then revisit the
|
||||
`< 2.0.0` skip in `_warn_if_incompatible`, which currently silences the
|
||||
warning for the users who most need it.
|
||||
3. **Add the compatibility gate** to `StoreManager.install_plugin` and
|
||||
`.update_plugin`: refuse a plugin whose declared floor exceeds
|
||||
`src.__version__`, and surface the reason in the store UI rather than only
|
||||
the log. This is the single change that turns the floor from documentation
|
||||
into a guarantee, and B6 depends on it.
|
||||
4. **Migrate the manifests** to `ledmatrix_min_version`, and reconcile them with
|
||||
`compatible_versions` (see above — that field is the required, canonical one,
|
||||
and the gate does not read it yet). Currently 28 plugins spell the floor both
|
||||
ways across their `versions[]` entries, 12 use only the old spelling, and 2
|
||||
only the new. Scope the sweep to the nine sports plugins if a 42-plugin
|
||||
version-bump wave isn't worth it — but the `compatible_versions` half has to
|
||||
cover every manifest the gate can refuse, or define explicit legacy handling,
|
||||
before the gate is allowed to block anything.
|
||||
5. **Run B5 adoption** — hockey, soccer, football, then the remaining six.
|
||||
Bundled copies stay. Byte-identical harness output per plugin, then a soak.
|
||||
6. **Only then plan B6**, with the compatibility regression test described above
|
||||
in CI first.
|
||||
|
||||
## How to keep this project healthy
|
||||
|
||||
Lessons this migration paid for, worth applying beyond it:
|
||||
|
||||
- **A version number is a promise; keep it in one place.** Three different
|
||||
answers to "what version am I on" (tag, release, `__version__`) is what made
|
||||
the floor untrustworthy. Assert their agreement mechanically.
|
||||
- **Advisory checks protect nobody.** If a rule matters, enforce it where the
|
||||
action happens — the install path, not a log line the user will never read.
|
||||
If it doesn't matter enough to enforce, don't write the rule.
|
||||
- **Prefer failures that are loud and early.** A plugin that dies at load with
|
||||
one journal line is indistinguishable, to a user, from a plugin that was never
|
||||
installed. Surface plugin health in the UI.
|
||||
- **Keep the two repos' rules in sync deliberately.** The sunset rule lives in
|
||||
both this file and the plugins repo's
|
||||
`docs/plugin-development/08-shared-sports-code.md`. When one changes, change
|
||||
the other in the same PR — drift between them is how a contributor ends up
|
||||
following a rule that was superseded.
|
||||
- **Measure before and after, on real hardware.** Byte-identical harness renders
|
||||
and a device soak caught what unit tests could not. Reserve "it should be
|
||||
fine" for things you have actually looked at.
|
||||
|
||||
## Rules for contributors
|
||||
|
||||
- **Promote on evidence, not intuition.** A method moves to core when every copy
|
||||
has it and they agree on intent. Otherwise it stays in the plugins.
|
||||
- **Never add a sport name to core.** If core needs to know which sport it is,
|
||||
the design is wrong — add an override point instead.
|
||||
- **A capability that is not opted into must not execute.** If you find yourself
|
||||
writing `if self.<capability>_enabled` inside a base class, it belongs in a
|
||||
mixin.
|
||||
- **Touch the view-model keys only additively.** Published skins depend on them.
|
||||
- **Every promotion lands with the characterization suite green**, and every
|
||||
pilot adoption lands with that plugin's harness and golden suites green.
|
||||
@@ -82,6 +82,70 @@ python3 web_interface/start.py
|
||||
|
||||
## Common Issues by Category
|
||||
|
||||
### Installation & Build Issues
|
||||
|
||||
#### Step 6 fails: "Failed building wheel for rgbmatrix"
|
||||
|
||||
**Symptoms:**
|
||||
|
||||
```
|
||||
note: This error originates from a subprocess, and is likely not a problem with pip.
|
||||
ERROR: Failed building wheel for rgbmatrix
|
||||
Failed to build rgbmatrix
|
||||
✗ Failed to install rpi-rgb-led-matrix Python package
|
||||
```
|
||||
|
||||
**Cause:**
|
||||
|
||||
Almost always the kernel's out-of-memory killer, not missing build tools. The
|
||||
`rpi-rgb-led-matrix` library compiles roughly 45 C++ translation units, two of
|
||||
them Cython-generated — a single `cc1plus` on those can peak near 800MB. The
|
||||
build system defaults to running several of those at once, which exceeds RAM on
|
||||
512MB and 1GB boards. Because the OOM killer writes nothing to pip's output, the
|
||||
failure looks like a toolchain problem, and `sudo apt install -y
|
||||
python-dev-is-python3 cmake build-essential` will report everything is already
|
||||
up to date.
|
||||
|
||||
**How to confirm:**
|
||||
|
||||
```bash
|
||||
dmesg -T | grep -i "out of memory" # look for "Killed process ... (cc1plus)"
|
||||
free -h # total RAM and swap
|
||||
```
|
||||
|
||||
**Fix:**
|
||||
|
||||
Current versions of the installer handle this automatically: they cap build
|
||||
parallelism based on available RAM and add a temporary swapfile for the build,
|
||||
removing it when the build finishes. If you are on an older checkout, or the
|
||||
temporary swapfile could not be created, either force a serial compile:
|
||||
|
||||
```bash
|
||||
sudo ./first_time_install.sh --build-jobs 1
|
||||
```
|
||||
|
||||
or add permanent swap and re-run the installer, which resumes at Step 6:
|
||||
|
||||
```bash
|
||||
sudo apt install -y dphys-swapfile
|
||||
sudo sed -i 's/^#\?CONF_SWAPSIZE=.*/CONF_SWAPSIZE=2048/' /etc/dphys-swapfile
|
||||
sudo sed -i 's/^#\?CONF_MAXSWAP=.*/CONF_MAXSWAP=2048/' /etc/dphys-swapfile
|
||||
sudo dphys-swapfile swapoff && sudo dphys-swapfile setup && sudo dphys-swapfile swapon
|
||||
sudo ./first_time_install.sh
|
||||
```
|
||||
|
||||
`CONF_MAXSWAP` matters: it defaults to 2048 and silently clamps `CONF_SWAPSIZE`,
|
||||
so setting only `CONF_SWAPSIZE` to a larger value has no effect.
|
||||
|
||||
**Related:**
|
||||
|
||||
- The installer needs roughly 3GB free on the card to place the swapfile. If
|
||||
disk is tight it will say so and skip the swapfile: `sudo apt clean` first.
|
||||
- `sudo bash scripts/check_system_compatibility.sh` reports RAM and disk.
|
||||
- `sudo bash scripts/diagnose_dependencies.sh` dumps build-dependency state.
|
||||
|
||||
---
|
||||
|
||||
### Web Interface & Service Issues
|
||||
|
||||
#### Service Not Running/Starting
|
||||
@@ -266,8 +330,8 @@ sudo systemctl cat ledmatrix-web | grep User
|
||||
|
||||
6. **Manually enable AP mode:**
|
||||
```bash
|
||||
# Via API
|
||||
curl -X POST http://localhost:5000/api/wifi/ap/enable
|
||||
# Via API (the WiFi blueprint is mounted under /api/v3)
|
||||
curl -X POST http://localhost:5000/api/v3/wifi/ap/enable
|
||||
|
||||
# Via Python
|
||||
python3 -c "
|
||||
@@ -418,19 +482,19 @@ sudo systemctl cat ledmatrix-web | grep User
|
||||
|
||||
1. **Check plugin directory exists:**
|
||||
```bash
|
||||
ls -ld plugins/plugin-id/
|
||||
ls -ld plugin-repos/plugin-id/
|
||||
```
|
||||
|
||||
2. **Verify manifest.json:**
|
||||
```bash
|
||||
cat plugins/plugin-id/manifest.json
|
||||
cat plugin-repos/plugin-id/manifest.json
|
||||
# Verify all required fields present
|
||||
```
|
||||
|
||||
3. **Check dependencies installed:**
|
||||
```bash
|
||||
if [ -f plugins/plugin-id/requirements.txt ]; then
|
||||
pip3 install --break-system-packages -r plugins/plugin-id/requirements.txt
|
||||
if [ -f plugin-repos/plugin-id/requirements.txt ]; then
|
||||
pip3 install --break-system-packages -r plugin-repos/plugin-id/requirements.txt
|
||||
fi
|
||||
```
|
||||
|
||||
@@ -443,7 +507,7 @@ sudo systemctl cat ledmatrix-web | grep User
|
||||
```bash
|
||||
python3 -c "
|
||||
import sys
|
||||
sys.path.insert(0, 'plugins/plugin-id')
|
||||
sys.path.insert(0, 'plugin-repos/plugin-id')
|
||||
from manager import PluginClass
|
||||
print('Plugin imports successfully')
|
||||
"
|
||||
@@ -459,12 +523,18 @@ sudo systemctl cat ledmatrix-web | grep User
|
||||
**Solutions:**
|
||||
|
||||
1. **Manual cache clearing:**
|
||||
```bash
|
||||
# Remove plugin-specific cache
|
||||
rm -rf cache/plugin-id*
|
||||
|
||||
# Or remove all cache
|
||||
rm -rf cache/*
|
||||
The cache does not live in the project directory. The cache manager
|
||||
uses the first writable location among `/var/cache/ledmatrix`,
|
||||
`~/.ledmatrix_cache`, `/opt/ledmatrix/cache`, and
|
||||
`$TMPDIR/ledmatrix_cache`. The easiest option is the helper script:
|
||||
|
||||
```bash
|
||||
# Clear the cache with the helper script
|
||||
sudo python3 scripts/utils/clear_cache.py
|
||||
|
||||
# Or remove files manually from the cache dir in use, e.g.:
|
||||
sudo rm -rf /var/cache/ledmatrix/*
|
||||
|
||||
# Restart display
|
||||
sudo systemctl restart ledmatrix
|
||||
@@ -472,8 +542,8 @@ sudo systemctl cat ledmatrix-web | grep User
|
||||
|
||||
2. **Check cache permissions:**
|
||||
```bash
|
||||
ls -ld cache/
|
||||
sudo chown -R ledpi:ledpi cache/
|
||||
ls -ld /var/cache/ledmatrix
|
||||
sudo ./scripts/fix_perms/fix_cache_permissions.sh
|
||||
```
|
||||
|
||||
---
|
||||
@@ -708,11 +778,11 @@ nmcli device status
|
||||
```bash
|
||||
# Check file exists
|
||||
ls -l config/config.json
|
||||
ls -l plugins/plugin-id/manifest.json
|
||||
ls -l plugin-repos/plugin-id/manifest.json
|
||||
|
||||
# Check directory structure
|
||||
ls -la web_interface/
|
||||
ls -la plugins/
|
||||
ls -la plugin-repos/
|
||||
|
||||
# Check file permissions
|
||||
ls -l config/config_secrets.json
|
||||
@@ -740,7 +810,7 @@ python3 -c "from src.wifi_manager import WiFiManager; print('OK')"
|
||||
# Test plugin import
|
||||
python3 -c "
|
||||
import sys
|
||||
sys.path.insert(0, 'plugins/plugin-id')
|
||||
sys.path.insert(0, 'plugin-repos/plugin-id')
|
||||
from manager import PluginClass
|
||||
print('Plugin imports OK')
|
||||
"
|
||||
@@ -748,40 +818,29 @@ print('Plugin imports OK')
|
||||
|
||||
---
|
||||
|
||||
## Service File Template
|
||||
## Reinstalling Service Files
|
||||
|
||||
If your systemd service file is corrupted or missing, use this template:
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=LEDMatrix Web Interface
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=ledpi
|
||||
Group=ledpi
|
||||
WorkingDirectory=/home/ledpi/LEDMatrix
|
||||
Environment="PYTHONUNBUFFERED=1"
|
||||
ExecStart=/usr/bin/python3 /home/ledpi/LEDMatrix/web_interface/start.py
|
||||
Restart=on-failure
|
||||
RestartSec=5s
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=ledmatrix-web
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
Save to `/etc/systemd/system/ledmatrix-web.service` and run:
|
||||
If a systemd service file is corrupted or missing, do NOT hand-write
|
||||
one. The real unit files live in the repo's `systemd/` directory
|
||||
(`ledmatrix.service`, `ledmatrix-web.service`,
|
||||
`ledmatrix-wifi-monitor.service`) and contain a
|
||||
`__PROJECT_ROOT_DIR__` placeholder that the install scripts substitute
|
||||
with your actual checkout path:
|
||||
|
||||
```bash
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable ledmatrix-web
|
||||
sudo systemctl start ledmatrix-web
|
||||
# Reinstall the display service unit
|
||||
sudo ./scripts/install/install_service.sh
|
||||
|
||||
# Reinstall the web interface service unit
|
||||
sudo ./scripts/install/install_web_service.sh
|
||||
```
|
||||
|
||||
Note that `ledmatrix-web.service` runs as root via
|
||||
`scripts/utils/start_web_conditionally.py` — root is needed for
|
||||
system operations (service control, WiFi management), and the wrapper
|
||||
honors the `web_display_autostart` config flag before actually
|
||||
starting the web server.
|
||||
|
||||
---
|
||||
|
||||
## Complete Diagnostic Script
|
||||
@@ -814,7 +873,7 @@ echo ""
|
||||
|
||||
echo "5. File Structure:"
|
||||
ls -la web_interface/ | head -10
|
||||
ls -la plugins/ | head -10
|
||||
ls -la plugin-repos/ | head -10
|
||||
echo ""
|
||||
|
||||
echo "6. Python Imports:"
|
||||
@@ -890,12 +949,11 @@ sudo systemctl restart ledmatrix-web
|
||||
# Reinstall WiFi monitor
|
||||
sudo ./scripts/install/install_wifi_monitor.sh
|
||||
|
||||
# Recreate service files from templates
|
||||
sudo cp templates/ledmatrix.service /etc/systemd/system/
|
||||
sudo cp templates/ledmatrix-web.service /etc/systemd/system/
|
||||
# Recreate service files (substitutes __PROJECT_ROOT_DIR__ in systemd/ units)
|
||||
sudo ./scripts/install/install_service.sh
|
||||
sudo ./scripts/install/install_web_service.sh
|
||||
|
||||
# Reload and restart
|
||||
sudo systemctl daemon-reload
|
||||
# Restart
|
||||
sudo systemctl restart ledmatrix ledmatrix-web
|
||||
```
|
||||
|
||||
|
||||
@@ -39,12 +39,18 @@ present:
|
||||
- **WiFi** — Network selection and AP-mode setup
|
||||
- **Schedule** — Power and dim schedules
|
||||
- **Display** — Matrix hardware configuration (rows, cols, hardware
|
||||
mapping, GPIO slowdown, brightness, PWM)
|
||||
mapping, GPIO slowdown, brightness, PWM) and Vegas Scroll Mode
|
||||
settings
|
||||
- **Rotation** — drag-and-drop **Rotation Order** list and per-plugin
|
||||
**Screen Durations**
|
||||
- **Config Editor** — Raw `config.json` editor with validation
|
||||
- **Backup & Restore** — back up and restore your configuration
|
||||
- **Fonts** — Upload and manage fonts
|
||||
- **Logs** — Real-time log streaming
|
||||
- **Cache** — Cached data inspection and cleanup
|
||||
- **Operation History** — Recent service operations
|
||||
- **Tools** — system diagnostics, git & updates, Python dependencies,
|
||||
maintenance, power supply, network radio, services, and plugin health
|
||||
|
||||
A second nav row holds plugin tabs:
|
||||
|
||||
@@ -111,6 +117,12 @@ Configure your LED matrix hardware:
|
||||
- Dynamic Duration — global cap for plugins that extend their display
|
||||
time based on content
|
||||
|
||||
**Vegas Scroll Mode:** the Display tab also has a full Vegas Scroll
|
||||
Mode section — enable toggle, scroll speed, separator width, dynamic
|
||||
duration, and related settings — so you can configure Vegas mode
|
||||
entirely from the web UI without hand-editing JSON. See
|
||||
[ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) for what the options do.
|
||||
|
||||
Changes require **Restart Display Service** from the Overview tab.
|
||||
|
||||
### Plugin Manager Tab
|
||||
@@ -159,9 +171,10 @@ Manage fonts for your display:
|
||||
- See font previews
|
||||
- Check font sizes and styles
|
||||
|
||||
**Plugin Font Overrides:**
|
||||
- Set custom fonts for specific plugins
|
||||
- Override default font choices
|
||||
**Font Overrides:**
|
||||
- Overrides are set per display *element* (e.g. a specific score or
|
||||
clock text element), not per plugin
|
||||
- Override default font choices for individual elements
|
||||
- Preview font changes
|
||||
|
||||
**Delete Fonts:**
|
||||
@@ -183,9 +196,11 @@ View real-time system logs:
|
||||
- Filter by plugin or component
|
||||
|
||||
**Actions:**
|
||||
- **Refresh**: Reload the log view
|
||||
- **Clear**: Clear the current view
|
||||
- **Download**: Download logs for offline analysis
|
||||
- **Pause**: Pause auto-scrolling
|
||||
- **Auto-scroll** checkbox: toggle automatic scrolling to the latest
|
||||
entries
|
||||
|
||||
---
|
||||
|
||||
@@ -248,7 +263,8 @@ The web interface uses Server-Sent Events (SSE) for real-time updates:
|
||||
**Performance:**
|
||||
- Minimal bandwidth usage
|
||||
- Server-side rendering for fast load times
|
||||
- Progressive enhancement - works without JavaScript
|
||||
- The UI is built on Alpine.js and HTMX, so JavaScript must be enabled
|
||||
in the browser
|
||||
|
||||
---
|
||||
|
||||
@@ -267,17 +283,6 @@ The interface is fully responsive and works on mobile devices:
|
||||
|
||||
---
|
||||
|
||||
## Keyboard Shortcuts
|
||||
|
||||
Use keyboard shortcuts for faster navigation:
|
||||
|
||||
- **Tab**: Navigate between form fields
|
||||
- **Enter**: Submit forms
|
||||
- **Esc**: Close modals
|
||||
- **Ctrl+F**: Search in logs
|
||||
|
||||
---
|
||||
|
||||
## API Access
|
||||
|
||||
The web interface is built on a REST API that you can access programmatically:
|
||||
@@ -288,7 +293,7 @@ http://your-pi-ip:5000/api/v3
|
||||
```
|
||||
|
||||
The API blueprint mounts at `/api/v3` (see
|
||||
`web_interface/app.py:144`). All endpoints below are relative to that
|
||||
`web_interface/app.py:199`). All endpoints below are relative to that
|
||||
base.
|
||||
|
||||
**Common Endpoints:**
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# Plugin Safety Harness
|
||||
|
||||
Renders a plugin across **every declared screen (mode)** and **a spread of
|
||||
matrix sizes**, and fails if any combination crashes, draws past the panel edge,
|
||||
or — for plugins that ship golden images — drifts visually. The goal: change a
|
||||
plugin without breaking a size or screen you didn't think to test.
|
||||
|
||||
## Sizes: a sample, not a fixed list
|
||||
|
||||
There is **no fixed set of supported panel sizes** — an RGB matrix build can be
|
||||
any width/height and configuration (square, rectangle, 2×2, 4×4, 8×2, long
|
||||
strips, tall stacks). Plugins are expected to read dimensions dynamically
|
||||
(`self.display_manager.matrix.width/height`) and lay themselves out
|
||||
accordingly, so a hardcoded coordinate or unscaled font shows up as a failure
|
||||
here.
|
||||
|
||||
The harness therefore renders against a **representative sample** that spans the
|
||||
axes of variation (`DEFAULT_TEST_SIZES` in `src/plugin_system/testing/sizes.py`),
|
||||
not an authoritative list:
|
||||
|
||||
Each module is 64×32; entries are real panel-grid arrangements (cols × rows):
|
||||
|
||||
| Size | Grid | Why it's in the sample |
|
||||
|---------|------|--------------------------------------------|
|
||||
| 64×32 | 1×1 | single panel — tightest common rectangle |
|
||||
| 128×32 | 2×1 | the baseline most plugins are tuned for |
|
||||
| 64×64 | 1×2 | stacked — tall-narrow centering |
|
||||
| 128×64 | 2×2 | block — icon scaling / vertical centering |
|
||||
| 256×32 | 4×1 | long strip — wide horizontal layout |
|
||||
| 128×96 | 2×3 | tall — vertical overflow |
|
||||
| 256×128 | 4×4 | large block — both dimensions big at once |
|
||||
|
||||
**Override the sizes entirely** to test your actual hardware (or any shape):
|
||||
|
||||
```bash
|
||||
# CLI — one-off:
|
||||
python scripts/check_plugin.py --plugin clock-simple --sizes 8x16,64x64,256x32
|
||||
|
||||
# pytest — force every plugin onto your panel(s):
|
||||
LEDMATRIX_TEST_SIZES="8x16,128x128" pytest test/plugins/test_plugin_matrix.py
|
||||
|
||||
# Per-plugin — declare the shapes a plugin targets in its test/harness.json:
|
||||
# { "sizes": [[8, 16], [64, 64]] }
|
||||
```
|
||||
|
||||
Precedence: `LEDMATRIX_TEST_SIZES` env (global) → per-plugin `harness.json`
|
||||
`sizes` → the default sample. Bounds checking adapts to whatever sizes a run
|
||||
uses — the backing canvas is padded out to the **largest** panel in the run, so
|
||||
a coordinate meant for a big build is still caught when rendering a small one.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
# Functional + bounds check across all sizes/screens:
|
||||
python scripts/check_plugin.py --plugin clock-simple
|
||||
|
||||
# Every discovered plugin:
|
||||
python scripts/check_plugin.py --all
|
||||
|
||||
# Dump PNGs to eyeball each size/screen:
|
||||
python scripts/check_plugin.py --plugin ledmatrix-weather --out-dir /tmp/preview
|
||||
```
|
||||
|
||||
Exit code is non-zero if any `(plugin, size, screen)` fails. Plugins are
|
||||
discovered in `plugin-repos/` and `plugins/` (override with `--plugin-dir`).
|
||||
|
||||
## What it checks (Phase 1 — always on)
|
||||
|
||||
1. **Loads** and builds its mode list.
|
||||
2. **Renders every screen** at every size without raising. `update()` may fail
|
||||
(no network in CI) and is tolerated; a crash in `display()` is a failure —
|
||||
`display()` must handle the no-data state.
|
||||
3. **Bounds**: nothing is drawn past the right/bottom edge. Implemented by
|
||||
`BoundsCheckingDisplayManager`, which backs the declared panel with an
|
||||
oversized canvas and flags any pixels that land in the margin. (Left/top
|
||||
overflow at negative coordinates and BDF text are not flagged — golden images
|
||||
cover those.)
|
||||
|
||||
## Golden images (Phase 2 — opt-in per plugin)
|
||||
|
||||
A plugin opts in by committing reference PNGs and (usually) a small harness spec:
|
||||
|
||||
```
|
||||
plugins/<id>/test/harness.json # how to render deterministically
|
||||
plugins/<id>/test/fixtures/mock.json # optional cached data
|
||||
plugins/<id>/test/golden/<WxH>/<mode>.png
|
||||
```
|
||||
|
||||
`test/harness.json` keys (all optional):
|
||||
|
||||
```json
|
||||
{
|
||||
"config": { "timezone": "UTC" },
|
||||
"mock_data": "fixtures/mock.json",
|
||||
"freeze_time": "2025-08-01 15:25:00",
|
||||
"skip_update": false,
|
||||
"sizes": [[128, 32], [128, 64]]
|
||||
}
|
||||
```
|
||||
|
||||
Generate / refresh goldens after an intentional visual change, then review the
|
||||
diff before committing:
|
||||
|
||||
```bash
|
||||
python scripts/check_plugin.py --plugin clock-simple --update-golden \
|
||||
--config '{"timezone":"UTC"}' --freeze-time "2025-08-01 15:25:00"
|
||||
```
|
||||
|
||||
Comparison is exact by default (`compare_images` in `harness.py` accepts a
|
||||
tolerance for known anti-aliasing noise). Determinism requires a pinned Pillow
|
||||
and the bundled fonts — keep both stable when regenerating goldens.
|
||||
|
||||
## Tests & CI
|
||||
|
||||
- `test/plugins/test_harness.py` — unit tests for bounds detection, image
|
||||
comparison, and mode enumeration (run anywhere).
|
||||
- `test/plugins/test_plugin_matrix.py` — parametrized over discovered plugins ×
|
||||
sizes × screens; honors each plugin's `test/harness.json` and goldens. Skips
|
||||
when no plugins are present (e.g. a fresh core checkout); set
|
||||
`LEDMATRIX_REQUIRE_PLUGINS=1` in a pipeline where plugins must be present to
|
||||
turn an empty discovery into a hard failure instead. Point it at the monorepo
|
||||
with `LEDMATRIX_PLUGINS_DIR=/path/to/ledmatrix-plugins/plugins`.
|
||||
- `.github/workflows/test.yml` — runs the harness + visual tests on every PR.
|
||||
|
||||
The plugin monorepo has its own `Plugin Safety` workflow that runs this harness
|
||||
against changed plugins on every PR.
|
||||
|
||||
## Developer workflow
|
||||
|
||||
1. Change the plugin on a branch.
|
||||
2. `python scripts/check_plugin.py --plugin <id> --out-dir /tmp/preview` and
|
||||
eyeball the PNGs.
|
||||
3. Intentional visual change? `--update-golden`, review diffs, commit goldens.
|
||||
4. (Monorepo) bump `manifest.json` version and let the pre-commit hook sync
|
||||
`plugins.json`.
|
||||
5. Push — CI re-runs the harness across all sizes and gates the PR.
|
||||
@@ -206,6 +206,40 @@ To use an existing widget in your plugin's `config_schema.json`, simply add the
|
||||
|
||||
The widget will be automatically rendered when the plugin configuration form is loaded.
|
||||
|
||||
## Marking Fields as Advanced (`x-advanced`)
|
||||
|
||||
Add `"x-advanced": true` to any top-level, non-object property to move it out
|
||||
of the main form and into a single collapsed **Advanced Settings** section at
|
||||
the bottom of the plugin's configuration page:
|
||||
|
||||
```json
|
||||
{
|
||||
"properties": {
|
||||
"city": {
|
||||
"type": "string",
|
||||
"title": "City"
|
||||
},
|
||||
"request_timeout": {
|
||||
"type": "integer",
|
||||
"default": 10,
|
||||
"description": "HTTP timeout in seconds",
|
||||
"x-advanced": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Guidelines:
|
||||
|
||||
- Use it for fine-tuning knobs most users never touch (timeouts, retry
|
||||
behavior, cache TTLs, styling overrides). Anything a first-time user must
|
||||
set to get the plugin working should stay basic.
|
||||
- Nothing is hidden permanently — the section expands on click, and the
|
||||
settings search finds and auto-expands advanced fields like any others.
|
||||
- The flag is ignored on `object`-type properties (they already render as
|
||||
their own collapsible sections) and is safely ignored by older cores, so
|
||||
adding it never breaks compatibility.
|
||||
|
||||
## Creating Custom Widgets
|
||||
|
||||
### Step 1: Create Widget File
|
||||
|
||||
@@ -15,8 +15,8 @@ on_error() {
|
||||
echo "✗ An error occurred during: $CURRENT_STEP (line $line_no, exit $exit_code)" >&2
|
||||
if [ -n "${LOG_FILE:-}" ]; then
|
||||
echo "See the log for details: $LOG_FILE" >&2
|
||||
echo "-- Last 50 lines from log --" >&2
|
||||
tail -n 50 "$LOG_FILE" >&2 || true
|
||||
echo "-- Last 100 lines from log --" >&2
|
||||
tail -n 100 "$LOG_FILE" >&2 || true
|
||||
fi
|
||||
echo "\nCommon fixes:" >&2
|
||||
echo "- Ensure the Pi is online (try: ping -c1 8.8.8.8)." >&2
|
||||
@@ -152,6 +152,8 @@ ASSUME_YES=${LEDMATRIX_ASSUME_YES:-0}
|
||||
SKIP_SOUND=${LEDMATRIX_SKIP_SOUND:-0}
|
||||
SKIP_PERF=${LEDMATRIX_SKIP_PERF:-0}
|
||||
SKIP_REBOOT_PROMPT=${LEDMATRIX_SKIP_REBOOT_PROMPT:-0}
|
||||
SKIP_SWAP=${LEDMATRIX_SKIP_SWAP:-0}
|
||||
BUILD_JOBS_OVERRIDE=${LEDMATRIX_BUILD_JOBS:-}
|
||||
|
||||
usage() {
|
||||
cat <<USAGE
|
||||
@@ -163,11 +165,21 @@ Options:
|
||||
--skip-sound Skip sound module configuration
|
||||
--skip-perf Skip performance tweaks (isolcpus/audio)
|
||||
--no-reboot-prompt Do not prompt for reboot at the end
|
||||
--skip-swap Never add temporary swap for the C++ build
|
||||
--build-jobs N Compile the C++ library with N parallel jobs
|
||||
(default: scaled to available RAM)
|
||||
-h, --help Show this help message and exit
|
||||
|
||||
Environment variables (same effect as flags):
|
||||
LEDMATRIX_ASSUME_YES=1, RPI_RGB_FORCE_REBUILD=1, LEDMATRIX_SKIP_SOUND=1,
|
||||
LEDMATRIX_SKIP_PERF=1, LEDMATRIX_SKIP_REBOOT_PROMPT=1
|
||||
LEDMATRIX_SKIP_PERF=1, LEDMATRIX_SKIP_REBOOT_PROMPT=1,
|
||||
LEDMATRIX_SKIP_SWAP=1, LEDMATRIX_BUILD_JOBS=N
|
||||
|
||||
Low-memory devices:
|
||||
On a Pi with under 2GB of RAM the C++ build is limited to fewer parallel
|
||||
jobs and a temporary swapfile is added for the duration of the build, then
|
||||
removed. Without this the compiler is killed by the kernel out-of-memory
|
||||
killer on 512MB and 1GB models.
|
||||
USAGE
|
||||
}
|
||||
|
||||
@@ -178,12 +190,38 @@ while [ $# -gt 0 ]; do
|
||||
--skip-sound) SKIP_SOUND=1 ;;
|
||||
--skip-perf) SKIP_PERF=1 ;;
|
||||
--no-reboot-prompt) SKIP_REBOOT_PROMPT=1 ;;
|
||||
--skip-swap) SKIP_SWAP=1 ;;
|
||||
--build-jobs)
|
||||
shift
|
||||
if [ $# -eq 0 ]; then echo "--build-jobs requires a number"; usage; exit 1; fi
|
||||
BUILD_JOBS_OVERRIDE="$1"
|
||||
;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) echo "Unknown option: $1"; usage; exit 1 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# Low-memory build helpers (job sizing, temporary swap, OOM detection).
|
||||
# Sourced rather than inlined so the sizing logic can be unit-tested; if the
|
||||
# file is missing we fall back to the historical behaviour rather than failing
|
||||
# the install.
|
||||
LOWMEM_LIB="$PROJECT_ROOT_DIR/scripts/install/lib_lowmem.sh"
|
||||
LOWMEM_AVAILABLE=0
|
||||
if [ -f "$LOWMEM_LIB" ]; then
|
||||
# shellcheck source=scripts/install/lib_lowmem.sh
|
||||
. "$LOWMEM_LIB"
|
||||
LOWMEM_AVAILABLE=1
|
||||
else
|
||||
echo "⚠ $LOWMEM_LIB not found; skipping low-memory build protections."
|
||||
lm_remove_build_swap() { return 0; }
|
||||
fi
|
||||
|
||||
# Remove the temporary build swapfile no matter how the script ends. Step 6
|
||||
# tears it down itself; this is the backstop for the error path, since
|
||||
# on_error ends in `exit` and EXIT traps still run.
|
||||
trap 'lm_remove_build_swap' EXIT
|
||||
|
||||
# Helpers
|
||||
retry() {
|
||||
local attempt=1
|
||||
@@ -202,8 +240,33 @@ retry() {
|
||||
done
|
||||
}
|
||||
|
||||
apt_update() { retry apt update; }
|
||||
apt_install() { retry apt install -y "$@"; }
|
||||
# Wait for another apt/dpkg process (commonly unattended-upgrades running
|
||||
# shortly after first boot) to release its lock before we try apt ourselves.
|
||||
# Without this, apt_update/apt_install can fail outright in the first couple
|
||||
# minutes after a fresh Pi OS boot with a generic "Command failed after 3
|
||||
# attempts" error.
|
||||
wait_for_apt_lock() {
|
||||
command -v flock >/dev/null 2>&1 || return 0
|
||||
local lock_file="/var/lib/dpkg/lock-frontend"
|
||||
local max_wait=180
|
||||
local waited=0
|
||||
local printed=0
|
||||
while ! flock -n "$lock_file" -c true 2>/dev/null; do
|
||||
if [ "$printed" -eq 0 ]; then
|
||||
echo "⚠ Waiting for another apt/dpkg process to finish (e.g. unattended-upgrades on first boot)..."
|
||||
printed=1
|
||||
fi
|
||||
if [ "$waited" -ge "$max_wait" ]; then
|
||||
echo "⚠ Still waiting after ${max_wait}s; proceeding anyway."
|
||||
break
|
||||
fi
|
||||
sleep 5
|
||||
waited=$((waited+5))
|
||||
done
|
||||
}
|
||||
|
||||
apt_update() { wait_for_apt_lock; retry apt-get -o DPkg::Lock::Timeout=180 update; }
|
||||
apt_install() { wait_for_apt_lock; retry apt-get -o DPkg::Lock::Timeout=180 install -y "$@"; }
|
||||
apt_remove() { apt-get remove -y "$@" || true; }
|
||||
|
||||
check_network() {
|
||||
@@ -222,15 +285,160 @@ check_network() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
check_disk_space() {
|
||||
command -v df >/dev/null 2>&1 || return 0
|
||||
local available_mb
|
||||
available_mb=$(df -m "$PROJECT_ROOT_DIR" | awk 'NR==2{print $4}')
|
||||
available_mb=${available_mb:-0}
|
||||
if [ "$available_mb" -lt 500 ]; then
|
||||
echo "✗ ERROR: Insufficient disk space: ${available_mb}MB available (need at least 500MB)"
|
||||
echo " Free up space first, e.g.: sudo apt clean && sudo apt autoremove"
|
||||
exit 1
|
||||
elif [ "$available_mb" -lt 1024 ]; then
|
||||
echo "⚠ Limited disk space: ${available_mb}MB available (recommend at least 1GB for the rpi-rgb-led-matrix build in Step 6)"
|
||||
else
|
||||
echo "✓ Disk space sufficient: ${available_mb}MB available"
|
||||
fi
|
||||
}
|
||||
|
||||
# Decide how much memory Step 6's C++ build may use, and say so up front.
|
||||
#
|
||||
# Sets TOTAL_RAM_MB, TOTAL_SWAP_MB, BUILD_JOBS and LOW_RAM for later steps.
|
||||
check_memory() {
|
||||
command -v nproc >/dev/null 2>&1 && CPU_CORES=$(nproc) || CPU_CORES=1
|
||||
|
||||
# Validated up front rather than trusted: a non-numeric value would other-
|
||||
# wise survive as far as an arithmetic test in Step 6 and fail there with a
|
||||
# generic error. This must precede the fallback return below, which also
|
||||
# honours the override.
|
||||
if [ -n "$BUILD_JOBS_OVERRIDE" ]; then
|
||||
if ! echo "$BUILD_JOBS_OVERRIDE" | grep -qE '^[1-9][0-9]*$'; then
|
||||
echo "✗ Invalid build job count: '$BUILD_JOBS_OVERRIDE' (expected a positive integer)"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$LOWMEM_AVAILABLE" != "1" ]; then
|
||||
TOTAL_RAM_MB=0
|
||||
TOTAL_SWAP_MB=0
|
||||
LOW_RAM=0
|
||||
BUILD_JOBS=${BUILD_JOBS_OVERRIDE:-$CPU_CORES}
|
||||
return 0
|
||||
fi
|
||||
|
||||
TOTAL_RAM_MB=$(lm_total_ram_mb)
|
||||
TOTAL_SWAP_MB=$(lm_total_swap_mb)
|
||||
|
||||
# Test hook: exercise the low-memory path on a machine that has plenty.
|
||||
if [ -n "${LEDMATRIX_FORCE_LOW_RAM:-}" ] && [ "${LEDMATRIX_FORCE_LOW_RAM}" != "0" ]; then
|
||||
TOTAL_RAM_MB="${LEDMATRIX_FORCE_LOW_RAM}"
|
||||
echo "⚠ LEDMATRIX_FORCE_LOW_RAM set: pretending this device has ${TOTAL_RAM_MB}MB of RAM"
|
||||
fi
|
||||
|
||||
LOW_RAM=0
|
||||
if [ "$TOTAL_RAM_MB" -gt 0 ] && [ "$TOTAL_RAM_MB" -lt 2048 ]; then
|
||||
LOW_RAM=1
|
||||
fi
|
||||
|
||||
if [ -n "$BUILD_JOBS_OVERRIDE" ]; then
|
||||
BUILD_JOBS="$BUILD_JOBS_OVERRIDE"
|
||||
else
|
||||
BUILD_JOBS=$(lm_build_jobs "$TOTAL_RAM_MB" "$CPU_CORES")
|
||||
fi
|
||||
|
||||
echo "System memory: ${TOTAL_RAM_MB}MB RAM, ${TOTAL_SWAP_MB}MB swap, ${CPU_CORES} core(s)"
|
||||
if [ "$LOW_RAM" = "1" ]; then
|
||||
echo "⚠ Low-memory device detected."
|
||||
echo " The rpi-rgb-led-matrix C++ build in Step 6 will use ${BUILD_JOBS} parallel job(s)"
|
||||
echo " instead of all cores, and a temporary swapfile will be added for the build"
|
||||
echo " and removed afterwards. Without this the compiler is killed by the kernel"
|
||||
echo " out-of-memory killer. Expect Step 6 to take 15-25 minutes."
|
||||
if [ "$SKIP_SWAP" = "1" ]; then
|
||||
echo " Temporary swap is disabled (--skip-swap); the build may still run out of memory."
|
||||
fi
|
||||
else
|
||||
echo "✓ Memory sufficient for the rpi-rgb-led-matrix build (${BUILD_JOBS} parallel job(s))"
|
||||
fi
|
||||
}
|
||||
|
||||
# Compile and install the rgbmatrix Python package.
|
||||
#
|
||||
# CMAKE_BUILD_PARALLEL_LEVEL is the setting that actually caps the compile:
|
||||
# upstream's pyproject.toml declares no [tool.scikit-build] options, so
|
||||
# scikit-build-core drives Ninja through `cmake --build`, which reads this
|
||||
# variable. Ninja's own default is nproc+2, i.e. six concurrent cc1plus
|
||||
# processes on a 4-core Pi. MAKEFLAGS is ignored by Ninja and is set only to
|
||||
# cover the Makefile-generator fallback if ninja-build is somehow absent.
|
||||
#
|
||||
# BUILD_TMPDIR redirects pip's build tree off tmpfs where applicable — see
|
||||
# where it is computed in Step 6.
|
||||
run_rgbmatrix_build() {
|
||||
local jobs="$1" out="$2"
|
||||
local pid elapsed=0
|
||||
|
||||
TMPDIR="${BUILD_TMPDIR:-${TMPDIR:-/tmp}}" \
|
||||
CMAKE_BUILD_PARALLEL_LEVEL="$jobs" \
|
||||
MAKEFLAGS="-j${jobs}" \
|
||||
python3 -m pip install --break-system-packages . > "$out" 2>&1 &
|
||||
pid=$!
|
||||
|
||||
# The build's output is captured to a file, so without a heartbeat a serial
|
||||
# compile on a 1GB Pi looks like a 20-minute hang and invites a Ctrl-C.
|
||||
#
|
||||
# Polled at a short interval but reported every 30s: polling at the report
|
||||
# interval instead would add most of that interval to the wall time of
|
||||
# every build, including fast ones on a Pi 4/5.
|
||||
while kill -0 "$pid" 2>/dev/null; do
|
||||
sleep 2
|
||||
elapsed=$((elapsed + 2))
|
||||
if [ "$((elapsed % 30))" -eq 0 ] && kill -0 "$pid" 2>/dev/null; then
|
||||
printf ' ... still compiling (%dm%02ds elapsed)\n' "$((elapsed / 60))" "$((elapsed % 60))"
|
||||
fi
|
||||
done
|
||||
|
||||
wait "$pid"
|
||||
}
|
||||
|
||||
# Explain a failed rgbmatrix build. The kernel OOM killer writes nothing to the
|
||||
# build's own output, which is why this used to be reported as a missing
|
||||
# build-tools problem and sent users chasing packages they already had.
|
||||
print_rgbmatrix_build_failure() {
|
||||
local out="$1"
|
||||
|
||||
if [ "$LOWMEM_AVAILABLE" = "1" ] && lm_build_failed_on_oom "$out"; then
|
||||
echo "✗ The rpi-rgb-led-matrix build was killed: the system ran out of memory."
|
||||
echo " This is NOT a missing build-tools problem — the C++ compiler ran out of RAM."
|
||||
echo " RAM: ${TOTAL_RAM_MB}MB Swap: $(lm_total_swap_mb)MB Parallel jobs used: ${BUILD_JOBS}"
|
||||
if [ -n "${LM_SWAP_SKIP_REASON:-}" ]; then
|
||||
echo " No temporary swap was added: ${LM_SWAP_SKIP_REASON}"
|
||||
fi
|
||||
echo ""
|
||||
echo " Try one of these, then re-run this script (it resumes at Step 6):"
|
||||
echo " 1. Force a single compile job:"
|
||||
echo " sudo ./first_time_install.sh --build-jobs 1"
|
||||
echo " 2. Add permanent swap, if the temporary swapfile could not be created:"
|
||||
echo " sudo apt install -y dphys-swapfile"
|
||||
echo " sudo sed -i 's/^#\\?CONF_SWAPSIZE=.*/CONF_SWAPSIZE=2048/' /etc/dphys-swapfile"
|
||||
echo " sudo sed -i 's/^#\\?CONF_MAXSWAP=.*/CONF_MAXSWAP=2048/' /etc/dphys-swapfile"
|
||||
echo " sudo dphys-swapfile swapoff && sudo dphys-swapfile setup && sudo dphys-swapfile swapon"
|
||||
echo " 3. Free up disk space so a larger swapfile fits: sudo apt clean"
|
||||
else
|
||||
echo "✗ Failed to install rpi-rgb-led-matrix Python package"
|
||||
echo " Ensure build tools are installed:"
|
||||
echo " sudo apt install -y python-dev-is-python3 cmake build-essential"
|
||||
fi
|
||||
}
|
||||
|
||||
echo ""
|
||||
echo "This script will perform the following steps:"
|
||||
echo "1. Install system dependencies"
|
||||
echo "1. Check prerequisites (network, disk, memory) and install system dependencies"
|
||||
echo "2. Fix cache permissions"
|
||||
echo "3. Fix assets directory permissions"
|
||||
echo "3.1. Fix plugin directory permissions"
|
||||
echo "4. Ensure configuration files exist"
|
||||
echo "5. Install Python project dependencies (requirements.txt)"
|
||||
echo "6. Build and install rpi-rgb-led-matrix and test import"
|
||||
echo " (compiles C++; low-memory Pis get temporary swap and a serial build)"
|
||||
echo "7. Install web interface dependencies"
|
||||
echo "7.5. Install main LED Matrix service"
|
||||
echo "8. Install web interface service"
|
||||
@@ -271,11 +479,19 @@ CURRENT_STEP="Install system dependencies"
|
||||
echo "Step 1: Installing system dependencies..."
|
||||
echo "----------------------------------------"
|
||||
|
||||
# Ensure network is available before APT operations
|
||||
# Pre-flight checks before APT operations
|
||||
check_network
|
||||
check_disk_space
|
||||
check_memory
|
||||
|
||||
# Update package list
|
||||
apt_update
|
||||
# Update package list. The one-shot installer refreshes the lists moments
|
||||
# before invoking this script and exports LEDMATRIX_APT_UPDATED=1, so skip the
|
||||
# duplicate refresh on that path.
|
||||
if [ "${LEDMATRIX_APT_UPDATED:-0}" = "1" ]; then
|
||||
echo "Package lists already refreshed by the one-shot installer; skipping apt update."
|
||||
else
|
||||
apt_update
|
||||
fi
|
||||
|
||||
# Install required system packages
|
||||
echo "Installing Python packages and dependencies..."
|
||||
@@ -605,10 +821,6 @@ if [ ! -f "$PROJECT_ROOT_DIR/config/config_secrets.json" ]; then
|
||||
echo "⚠ Template config/config_secrets.template.json not found; creating a minimal secrets file"
|
||||
cat > "$PROJECT_ROOT_DIR/config/config_secrets.json" <<'EOF'
|
||||
{
|
||||
"youtube": {
|
||||
"api_key": "YOUR_YOUTUBE_API_KEY",
|
||||
"channel_id": "YOUR_YOUTUBE_CHANNEL_ID"
|
||||
},
|
||||
"github": {
|
||||
"api_token": "YOUR_GITHUB_PERSONAL_ACCESS_TOKEN"
|
||||
}
|
||||
@@ -684,7 +896,11 @@ if [ -f "$PROJECT_ROOT_DIR/requirements.txt" ]; then
|
||||
|
||||
if command -v timeout >/dev/null 2>&1; then
|
||||
# Use timeout if available (10 minutes = 600 seconds)
|
||||
if timeout 600 python3 -m pip install --break-system-packages --no-cache-dir --prefer-binary --verbose "$line" > "$INSTALL_OUTPUT" 2>&1; then
|
||||
# --ignore-installed: apt-managed packages (e.g. python3-requests)
|
||||
# ship no pip RECORD file, so upgrading them would otherwise abort
|
||||
# with "uninstall-no-record-file"; this lays the new version down
|
||||
# alongside instead of trying to uninstall the apt copy first.
|
||||
if timeout 600 python3 -m pip install --break-system-packages --no-cache-dir --prefer-binary --ignore-installed --verbose "$line" > "$INSTALL_OUTPUT" 2>&1; then
|
||||
INSTALL_SUCCESS=true
|
||||
else
|
||||
EXIT_CODE=$?
|
||||
@@ -692,7 +908,7 @@ if [ -f "$PROJECT_ROOT_DIR/requirements.txt" ]; then
|
||||
echo "✗ Timeout (10 minutes) installing: $line"
|
||||
echo " This package may require building from source, which can be slow on Raspberry Pi."
|
||||
echo " You can try installing it manually later with:"
|
||||
echo " python3 -m pip install --break-system-packages --no-cache-dir --prefer-binary --verbose '$line'"
|
||||
echo " python3 -m pip install --break-system-packages --no-cache-dir --prefer-binary --ignore-installed --verbose '$line'"
|
||||
else
|
||||
echo "✗ Failed to install: $line (exit code: $EXIT_CODE)"
|
||||
fi
|
||||
@@ -700,7 +916,7 @@ if [ -f "$PROJECT_ROOT_DIR/requirements.txt" ]; then
|
||||
else
|
||||
# No timeout command available, install without timeout
|
||||
echo " Note: timeout command not available, installation may take a while..."
|
||||
if python3 -m pip install --break-system-packages --no-cache-dir --prefer-binary --verbose "$line" > "$INSTALL_OUTPUT" 2>&1; then
|
||||
if python3 -m pip install --break-system-packages --no-cache-dir --prefer-binary --ignore-installed --verbose "$line" > "$INSTALL_OUTPUT" 2>&1; then
|
||||
INSTALL_SUCCESS=true
|
||||
else
|
||||
EXIT_CODE=$?
|
||||
@@ -752,7 +968,7 @@ if [ -f "$PROJECT_ROOT_DIR/requirements.txt" ]; then
|
||||
echo " 1. Ensure you have enough disk space: df -h"
|
||||
echo " 2. Check available memory: free -h"
|
||||
echo " 3. Try installing failed packages individually with verbose output:"
|
||||
echo " python3 -m pip install --break-system-packages --no-cache-dir --prefer-binary --verbose <package>"
|
||||
echo " python3 -m pip install --break-system-packages --no-cache-dir --prefer-binary --ignore-installed --verbose <package>"
|
||||
echo " 4. For packages that build from source (like numpy), consider:"
|
||||
echo " - Installing pre-built wheels: python3 -m pip install --only-binary :all: <package>"
|
||||
echo " - Or installing via apt if available: sudo apt install python3-<package>"
|
||||
@@ -774,7 +990,10 @@ echo ""
|
||||
# Install web interface dependencies
|
||||
echo "Installing web interface dependencies..."
|
||||
if [ -f "$PROJECT_ROOT_DIR/web_interface/requirements.txt" ]; then
|
||||
if python3 -m pip install --break-system-packages --prefer-binary -r "$PROJECT_ROOT_DIR/web_interface/requirements.txt"; then
|
||||
# --ignore-installed: apt-managed packages (e.g. python3-requests) ship no
|
||||
# pip RECORD file, so upgrading them to the version pinned here would
|
||||
# otherwise abort the whole install with "uninstall-no-record-file".
|
||||
if python3 -m pip install --break-system-packages --prefer-binary --ignore-installed -r "$PROJECT_ROOT_DIR/web_interface/requirements.txt"; then
|
||||
echo "✓ Web interface dependencies installed"
|
||||
# Create marker file to indicate dependencies are installed
|
||||
touch "$PROJECT_ROOT_DIR/.web_deps_installed"
|
||||
@@ -815,6 +1034,12 @@ if [ "$_SKIP_BUILD" = "1" ]; then
|
||||
echo "rgbmatrix already installed${_skip_suffix}; skipping build (set RPI_RGB_FORCE_REBUILD=1 to force rebuild)."
|
||||
else
|
||||
# Ensure rpi-rgb-led-matrix submodule is initialized
|
||||
# Wrapper used with retry(): removes any partial clone dir before each attempt
|
||||
# so git clone doesn't fail with "destination path already exists".
|
||||
_clone_rpi_rgb() {
|
||||
rm -rf "$PROJECT_ROOT_DIR/rpi-rgb-led-matrix-master"
|
||||
git clone https://github.com/hzeller/rpi-rgb-led-matrix.git rpi-rgb-led-matrix-master
|
||||
}
|
||||
if [ ! -d "$PROJECT_ROOT_DIR/rpi-rgb-led-matrix-master" ]; then
|
||||
echo "rpi-rgb-led-matrix-master not found. Initializing git submodule..."
|
||||
cd "$PROJECT_ROOT_DIR"
|
||||
@@ -822,14 +1047,14 @@ else
|
||||
# Try to initialize submodule if .gitmodules exists
|
||||
if [ -f "$PROJECT_ROOT_DIR/.gitmodules" ] && grep -q "rpi-rgb-led-matrix" "$PROJECT_ROOT_DIR/.gitmodules"; then
|
||||
echo "Initializing rpi-rgb-led-matrix submodule..."
|
||||
if ! git submodule update --init --recursive rpi-rgb-led-matrix-master 2>&1; then
|
||||
if ! retry git submodule update --init --recursive rpi-rgb-led-matrix-master; then
|
||||
echo "⚠ Submodule init failed, cloning directly from GitHub..."
|
||||
git clone https://github.com/hzeller/rpi-rgb-led-matrix.git rpi-rgb-led-matrix-master
|
||||
retry _clone_rpi_rgb
|
||||
fi
|
||||
else
|
||||
# Fallback: clone directly if submodule not configured
|
||||
echo "Submodule not configured, cloning directly from GitHub..."
|
||||
git clone https://github.com/hzeller/rpi-rgb-led-matrix.git rpi-rgb-led-matrix-master
|
||||
retry _clone_rpi_rgb
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -841,24 +1066,72 @@ else
|
||||
cd "$PROJECT_ROOT_DIR"
|
||||
rm -rf rpi-rgb-led-matrix-master
|
||||
if [ -f "$PROJECT_ROOT_DIR/.gitmodules" ] && grep -q "rpi-rgb-led-matrix" "$PROJECT_ROOT_DIR/.gitmodules"; then
|
||||
git submodule update --init --recursive rpi-rgb-led-matrix-master
|
||||
retry git submodule update --init --recursive rpi-rgb-led-matrix-master
|
||||
else
|
||||
git clone https://github.com/hzeller/rpi-rgb-led-matrix.git rpi-rgb-led-matrix-master
|
||||
retry _clone_rpi_rgb
|
||||
fi
|
||||
fi
|
||||
|
||||
# Add temporary swap on low-memory devices so the compiler survives.
|
||||
CURRENT_STEP="Prepare the low-memory build environment"
|
||||
if [ "$LOWMEM_AVAILABLE" = "1" ] && [ "$SKIP_SWAP" != "1" ]; then
|
||||
lm_ensure_build_swap "$(lm_swap_needed_mb "$TOTAL_RAM_MB" "$TOTAL_SWAP_MB")"
|
||||
elif [ "$SKIP_SWAP" = "1" ]; then
|
||||
LM_SWAP_SKIP_REASON="disabled with --skip-swap"
|
||||
fi
|
||||
|
||||
# pip builds in $TMPDIR. Debian 13 mounts /tmp as tmpfs, so the default
|
||||
# would hold the entire C++ build tree in RAM — competing with the very
|
||||
# compiler we are trying to keep under the memory limit.
|
||||
BUILD_TMPDIR=""
|
||||
if [ "$LOWMEM_AVAILABLE" = "1" ]; then
|
||||
_disk_tmp=$(lm_disk_backed_tmpdir)
|
||||
if [ -n "$_disk_tmp" ]; then
|
||||
BUILD_TMPDIR="$_disk_tmp/ledmatrix-build"
|
||||
# If this fails (a nearly-full disk being the likely cause on
|
||||
# exactly the devices this targets), fall back to the default
|
||||
# rather than pointing the build at a path that does not exist.
|
||||
if mkdir -p "$BUILD_TMPDIR" 2>/dev/null; then
|
||||
echo "Building in $BUILD_TMPDIR (TMPDIR is memory-backed; keeping the build tree on disk)"
|
||||
else
|
||||
echo "⚠ Could not create $BUILD_TMPDIR; falling back to the default TMPDIR"
|
||||
BUILD_TMPDIR=""
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
CURRENT_STEP="Build and install rpi-rgb-led-matrix"
|
||||
pushd "$PROJECT_ROOT_DIR/rpi-rgb-led-matrix-master" >/dev/null
|
||||
echo "Installing rpi-rgb-led-matrix Python package (scikit-build-core + cmake)..."
|
||||
echo " Build deps required: python-dev-is-python3 cmake"
|
||||
echo " This compiles C++ — may take 2-5 minutes on Pi 4/5..."
|
||||
if ! python3 -m pip install --break-system-packages .; then
|
||||
echo "✗ Failed to install rpi-rgb-led-matrix Python package"
|
||||
echo " Ensure build tools are installed:"
|
||||
echo " sudo apt install -y python-dev-is-python3 cmake build-essential"
|
||||
echo " Compiling C++ with ${BUILD_JOBS} parallel job(s)..."
|
||||
if [ "$BUILD_JOBS" -le 1 ]; then
|
||||
echo " Deliberately serial to stay within this device's memory — expect 15-25 minutes."
|
||||
else
|
||||
echo " This may take 2-5 minutes on a Pi 4/5..."
|
||||
fi
|
||||
BUILD_OUTPUT=$(mktemp)
|
||||
BUILD_SUCCESS=false
|
||||
if run_rgbmatrix_build "$BUILD_JOBS" "$BUILD_OUTPUT"; then
|
||||
BUILD_SUCCESS=true
|
||||
fi
|
||||
cat "$BUILD_OUTPUT" >> "$LOG_FILE"
|
||||
if [ "$BUILD_SUCCESS" != true ]; then
|
||||
print_rgbmatrix_build_failure "$BUILD_OUTPUT"
|
||||
echo ""
|
||||
echo "-- Last 50 lines of build output --"
|
||||
tail -n 50 "$BUILD_OUTPUT"
|
||||
rm -f "$BUILD_OUTPUT"
|
||||
if [ -n "$BUILD_TMPDIR" ]; then rm -rf "$BUILD_TMPDIR"; fi
|
||||
popd >/dev/null
|
||||
lm_remove_build_swap
|
||||
exit 1
|
||||
fi
|
||||
rm -f "$BUILD_OUTPUT"
|
||||
if [ -n "$BUILD_TMPDIR" ]; then rm -rf "$BUILD_TMPDIR"; fi
|
||||
popd >/dev/null
|
||||
# Hand the memory back well before Step 14's reboot.
|
||||
lm_remove_build_swap
|
||||
else
|
||||
echo "✗ rpi-rgb-led-matrix-master directory not found at $PROJECT_ROOT_DIR"
|
||||
echo "Failed to initialize submodule or clone repository"
|
||||
@@ -912,14 +1185,11 @@ else
|
||||
# Try to install dependencies using the smart installer if available
|
||||
if [ -f "$PROJECT_ROOT_DIR/scripts/install_dependencies_apt.py" ]; then
|
||||
echo "Using smart dependency installer..."
|
||||
python3 "$PROJECT_ROOT_DIR/scripts/install_dependencies_apt.py"
|
||||
# -u: unbuffered stdout/stderr so output is captured in $LOG_FILE in
|
||||
# real time and in order relative to this script's own echo statements
|
||||
python3 -u "$PROJECT_ROOT_DIR/scripts/install_dependencies_apt.py"
|
||||
else
|
||||
echo "Using pip to install dependencies..."
|
||||
if [ -f "$PROJECT_ROOT_DIR/requirements_web_v2.txt" ]; then
|
||||
python3 -m pip install --break-system-packages --prefer-binary -r requirements_web_v2.txt
|
||||
else
|
||||
echo "⚠ requirements_web_v2.txt not found; skipping web dependency install"
|
||||
fi
|
||||
echo "Web dependencies already installed from web_interface/requirements.txt in Step 5"
|
||||
fi
|
||||
|
||||
# Create marker file to indicate dependencies are installed
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Test/dev-only dependencies (not needed on a running display).
|
||||
# Install alongside requirements.txt: pip install -r requirements.txt -r requirements-test.txt
|
||||
pytest>=9.0.3,<10.0.0
|
||||
pytest-cov>=4.1.0,<5.0.0
|
||||
pytest-mock>=3.11.0,<4.0.0
|
||||
freezegun>=1.2,<2 # deterministic time for golden-image tests
|
||||
mypy>=1.5.0,<2.0.0 # static type checking (also pinned in .pre-commit-config.yaml)
|
||||