Compare commits

..
Author SHA1 Message Date
ChuckBuildsandClaude 105c6df019 Fix IndexError in find_blank_cut when the cut lands on the image edge
A cut position after the last column is legitimate — _crop_to_budget asks for
min(start + budget, img.width), which equals the width whenever the remaining
strip is shorter than the budget. find_blank_cut clamped target to width but
then walked leftwards starting at target itself, so ink[width] raised
IndexError.

Caught on hardware: it killed the ledmatrix-stocks fetch, and because
_fetch_plugin_content catches broadly that surfaced as the plugin silently
contributing nothing for the cycle.

Only reachable on the second or later pass of the rotating window over a single
oversized image, which is why the existing tests missed it — they all exercised
the first pass, where start is 0 and start + budget is comfortably inside the
image. Added TestRotationAcrossMultipleCycles, which walks the window round
several times and asserts content is never lost, plus direct coverage of
find_blank_cut at and beyond the image edge.

Both bounds now stop at width - 1 so neither direction can index past the end.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ
2026-07-29 09:42:51 -04:00
ChuckBuildsandClaude 62919a13e3 Vegas mode: end cycles before the wrap, keep the width budget honest
Three fixes, the first a regression from lead_in_width defaulting to 0.

get_visible_portion wraps: once scroll_position + display_width passes the end
of the strip it fills the right of the frame from the *head* of the same strip.
So the final display_width of travel showed the cycle's first plugin re-entering
on the right while its last plugin exited on the left, and the recompose that
followed replaced both at once. On a 512px panel at 50px/s that was 10.2s of
two plugins on screen at once, ending in a hard cut — reported as the ticker
"switching mid-scroll" from F1 to news.

That used to be invisible because the strip began with a full display_width of
blank, so the wrapped-in region was black. Removing that blank (it was 10s of
dead panel per cycle) exposed the wrap. Cycles now end one display width
earlier, before any wrapped content appears, clamped for strips no wider than
the display so they don't complete instantly and spin the recompose loop.

Verified on hardware: a 3936px strip now completes at 68.5s, exactly
(3936 - 512) / 50.

Second, auto_trim=False also skipped the width budget, which is an unrelated
concern — turning off margin cropping should not let one plugin hold the panel
for minutes. Seen in the field: the F1 scoreboard contributed 116 images and
14,848px untouched, giving a 33,821px cycle (11 minutes of content). The budget
now applies regardless of trimming; with it restored that cycle is 6,362px.

Third, the budget accounted for row gaps using the flat intra_plugin_gap while
the compositor had moved to measured separation, so it under-counted by up to
(min_content_separation - intra_plugin_gap) per row and a many-row plugin
overran its cap. Both now use the same separation_gap() rule, and a test
asserts the composed block fits the budget end to end rather than trusting the
two paths to agree.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ
2026-07-29 09:35:23 -04:00
ChuckBuildsandClaude 616d21c6d3 Vegas mode: render plugins narrower, space rows by measured separation
Trimming reclaims blank margins but cannot compact a layout that genuinely
spans the display — a five-column forecast, a progress bar drawn at 100%
width, a stat block with the panel's whole width between its elements. Those
need the plugin to make different layout decisions, which means telling it the
screen is narrower while it renders.

DisplayManager.render_size() presents a smaller logical canvas for the
duration of a Vegas content fetch, reusing the same _LogicalMatrix
indirection double-sided mode already relies on so plugins see a consistent
size from every accessor. Plugins that size themselves from matrix.width need
no changes at all; one that wants to be explicit can read the new
BasePlugin.get_vegas_render_width().

Width is a percentage so a single setting travels across panel sizes:
vegas_scroll.render_width_pct globally, or vegas_width_pct in an individual
plugin's config. Measured on a 512x64 panel with real data:

  ledmatrix-weather   1536px -> 576px   (forecast becomes narrow cards)
  youtube-stats        353px -> 199px   (2% blank left, so genuinely compact)
  geochron             453px -> 153px   (ink density rises to 100%)
  ledmatrix-flights    950px -> 740px

The youtube-stats figure is the clearest evidence the layout itself changed
rather than being cropped: at full width the content had to be trimmed from
512px to 353px, whereas at 40% it arrives with almost no blank to reclaim.

Row spacing is now measured rather than added. A flat gap gets it wrong in
both directions at once — content drawn flush to its own edges ends up nearly
touching (reported for recent sports scores, which sat 8px apart), while
content already carrying wide margins gets pushed even further out.
separation_gap() measures the blank each pair already has and adds only the
shortfall, up to min_content_separation (default 24). intra_plugin_gap stays
as a floor applied regardless.

Two tests shipped in the previous commit encoded the old flat-gap arithmetic
and are updated to the measured semantics, including one renamed to reflect
that zero intra_plugin_gap alone no longer butts rows together.

Also fixes a real bug found while testing: the harness display manager had no
render_size(), and because the adapter catches broadly that surfaced as "no
content" rather than an error, silently dropping five plugins. Added the
context to VisualTestDisplayManager for parity, and _render_at() now degrades
to a no-op on any display manager lacking it, so a third-party or older
harness loses the narrowing rather than the content.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ
2026-07-29 09:01:28 -04:00
ChuckBuildsandClaude d69dfbbaee Align Vegas API bounds with validate(), fix audit config plumbing
Both from review feedback on #423.

The web API's accepted ranges disagreed with VegasModeConfig.validate(),
which is what actually gates Vegas starting:

  scroll_speed      1-100  -> 1-200   (a slider value of 150 returned 400)
  separator_width   0-500  -> 0-128
  target_fps        1-200  -> 30-200
  buffer_ahead      1-20   -> 1-5

The three loose ones were the dangerous direction: the value saved with a
200, then VegasModeCoordinator.start() failed validation with only a log
line, so the ticker silently never ran. The UI already matched validate() in
all four cases, so the API was the odd one out.

test_vegas_api_bounds_match_validate parses the numeric_fields map out of
api_v3 and asserts every bound against validate(), plus that validate()
accepts both endpoints and rejects just outside them, so these cannot drift
apart again. That test immediately caught a missing upper bound on
min_plugin_width, now added — unbounded it would drop every segment and
leave a blank ticker.

Separately, vegas_audit.py constructed PluginAdapter without the config, so
it fell back to VegasModeConfig() defaults and would report trimming and
width-budget behaviour that differed from the user's config.json. It now
passes the loaded config exactly as the coordinator does. This is the same
class of drift the explicit lead_gap and grouping arguments already guard
against. Output is unchanged on a rig whose config matches the defaults.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ
2026-07-28 20:32:09 -04:00
ChuckBuildsandClaude ec96422803 Drop unused Optional import from the vegas audit script
Flagged by Codacy (F401). Any, Dict and List are all still used.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ
2026-07-28 20:26:22 -04:00
ChuckBuildsandClaude 8d57a748a7 Vegas mode: reclaim dead space and pace the rotation
On a wide panel Vegas mode spent much of its time showing black. At 50px/s
on a 512px display, one display width of blank is 10.2 seconds, which makes
several long-standing behaviours expensive:

- ScrollHelper prepended a full display width of black as an "initial gap",
  charged once per cycle — 10.2s of black at the start of every rotation.
- Plugins without get_vegas_content() are captured off a full-display canvas,
  so their blank margins entered the ticker too. Measured: of-the-day drew
  35px of "No Data" on a 512px canvas (92% blank), youtube-stats 142px of
  content with 185px of black either side. Only the scroll_helper path had
  any trimming.
- Cycle transitions deliberately pushed a blank frame and then recomposed
  synchronously: 84ms at best, 4.8s at worst, every millisecond of it black.
- buffer_ahead doubled as the cycle size, so a 21-plugin install showed 3
  plugins per cycle and took ~7 cycles to come around.
- separator_width was applied between every image rather than at plugin
  boundaries, so a per-row ticker like the F1 scoreboard (116 images, which
  it renders 4px apart internally) got a 32px chasm between each row — and
  the width budget didn't count those gaps, so the plugin quietly occupied
  far more of the panel than intended.

Changes:

- src/vegas_mode/geometry.py: numpy column-ink primitives shared by the
  trimmer and the audit tool, so the number reported is the number acted on.
  A Python per-column loop over a 17,000px strip is far too slow for the
  render path.
- PluginAdapter trims every content path, not just scroll_helper. Only outer
  edges are cropped: interior blank columns are the plugin's own layout
  (logo left, score right) and closing them would corrupt the design. A
  plugin on a non-black background is inherently unaffected.
- ScrollHelper.create_scrolling_image takes an explicit lead_gap, still
  defaulting to display_width so the many standalone-ticker callers are
  unchanged. Vegas passes lead_in_width (default 0).
- Cycle end holds the last rendered frame instead of blanking, turning the
  recompose into a brief freeze rather than the panel switching off.
- plugins_per_cycle (default 6) is split from buffer_ahead, which goes back
  to being only a prefetch low-water mark.
- max_plugin_width_ratio (default 3x display width) caps one plugin's share
  of a cycle. Overflow is deferred, not discarded: a rotation offset advances
  each fetch so later rows appear on subsequent cycles. Single oversized
  images are cropped at a blank column so the cut misses glyphs.
- Composition groups images by plugin: rows are joined by intra_plugin_gap
  (default 8) and separator_width applies only between plugins. The width
  budget now counts those gaps.
- Plugin data updates no longer run on the Vegas render path.

All new settings are user-configurable in Display -> Vegas Scroll, including
min/max cycle duration and dynamic duration, which previously existed in code
but were reachable only by hand-editing config.json.

Measured with scripts/dev/vegas_audit.py on a 512x64 panel:

  mean ink coverage    42.7% -> 69.4%
  fully blank           5.9% -> 0%
  reads as empty        13.6% -> 0%
  worst blank stretch    4.8s -> 0s
  full rotation          414s -> 123s
  plugins per cycle         3 -> 6

Note the metric choice: a "fully blank" scan (>=95% black viewport) reported
only 0.4% and badly understated the problem, because two full-width segments
with mid-canvas content never fully blank the viewport — they hold it at ~28%.
window_coverage_stats grades every viewport position by how much ink it
carries, which is what tracks perceived dead time.

Known remaining: cycle transitions still freeze ~3.5s while the next cycle is
fetched. Fixing that needs background prefetch, which is deferred because the
fallback-capture path mutates the shared display_manager.image and racing it
against the render loop risks torn frames.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ
2026-07-28 20:18:51 -04:00
213 changed files with 6416 additions and 20526 deletions
+145
View File
@@ -0,0 +1,145 @@
# 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/`
+247
View File
@@ -0,0 +1,247 @@
# 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
+156
View File
@@ -0,0 +1,156 @@
# 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
@@ -0,0 +1,44 @@
{
"$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
}
@@ -0,0 +1,226 @@
"""
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()
@@ -0,0 +1,55 @@
{
"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": ""
}
@@ -0,0 +1,13 @@
# 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
@@ -0,0 +1,136 @@
"""
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()
+751
View File
@@ -0,0 +1,751 @@
# 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
+38
View File
@@ -0,0 +1,38 @@
---
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
@@ -0,0 +1,42 @@
---
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
+50
View File
@@ -0,0 +1,50 @@
---
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
+51
View File
@@ -0,0 +1,51 @@
---
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**
+213
View File
@@ -0,0 +1,213 @@
---
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
+23
View File
@@ -0,0 +1,23 @@
---
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
@@ -0,0 +1,41 @@
---
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
+42
View File
@@ -0,0 +1,42 @@
---
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
+51
View File
@@ -0,0 +1,51 @@
---
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
View File
@@ -0,0 +1 @@
# Add directories or file patterns to ignore during indexing (e.g. foo/ or *.csv)
+364
View File
@@ -0,0 +1,364 @@
# 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`
@@ -1,40 +0,0 @@
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 }}
+5 -47
View File
@@ -4,24 +4,11 @@ on:
pull_request: pull_request:
push: push:
branches: [main] branches: [main]
# Manual runs against any branch — useful when a PR's automatic run
# needs a re-run or didn't get created.
workflow_dispatch:
# Both jobs only check out the repo and run pytest.
permissions:
contents: read
jobs: jobs:
plugin-safety: plugin-safety:
name: Plugin safety harness + unit tests name: Plugin safety harness + unit tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
# The bundled fixture plugin gives the harness at least one real plugin
# to render, and REQUIRE_PLUGINS turns "discovered zero plugins" into a
# hard failure instead of a silent all-skip green run.
LEDMATRIX_PLUGINS_DIR: test/fixtures/plugins
LEDMATRIX_REQUIRE_PLUGINS: "1"
steps: steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with: with:
@@ -38,38 +25,9 @@ jobs:
pip install -r requirements.txt -r requirements-test.txt pip install -r requirements.txt -r requirements-test.txt
pip install RGBMatrixEmulator pip install RGBMatrixEmulator
- name: Run plugin safety harness - name: Run harness + visual rendering tests
run: | run: |
pytest --no-cov test/plugins/ pytest --no-cov \
test/plugins/test_harness.py \
unit-tests: test/plugins/test_visual_rendering.py \
name: Core unit tests test/plugins/test_plugin_matrix.py
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
# Run the ENTIRE test tree (except test/plugins, which the
# plugin-safety job owns). New test files are enrolled automatically;
# excluding anything requires a visible, commented --ignore here.
# Coverage is measured and enforced only in this step — pytest.ini
# deliberately carries no coverage flags so local runs stay fast.
- name: Run core unit suites
run: |
pytest -m "not hardware" test/ \
--ignore=test/plugins \
--cov=src --cov=web_interface \
--cov-report=term \
--cov-fail-under=48
-176
View File
@@ -1,176 +0,0 @@
# 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).
+4 -21
View File
@@ -6,16 +6,12 @@
- `config/config.json` — User plugin configuration (persists across plugin reinstalls) - `config/config.json` — User plugin configuration (persists across plugin reinstalls)
- `plugin-repos/`**Default** plugin install directory used by the - `plugin-repos/`**Default** plugin install directory used by the
Plugin Store, set by `plugin_system.plugins_directory` in Plugin Store, set by `plugin_system.plugins_directory` in
`config.json` (default per `config/config.template.json:167`). `config.json` (default per `config/config.template.json:130`).
Not gitignored. Not gitignored.
- `plugins/` — Legacy/dev plugin location. Gitignored (`plugins/*`). - `plugins/` — Legacy/dev plugin location. Gitignored (`plugins/*`).
Used by `scripts/dev/dev_plugin_setup.sh` for symlinks. The plugin Used by `scripts/dev/dev_plugin_setup.sh` for symlinks. The plugin
loader does NOT fall back to it `PluginManager.discover_plugins()` loader falls back to it when something isn't found in `plugin-repos/`
(`src/plugin_system/plugin_manager.py`) scans only the configured (`src/plugin_system/schema_manager.py:77`).
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 ## Plugin System
- Plugins inherit from `BasePlugin` in `src/plugin_system/base_plugin.py` - Plugins inherit from `BasePlugin` in `src/plugin_system/base_plugin.py`
@@ -24,16 +20,6 @@
- Plugin instantiation args: `plugin_id, config, display_manager, cache_manager, plugin_manager` - Plugin instantiation args: `plugin_id, config, display_manager, cache_manager, plugin_manager`
- Config schemas use JSON Schema Draft-7 - Config schemas use JSON Schema Draft-7
- Display dimensions: always read dynamically from `self.display_manager.matrix.width/height` - 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 ## Plugin Store Architecture
- Official plugins live in the `ledmatrix-plugins` monorepo (not individual repos) - Official plugins live in the `ledmatrix-plugins` monorepo (not individual repos)
@@ -47,7 +33,7 @@
## Skin System (visual overlays for sports scoreboards) ## 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 - 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` - Core: `src/skin_system/` (ScoreboardSkin, SkinContext, runtime); hook: `SportsCore._render_game()` in `src/base_classes/sports.py`
- Skins render onto `ctx.canvas` only; fallback to built-in renderer on `False`/exception (3 strikes disables for session) - 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 - 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` - Validate skins headlessly: `python scripts/validate_skin.py --skin <id>`; docs: `docs/SKIN_SYSTEM.md`, `docs/CREATING_SKINS.md`
@@ -56,7 +42,4 @@
## Common Pitfalls ## Common Pitfalls
- paho-mqtt 2.x needs `callback_api_version=mqtt.CallbackAPIVersion.VERSION1` for v1 compat - 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()` - 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 - 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
+4 -8
View File
@@ -40,7 +40,7 @@ improvements, and code changes.
## Running the tests ## Running the tests
```bash ```bash
pip install -r requirements.txt -r requirements-test.txt pip install -r requirements.txt
pytest pytest
``` ```
@@ -57,13 +57,9 @@ integration tests.
`docs/<short-description>`. `docs/<short-description>`.
3. **Keep PRs focused.** One conceptual change per PR. If you find 3. **Keep PRs focused.** One conceptual change per PR. If you find
adjacent bugs while working, fix them in a separate PR. adjacent bugs while working, fix them in a separate PR.
4. **Follow the existing code style.** The pre-commit hooks run 4. **Follow the existing code style.** Python code uses standard
`flake8` (E9, F63, F7, F82 plus bugbear `B` checks), `mypy` on `black`/`ruff` conventions; HTML/JS in `web_interface/` follows the
`src/`, `bandit`, and `gitleaks` — install the CLI with patterns already in `templates/v3/` and `static/v3/`.
`python -m pip install pre-commit`, then run
`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 5. **Update documentation** alongside code changes. If you add a
config key, document it in the relevant `*.md` file (or, for config key, document it in the relevant `*.md` file (or, for
plugins, in `config_schema.json` so the form is auto-generated). plugins, in `config_schema.json` so the form is auto-generated).
+10 -24
View File
@@ -50,15 +50,7 @@ I'm trying to be open to constructive criticism and support, as long as it's a r
<details> <details>
<summary>Core Features</summary> <summary>Core Features</summary>
LEDMatrix is a plugin platform: the displays below are plugins installed 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:
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 ### Time and Weather
- Real-time clock display (2x 64x32 Displays 4mm Pixel Pitch) - Real-time clock display (2x 64x32 Displays 4mm Pixel Pitch)
@@ -149,7 +141,6 @@ The system supports live, recent, and upcoming game information for multiple spo
sudo RPI_RGB_FORCE_REBUILD=1 ./first_time_install.sh 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`. - 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 ### RGB Matrix Bonnet / HAT
@@ -323,12 +314,12 @@ curl -fsSL https://raw.githubusercontent.com/ChuckBuilds/LEDMatrix/main/scripts/
``` ```
This one-shot installer will automatically: This one-shot installer will automatically:
- Check system prerequisites (network, disk space, memory, sudo access) - Check system prerequisites (network, disk space, sudo access)
- Install required system packages (git, python3, build tools, etc.) - Install required system packages (git, python3, build tools, etc.)
- Clone or update the LEDMatrix repository - Clone or update the LEDMatrix repository
- Run the complete first-time installation script - Run the complete first-time installation script
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. The installation process typically takes 10-30 minutes depending on your internet connection and Pi model. All errors are reported explicitly with actionable fixes.
**Note:** The script is safe to run multiple times and will handle existing installations gracefully. **Note:** The script is safe to run multiple times and will handle existing installations gracefully.
@@ -365,12 +356,6 @@ sudo bash ./first_time_install.sh
This single script installs services, dependencies, configures permissions and sudoers, and validates the setup. This single script installs services, dependencies, configures permissions and sudoers, and validates the setup.
It finishes by asking whether to reboot. If you run it non-interactively — piped, over a script, or with `-y` — there is no one to ask, so **it reboots immediately without prompting**. Pass `--no-reboot-prompt` to install without rebooting:
```bash
sudo bash ./first_time_install.sh -y --no-reboot-prompt
```
</details> </details>
</details> </details>
@@ -386,10 +371,6 @@ sudo bash ./first_time_install.sh -y --no-reboot-prompt
### Initial Setup ### 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: 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 . Edit the project via the web interface at http://[IP ADDRESS or HOSTNAME]:5000 or http://ledpi:5000 .
@@ -435,7 +416,7 @@ I recommend using the web-ui "Quick Actions" to control the Display.
## Plugins ## Plugins
<details> <details>
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. 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.
### Plugin Store ### Plugin Store
See the [Plugin Store documentation](https://github.com/ChuckBuilds/ledmatrix-plugins) for detailed installation instructions. See the [Plugin Store documentation](https://github.com/ChuckBuilds/ledmatrix-plugins) for detailed installation instructions.
@@ -628,7 +609,12 @@ These settings control runtime behavior and GPIO timing:
### Display Durations (`display.display_durations`) ### Display Durations (`display.display_durations`)
Controls how long each installed plugin stays visible in seconds before switching to the next one, keyed by plugin id. 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
- **Plugin-specific durations** - **Plugin-specific durations**
- Each plugin can have its own duration setting - Each plugin can have its own duration setting
-22
View File
@@ -1,22 +0,0 @@
# 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.
+3 -16
View File
@@ -88,7 +88,6 @@
} }
}, },
"timezone": "America/New_York", "timezone": "America/New_York",
"target_fps": 100,
"location": { "location": {
"city": "Tampa", "city": "Tampa",
"state": "Florida", "state": "Florida",
@@ -110,11 +109,7 @@
"inverse_colors": false, "inverse_colors": false,
"show_refresh_rate": false, "show_refresh_rate": false,
"led_rgb_sequence": "RGB", "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": { "runtime": {
"gpio_slowdown": 3, "gpio_slowdown": 3,
@@ -139,10 +134,6 @@
"intra_plugin_gap": 8, "intra_plugin_gap": 8,
"render_width_pct": 100, "render_width_pct": 100,
"min_content_separation": 24, "min_content_separation": 24,
"min_cut_gap": 6,
"continuous_scroll": true,
"smooth_scroll": true,
"extend_threshold_screens": 2.0,
"auto_trim": true, "auto_trim": true,
"trim_threshold": 10, "trim_threshold": 10,
"content_padding": 8, "content_padding": 8,
@@ -150,12 +141,9 @@
"lead_in_width": 0, "lead_in_width": 0,
"plugins_per_cycle": 6, "plugins_per_cycle": 6,
"max_plugin_width_ratio": 3.0, "max_plugin_width_ratio": 3.0,
"overflow_mode": "rotate",
"dynamic_duration_enabled": true, "dynamic_duration_enabled": true,
"min_cycle_duration": 60, "min_cycle_duration": 60,
"max_cycle_duration": 240, "max_cycle_duration": 240
"frame_based_scrolling": true,
"scroll_delay": 0.02
} }
}, },
"sync": { "sync": {
@@ -166,8 +154,7 @@
"plugin_system": { "plugin_system": {
"plugins_directory": "plugin-repos", "plugins_directory": "plugin-repos",
"auto_discover": true, "auto_discover": true,
"auto_load_enabled": true, "auto_load_enabled": true
"development_mode": false
}, },
"web-ui-info": { "web-ui-info": {
"enabled": true, "enabled": true,
+4
View File
@@ -1,4 +1,8 @@
{ {
"youtube": {
"api_key": "YOUR_YOUTUBE_API_KEY",
"channel_id": "YOUR_YOUTUBE_CHANNEL_ID"
},
"github": { "github": {
"api_token": "YOUR_GITHUB_PERSONAL_ACCESS_TOKEN" "api_token": "YOUR_GITHUB_PERSONAL_ACCESS_TOKEN"
} }
+27 -48
View File
@@ -47,11 +47,6 @@ 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:** **Configuration Options:**
| Setting | Default | Description | | Setting | Default | Description |
@@ -62,11 +57,7 @@ JSON is optional.
| `plugin_order` | `[]` | Plugin display order (empty = auto) | | `plugin_order` | `[]` | Plugin display order (empty = auto) |
| `excluded_plugins` | `[]` | Plugins to exclude from Vegas mode | | `excluded_plugins` | `[]` | Plugins to exclude from Vegas mode |
| `target_fps` | `125` | Target frame rate | | `target_fps` | `125` | Target frame rate |
| `buffer_ahead` | `2` | Number of plugins buffered ahead | | `buffer_ahead` | `2` | Number of panels to render 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 ### Per-Plugin Configuration
@@ -88,13 +79,9 @@ Override Vegas behavior for specific plugins:
| Setting | Values | Description | | Setting | Values | Description |
|---------|--------|-------------| |---------|--------|-------------|
| `vegas_mode` | `scroll`, `fixed`, `static` | Display mode for this plugin | | `vegas_mode` | `scroll`, `fixed`, `static` | Display mode for this plugin |
| `vegas_panel_count` | any positive integer | Width in panels (1 panel = display width) | | `vegas_panel_count` | `1-10` | Width in panels (1 panel = display width) |
| `display_duration` | seconds | Pause duration for STATIC mode | | `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) ### Plugin Integration (Developer Guide)
**1. Implement Content Method:** **1. Implement Content Method:**
@@ -464,7 +451,7 @@ time when something is active.
### REST API Reference ### REST API Reference
The API is mounted at `/api/v3` (`web_interface/app.py:199`). The API is mounted at `/api/v3` (`web_interface/app.py:144`).
#### Start On-Demand Display #### Start On-Demand Display
@@ -531,15 +518,13 @@ curl http://localhost:5000/api/v3/display/on-demand/status
> There is no public Python on-demand API. The display controller's > There is no public Python on-demand API. The display controller's
> on-demand machinery is internal — drive it through the REST endpoints > on-demand machinery is internal — drive it through the REST endpoints
> above (or the web UI buttons). The API handlers > above (or the web UI buttons), which write a request into the cache
> (`start_on_demand_display()` / `stop_on_demand_display()` in > manager under the `display_on_demand_request` key
> `web_interface/blueprints/api_v3.py`) write a request into the cache > (`web_interface/blueprints/api_v3.py:1622,1687`) that the controller
> manager under the `display_on_demand_request` key, which > polls at `src/display_controller.py:921`. A separate
> `DisplayController._poll_on_demand_requests()`
> (`src/display_controller.py`) picks up. A separate
> `display_on_demand_config` key is used by the controller itself > `display_on_demand_config` key is used by the controller itself
> during activation (`_activate_on_demand()`) to track what's > during activation to track what's currently running (written at
> currently running, and is cleared by `_clear_on_demand()`. > `display_controller.py:1195`, cleared at `:1221`).
### Duration Modes ### Duration Modes
@@ -661,13 +646,13 @@ keys helps troubleshoot stuck states.
**When Set:** Every display loop iteration **When Set:** Every display loop iteration
**Auto-Cleared:** Never (continuously updated) **Auto-Cleared:** Never (continuously updated)
**4. display_on_demand_processed_id** (TTL: 1 hour) **4. display_on_demand_processed_id** (TTL: 5 minutes)
```text ```
"uuid-string-of-last-processed-request" "uuid-string-of-last-processed-request"
``` ```
**Purpose:** Prevents duplicate request processing **Purpose:** Prevents duplicate request processing
**When Set:** After processing request **When Set:** After processing request
**Auto-Cleared:** After 1 hour TTL **Auto-Cleared:** After 5 minutes TTL
### When Manual Clearing is Needed ### When Manual Clearing is Needed
@@ -700,9 +685,9 @@ keys helps troubleshoot stuck states.
The cache is stored as JSON files under one of: The cache is stored as JSON files under one of:
- `/var/cache/ledmatrix/` (preferred when the service has permission) - `/var/cache/ledmatrix/` (preferred when the service has permission)
- `~/.ledmatrix_cache/` - `~/.cache/ledmatrix/`
- `/opt/ledmatrix/cache/` - `/opt/ledmatrix/cache/`
- `$TMPDIR/ledmatrix_cache/` (fallback) - `/tmp/ledmatrix-cache/` (fallback)
```bash ```bash
# Find the cache dir actually in use # Find the cache dir actually in use
@@ -726,9 +711,8 @@ cache.clear_cache('display_on_demand_request')
cache.clear_cache('display_on_demand_processed_id') cache.clear_cache('display_on_demand_processed_id')
``` ```
> `CacheManager` also has a `delete(key)` method — a thin wrapper over > The actual public method is `clear_cache(key=None)` — there is no
> `clear_cache(key)` — so `cache.delete('display_on_demand_config')` > `delete()` method on `CacheManager`.
> works equally well.
### Cache Impact on Running Service ### Cache Impact on Running Service
@@ -746,7 +730,7 @@ The display controller automatically handles cleanup:
- **Config key**: Cleared when on-demand stops - **Config key**: Cleared when on-demand stops
- **State key**: Updated every display loop iteration - **State key**: Updated every display loop iteration
- **Request key**: Expires after 1 hour TTL (or after processing) - **Request key**: Expires after 1 hour TTL (or after processing)
- **Processed ID**: Expires after 1 hour TTL - **Processed ID**: Expires after 5 minutes TTL
--- ---
@@ -837,6 +821,9 @@ same shape as the example above.
### Testing ### Testing
```bash ```bash
# Run background service test
python test_background_service.py
# Check logs for background operations # Check logs for background operations
sudo journalctl -u ledmatrix -f | grep "background" sudo journalctl -u ledmatrix -f | grep "background"
``` ```
@@ -845,10 +832,9 @@ sudo journalctl -u ledmatrix -f | grep "background"
**View Statistics:** **View Statistics:**
```python ```python
from src.background_data_service import get_background_service from src.background_data_service import BackgroundDataService
from src.cache_manager import CacheManager
service = get_background_service(CacheManager()) service = BackgroundDataService()
stats = service.get_statistics() stats = service.get_statistics()
print(f"Active tasks: {stats['active_tasks']}") print(f"Active tasks: {stats['active_tasks']}")
print(f"Completed: {stats['completed']}") print(f"Completed: {stats['completed']}")
@@ -889,7 +875,6 @@ from src.common.permission_utils import (
ensure_file_permissions, ensure_file_permissions,
get_config_file_mode, get_config_file_mode,
get_assets_file_mode, get_assets_file_mode,
get_assets_dir_mode,
get_plugin_file_mode, get_plugin_file_mode,
get_cache_dir_mode get_cache_dir_mode
) )
@@ -898,10 +883,7 @@ from src.common.permission_utils import (
ensure_directory_permissions(Path("assets/sports"), get_assets_dir_mode()) ensure_directory_permissions(Path("assets/sports"), get_assets_dir_mode())
# Set file permissions after writing # Set file permissions after writing
# (get_config_file_mode requires the file path — secrets files get a ensure_file_permissions(Path("config/config.json"), get_config_file_mode())
# 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 ### When to Use Utilities
@@ -956,7 +938,7 @@ from src.common.permission_utils import ensure_file_permissions, get_config_file
config_path = Path("config/config.json") config_path = Path("config/config.json")
with open(config_path, 'w') as f: with open(config_path, 'w') as f:
json.dump(data, f) json.dump(data, f)
ensure_file_permissions(config_path, get_config_file_mode(config_path)) ensure_file_permissions(config_path, get_config_file_mode())
``` ```
**Pattern 3: Downloading Logo** **Pattern 3: Downloading Logo**
@@ -1002,11 +984,8 @@ These core utilities **already handle permissions** - you don't need to call per
If you encounter permission issues: If you encounter permission issues:
```bash ```bash
# Targeted permission fixes (see scripts/fix_perms/README.md) # Fix all permissions at once
sudo ./scripts/fix_perms/fix_assets_permissions.sh # assets/ tree (logos, fonts) sudo ./scripts/fix_permissions.sh
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 # Fix specific directory
sudo chown -R ledpi:ledpi /home/ledpi/LEDMatrix/config sudo chown -R ledpi:ledpi /home/ledpi/LEDMatrix/config
@@ -1038,7 +1017,7 @@ stat -c "%a %n" config/config.json
## Related Documentation ## Related Documentation
- [PLUGIN_DEVELOPMENT_GUIDE.md](PLUGIN_DEVELOPMENT_GUIDE.md) - Creating plugins with Vegas/on-demand support - [PLUGIN_DEVELOPMENT.md](PLUGIN_DEVELOPMENT.md) - Creating plugins with Vegas/on-demand support
- [WEB_INTERFACE_GUIDE.md](WEB_INTERFACE_GUIDE.md) - Using on-demand controls in web UI - [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 - [PLUGIN_API_REFERENCE.md](PLUGIN_API_REFERENCE.md) - Complete API documentation
- [DEVELOPMENT.md](DEVELOPMENT.md) - Development environment and testing - [DEVELOPMENT.md](DEVELOPMENT.md) - Development environment and testing
-172
View File
@@ -1,172 +0,0 @@
# 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 270295).
| 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 |
+4 -5
View File
@@ -31,7 +31,7 @@ POST /api/v3/system/action
**Base URL**: `http://your-pi-ip:5000/api/v3` **Base URL**: `http://your-pi-ip:5000/api/v3`
See [REST_API_REFERENCE.md](REST_API_REFERENCE.md) for complete documentation. See [API_REFERENCE.md](API_REFERENCE.md) for complete documentation.
## Display Manager Quick Methods ## Display Manager Quick Methods
@@ -190,13 +190,12 @@ def display(self, force_clear=False):
``` ```
LEDMatrix/ LEDMatrix/
├── plugin-repos/ # Installed plugins (default; plugins/ is only ├── plugins/ # Installed plugins
│ # for dev symlinks via scripts/dev/dev_plugin_setup.sh)
├── config/ ├── config/
│ ├── config.json # Main configuration │ ├── config.json # Main configuration
│ └── config_secrets.json # API keys and secrets │ └── config_secrets.json # API keys and secrets
├── docs/ # Documentation ├── docs/ # Documentation
│ ├── REST_API_REFERENCE.md │ ├── API_REFERENCE.md
│ ├── PLUGIN_API_REFERENCE.md │ ├── PLUGIN_API_REFERENCE.md
│ └── ... │ └── ...
└── src/ └── src/
@@ -208,7 +207,7 @@ LEDMatrix/
## Quick Links ## Quick Links
- [Complete REST API Reference](REST_API_REFERENCE.md) - [Complete API Reference](API_REFERENCE.md)
- [Plugin API Reference](PLUGIN_API_REFERENCE.md) - [Plugin API Reference](PLUGIN_API_REFERENCE.md)
- [Plugin Development Guide](PLUGIN_DEVELOPMENT_GUIDE.md) - [Plugin Development Guide](PLUGIN_DEVELOPMENT_GUIDE.md)
- [Advanced Patterns](ADVANCED_PLUGIN_DEVELOPMENT.md) - [Advanced Patterns](ADVANCED_PLUGIN_DEVELOPMENT.md)
+76 -84
View File
@@ -69,24 +69,23 @@ default configuration as it ships in the repo:
```json ```json
{ {
"pixel_outline": 0, "pixel_outline": 0,
"pixel_size": 16, "pixel_size": 5,
"pixel_style": "square", "pixel_style": "square",
"pixel_glow": 6, "pixel_glow": 6,
"display_adapter": "browser", "display_adapter": "pygame",
"allow_adapter_fallback": true,
"icon_path": null, "icon_path": null,
"emulator_title": null, "emulator_title": null,
"suppress_font_warnings": false, "suppress_font_warnings": false,
"suppress_adapter_load_errors": false,
"browser": { "browser": {
"_comment": "For use with the browser adapter only.", "_comment": "For use with the browser adapter only.",
"port": 8888, "port": 8888,
"target_fps": 60, "target_fps": 24,
"fps_display": false, "fps_display": false,
"quality": 70, "quality": 70,
"image_border": true, "image_border": true,
"debug_text": false, "debug_text": false,
"image_format": "JPEG", "image_format": "JPEG"
"open_immediately": false
}, },
"log_level": "info" "log_level": "info"
} }
@@ -97,13 +96,13 @@ default configuration as it ships in the repo:
| Option | Description | Default | Values | | Option | Description | Default | Values |
|--------|-------------|---------|--------| |--------|-------------|---------|--------|
| `pixel_outline` | Pixel border thickness | 0 | 0-5 | | `pixel_outline` | Pixel border thickness | 0 | 0-5 |
| `pixel_size` | Size of each pixel | 16 | 1-64 (816 is typical for testing) | | `pixel_size` | Size of each pixel | 5 | 1-64 (816 is typical for testing) |
| `pixel_style` | Pixel shape | "square" | "square", "circle" | | `pixel_style` | Pixel shape | "square" | "square", "circle" |
| `pixel_glow` | Glow effect intensity | 6 | 0-20 | | `pixel_glow` | Glow effect intensity | 6 | 0-20 |
| `display_adapter` | Display backend | "browser" | "browser", "pygame" | | `display_adapter` | Display backend | "pygame" | "pygame", "browser" |
| `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 | | `emulator_title` | Window title | null | Any string |
| `suppress_font_warnings` | Hide font warnings | false | true/false | | `suppress_font_warnings` | Hide font warnings | false | true/false |
| `suppress_adapter_load_errors` | Hide adapter errors | false | true/false |
### 3. Browser Adapter Configuration ### 3. Browser Adapter Configuration
@@ -112,32 +111,18 @@ When using the browser adapter, additional options are available:
| Option | Description | Default | | Option | Description | Default |
|--------|-------------|---------| |--------|-------------|---------|
| `port` | Web server port | 8888 | | `port` | Web server port | 8888 |
| `target_fps` | Target frames per second | 60 | | `target_fps` | Target frames per second | 24 |
| `fps_display` | Show FPS counter | false | | `fps_display` | Show FPS counter | false |
| `quality` | Image compression quality | 70 | | `quality` | Image compression quality | 70 |
| `image_border` | Show image border | true | | `image_border` | Show image border | true |
| `debug_text` | Show debug information | false | | `debug_text` | Show debug information | false |
| `image_format` | Image format | "JPEG" | | `image_format` | Image format | "JPEG" |
| `open_immediately` | Open the browser page automatically on start | false |
## Running the Emulator ## Running the Emulator
### 1. Use the `-e` Flag (Recommended) ### 1. Set Environment Variable
`run.py` accepts exactly two flags: `-e`/`--emulator` and Enable emulator mode by setting the `EMULATOR` environment variable:
`-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):** **Windows (Command Prompt):**
```cmd ```cmd
@@ -152,6 +137,15 @@ python run.py
``` ```
**Linux/macOS:** **Linux/macOS:**
```bash
export EMULATOR=true
python3 run.py
```
### 2. Alternative: Direct Python Execution
You can also run the emulator directly:
```bash ```bash
EMULATOR=true python3 run.py EMULATOR=true python3 run.py
``` ```
@@ -159,8 +153,7 @@ EMULATOR=true python3 run.py
### 3. Verify Emulator Mode ### 3. Verify Emulator Mode
When running in emulator mode, you should see: When running in emulator mode, you should see:
- The emulated matrix — a web page at `http://localhost:8888` with the - A window displaying the LED matrix simulation
default browser adapter, or a desktop window with the pygame adapter
- Console output indicating emulator mode - Console output indicating emulator mode
- No hardware initialization errors - No hardware initialization errors
@@ -168,36 +161,7 @@ When running in emulator mode, you should see:
LEDMatrix supports two display adapters for the emulator: LEDMatrix supports two display adapters for the emulator:
### 1. Browser Adapter (Default) ### 1. Pygame 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. The pygame adapter provides a native desktop window with real-time display.
@@ -222,6 +186,33 @@ The pygame adapter provides a native desktop window with real-time display.
- `+/-` - Zoom in/out - `+/-` - Zoom in/out
- `R` - Reset zoom - `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 ## Troubleshooting
### Common Issues ### Common Issues
@@ -283,7 +274,8 @@ Enable debug logging:
```json ```json
{ {
"log_level": "debug", "log_level": "debug",
"suppress_font_warnings": false "suppress_font_warnings": false,
"suppress_adapter_load_errors": false
} }
``` ```
@@ -307,18 +299,17 @@ Modify the display dimensions in your main config:
### 2. Plugin Development ### 2. Plugin Development
`run.py` always runs the full rotation — it has no single-plugin flag. For plugin development with the emulator:
To preview or check one plugin in isolation, use the dev tools:
```bash ```bash
# Run the full display in emulator mode (optionally with debug logging) # Enable emulator mode
python3 run.py -e -d export EMULATOR=true
# Live single-plugin preview in the browser (port 5001) # Run with specific plugin
python3 scripts/dev_server.py python run.py --plugin my-plugin
# Headless render/validation of one plugin # Debug mode
python3 scripts/check_plugin.py --plugin my-plugin python run.py --debug
``` ```
### 3. Performance Tuning ### 3. Performance Tuning
@@ -353,10 +344,11 @@ The emulator can work alongside the web interface:
```bash ```bash
# Terminal 1: Start emulator # Terminal 1: Start emulator
python3 run.py -e export EMULATOR=true
python run.py
# Terminal 2: Start web interface (supported entry point) # Terminal 2: Start web interface
python3 web_interface/start.py python web_interface/app.py
``` ```
Access the web interface at `http://localhost:5000` while the emulator runs. Access the web interface at `http://localhost:5000` while the emulator runs.
@@ -373,14 +365,13 @@ Access the web interface at `http://localhost:5000` while the emulator runs.
### 2. Plugin Testing ### 2. Plugin Testing
```bash ```bash
# Test a specific plugin (headless check) # Test specific plugin
python3 scripts/check_plugin.py --plugin clock-simple export EMULATOR=true
python run.py --plugin clock-simple
# Preview a single plugin live in the browser (port 5001) # Test all plugins
python3 scripts/dev_server.py export EMULATOR=true
python run.py --test-plugins
# Test the full rotation in the emulator
python3 run.py -e
``` ```
### 3. Configuration Management ### 3. Configuration Management
@@ -394,8 +385,9 @@ python3 run.py -e
### Basic Clock Display ### Basic Clock Display
```bash ```bash
# Start emulator with clock enabled in config.json # Start emulator with clock
python3 run.py -e export EMULATOR=true
python run.py
``` ```
### Sports Scores ### Sports Scores
@@ -403,16 +395,16 @@ python3 run.py -e
```bash ```bash
# Configure for sports display # Configure for sports display
# Edit config/config.json to enable sports plugins # Edit config/config.json to enable sports plugins
python3 run.py -e export EMULATOR=true
python run.py
``` ```
### Custom Text Display ### Custom Text Display
```bash ```bash
# Preview the text display plugin on its own # Use text display plugin
python3 scripts/check_plugin.py --plugin text-display export EMULATOR=true
# or use the live dev preview server python run.py --plugin text-display --text "Hello World"
python3 scripts/dev_server.py
``` ```
## Support ## Support
+15 -41
View File
@@ -21,30 +21,18 @@ This guide will help you set up your LEDMatrix display for the first time and ge
--- ---
## Quick Start ## Quick Start (5 Minutes)
### 1. Install LEDMatrix ### 1. First Boot
There is no prebuilt SD card image — you install LEDMatrix onto stock 1. Insert the MicroSD card with LEDMatrix installed
Raspberry Pi OS Lite yourself: 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)
1. Flash Raspberry Pi OS Lite to the MicroSD card (Raspberry Pi Imager) **Expected Behavior:**
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 - LED matrix will light up
- A fresh install ships only the bundled `starlark-apps` and - Display will show default plugins (clock, weather, etc.)
`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 - Pi creates WiFi network "LEDMatrix-Setup" if not connected
### 2. Connect to WiFi ### 2. Connect to WiFi
@@ -85,7 +73,7 @@ You should see:
2. Set your matrix configuration: 2. Set your matrix configuration:
- **Rows**: 32 or 64 (match your hardware) - **Rows**: 32 or 64 (match your hardware)
- **Columns**: commonly 64 or 96; the web UI accepts any integer - **Columns**: commonly 64 or 96; the web UI accepts any integer
in the 1128 range, but 64 and 96 are the values the bundled in the 16128 range, but 64 and 96 are the values the bundled
panel hardware ships with panel hardware ships with
- **Chain Length**: Number of panels chained horizontally - **Chain Length**: Number of panels chained horizontally
- **Hardware Mapping**: usually `adafruit-hat-pwm` (with the PWM jumper - **Hardware Mapping**: usually `adafruit-hat-pwm` (with the PWM jumper
@@ -127,16 +115,11 @@ 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 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, 2. Open that plugin's tab to edit its settings (favorite teams, API keys,
update intervals, etc.) update intervals, display duration, etc.)
3. Click **Save** 3. Click **Save**
4. Restart the display service from **Overview** so the new settings take 4. Restart the display service from **Overview** so the new settings take
effect 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** **Example: Weather Plugin**
- Set your location (city, state, country) - Set your location (city, state, country)
- Add an API key from OpenWeatherMap (free signup) to - Add an API key from OpenWeatherMap (free signup) to
@@ -225,14 +208,12 @@ The fastest way to verify a plugin works without waiting for the rotation:
### Customize Your Display ### Customize Your Display
**Adjust display durations:** **Adjust display durations:**
- Open the **Rotation** tab and use the **Screen Durations** section to - Each plugin's tab has a **Display Duration (seconds)** field — set how
set how long each plugin stays on screen per rotation (saved to long that plugin stays on screen each rotation.
`display.display_durations`).
**Organize plugin order:** **Organize plugin order:**
- The **Rotation** tab also has a drag-and-drop **Rotation Order** list - Use the **Plugin Manager** tab to enable/disable plugins. The display
(saved to `display.plugin_rotation_order`). Enable/disable plugins cycles through enabled plugins in the order they appear.
from the **Plugin Manager** tab.
**Add more plugins:** **Add more plugins:**
- Check the **Plugin Store** section of **Plugin Manager** for new plugins. - Check the **Plugin Store** section of **Plugin Manager** for new plugins.
@@ -299,14 +280,10 @@ sudo journalctl -u ledmatrix-web -f
│ ├── config_secrets.json # API keys and secrets │ ├── config_secrets.json # API keys and secrets
│ └── wifi_config.json # WiFi settings │ └── wifi_config.json # WiFi settings
├── plugin-repos/ # Installed plugins (default location) ├── plugin-repos/ # Installed plugins (default location)
├── cache/ # Cached data
└── web_interface/ # Web interface files └── 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 > The plugin install location is configurable via
> `plugin_system.plugins_directory` in `config.json`. The default is > `plugin_system.plugins_directory` in `config.json`. The default is
> `plugin-repos/`. Plugin discovery (`PluginManager.discover_plugins()`) > `plugin-repos/`. Plugin discovery (`PluginManager.discover_plugins()`)
@@ -326,14 +303,11 @@ System tabs:
- WiFi Network selection and AP-mode setup - WiFi Network selection and AP-mode setup
- Schedule Power and dim schedules - Schedule Power and dim schedules
- Display Matrix hardware configuration - Display Matrix hardware configuration
- Rotation Rotation order (drag-and-drop) and screen durations
- Config Editor Raw config.json editor - Config Editor Raw config.json editor
- Backup & Restore Config backup and restore
- Fonts Upload and manage fonts - Fonts Upload and manage fonts
- Logs Real-time log viewing - Logs Real-time log viewing
- Cache Cached data inspection and cleanup - Cache Cached data inspection and cleanup
- Operation History Recent service operations - Operation History Recent service operations
- Tools System diagnostics, updates, dependencies, maintenance
Plugin tabs (second row): Plugin tabs (second row):
- Plugin Manager Browse the Plugin Store, install/enable plugins - Plugin Manager Browse the Plugin Store, install/enable plugins
+15 -11
View File
@@ -10,7 +10,10 @@ Make sure you have the testing packages installed:
```bash ```bash
# Install all dependencies including test packages # Install all dependencies including test packages
pip install -r requirements.txt -r requirements-test.txt pip install -r requirements.txt
# Or install just the test dependencies
pip install pytest pytest-cov pytest-mock
``` ```
### 2. Set Environment Variables ### 2. Set Environment Variables
@@ -250,6 +253,7 @@ test/
├── test_error_aggregator.py # Error aggregation tests ├── test_error_aggregator.py # Error aggregation tests
├── test_schema_manager.py # Schema manager tests ├── test_schema_manager.py # Schema manager tests
├── test_web_api.py # Web API tests ├── test_web_api.py # Web API tests
├── test_nba_*.py # NBA-specific test suites
├── plugins/ # Per-plugin test suites ├── plugins/ # Per-plugin test suites
│ ├── test_clock_simple.py │ ├── test_clock_simple.py
│ ├── test_calendar.py │ ├── test_calendar.py
@@ -299,7 +303,7 @@ If tests fail due to missing packages:
```bash ```bash
# Install all dependencies # Install all dependencies
pip install -r requirements.txt -r requirements-test.txt pip install -r requirements.txt
# Or install specific missing package # Or install specific missing package
pip install <package-name> pip install <package-name>
@@ -331,15 +335,15 @@ pytest --cov=src --cov-report=html
## Continuous Integration ## Continuous Integration
The repo runs the pytest suite via The repo runs
[`.github/workflows/test.yml`](../.github/workflows/test.yml) on every [`.github/workflows/security-audit.yml`](../.github/workflows/security-audit.yml)
push and pull request: a plugin-safety job (harness, visual rendering (bandit + semgrep) on every push. A pytest CI workflow at
and plugin-matrix tests) plus a unit-test job that runs an explicit `.github/workflows/tests.yml` is queued to land alongside this
allowlist of suites — new test files must be added to that list to run PR ([ChuckBuilds/LEDMatrix#307](https://github.com/ChuckBuilds/LEDMatrix/pull/307));
in CI. Release version consistency is checked by the workflow file itself was held back from that PR because the
[`.github/workflows/release-version-check.yml`](../.github/workflows/release-version-check.yml). push token lacked the GitHub `workflow` scope, so it needs to be
Bandit, flake8, mypy and gitleaks run as pre-commit hooks (see committed separately by a maintainer. Once it's in, this section
`.pre-commit-config.yaml`), not in CI. will be updated to describe what the job runs.
## Best Practices ## Best Practices
+1 -1
View File
@@ -86,7 +86,7 @@ The plugin system has been enhanced but remains backward compatible with existin
If you encounter issues during migration: If you encounter issues during migration:
1. Check the [project root README](../README.md) for current installation and usage instructions 1. Check the [README.md](README.md) for current installation and usage instructions
2. Review script README files: 2. Review script README files:
- [`scripts/install/README.md`](../scripts/install/README.md) - Installation scripts documentation - [`scripts/install/README.md`](../scripts/install/README.md) - Installation scripts documentation
- [`scripts/fix_perms/README.md`](../scripts/fix_perms/README.md) - Permission scripts documentation - [`scripts/fix_perms/README.md`](../scripts/fix_perms/README.md) - Permission scripts documentation
+2 -3
View File
@@ -201,9 +201,8 @@ the mode selector for this plugin.
#### `get_vegas_segment_width() -> Optional[int]` #### `get_vegas_segment_width() -> Optional[int]`
For `FIXED_SEGMENT` plugins, the number of *panels* the segment For `FIXED_SEGMENT` plugins, the width in pixels of the segment they
occupies in the scroll (pixel width = panels × `single_panel_width`, occupy in the scroll. `None` lets the controller pick a default.
from `display.hardware.cols`). `None` uses the default of 1 panel.
> The full source for `BasePlugin` lives in > The full source for `BasePlugin` lives in
> `src/plugin_system/base_plugin.py`. If a method here disagrees with the > `src/plugin_system/base_plugin.py`. If a method here disagrees with the
+1 -4
View File
@@ -8,12 +8,9 @@
> - Code paths reference `web_interface_v2.py`; the current web UI is > - Code paths reference `web_interface_v2.py`; the current web UI is
> `web_interface/app.py` with v3 Blueprint-based templates. > `web_interface/app.py` with v3 Blueprint-based templates.
> - The example Flask routes use `/api/plugins/*`; the real API > - The example Flask routes use `/api/plugins/*`; the real API
> blueprint is mounted at `/api/v3` (`web_interface/app.py:199`). > blueprint is mounted at `/api/v3` (`web_interface/app.py:144`).
> - The default plugin location is `plugin-repos/` (configurable via > - The default plugin location is `plugin-repos/` (configurable via
> `plugin_system.plugins_directory`), not `./plugins/`. > `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 > - The "Migration Strategy" and "Implementation Roadmap" sections
> describe work that has now shipped. > describe work that has now shipped.
> >
-6
View File
@@ -1,11 +1,5 @@
# Plugin Configuration Tabs - Architecture # 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 ## System Architecture
### Component Overview ### Component Overview
+1 -1
View File
@@ -296,7 +296,7 @@ Want to change icons programmatically? While not officially supported, you could
## Related Documentation ## Related Documentation
- [Plugin Configuration Tabs](PLUGIN_CONFIGURATION_TABS.md) - Main plugin tabs documentation - [Plugin Configuration Tabs](PLUGIN_CONFIGURATION_TABS.md) - Main plugin tabs documentation
- [Plugin Development Guide](PLUGIN_DEVELOPMENT_GUIDE.md) - How to create plugins - [Plugin Development Guide](plugin_docs/) - How to create plugins
- [Font Awesome Icons](https://fontawesome.com/icons) - Browse all available icons - [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 - [Emoji Reference](https://unicode.org/emoji/charts/full-emoji-list.html) - All emoji options
+2 -2
View File
@@ -169,6 +169,6 @@ If you continue to experience issues:
## Related Documentation ## Related Documentation
- [Plugin Dependency Guide](PLUGIN_DEPENDENCY_GUIDE.md) - [Plugin Dependency Guide](PLUGIN_DEPENDENCY_GUIDE.md)
- [Plugin Development Guide](PLUGIN_DEVELOPMENT_GUIDE.md) - [Plugin Development Guide](docs/plugin_development.md)
- [Troubleshooting](TROUBLESHOOTING.md) - [Troubleshooting Quick Start](TROUBLESHOOTING_QUICK_START.md)
+5 -18
View File
@@ -589,24 +589,11 @@ Your plugin must:
### Versioning Best Practices ### Versioning Best Practices
- **Use semantic versioning**: `MAJOR.MINOR.PATCH` (e.g., `1.2.3`) - **Use semantic versioning**: `MAJOR.MINOR.PATCH` (e.g., `1.2.3`)
- **GitHub as source of truth**: the plugin store resolves versions in this - **Automatic version bumping**: Use the pre-push git hook for automatic patch version bumps
order: GitHub Releases → GitHub Tags → manifest from branch → git commit hash - **Manual versioning**: Only needed for major/minor bumps or special cases
- **Automatic version bumping**: install the self-contained pre-push hook in - **GitHub as source of truth**: Plugin store fetches versions from GitHub releases/tags/manifest
your plugin repo and patch versions bump themselves on push (a git tag
`v{version}` is created and `manifest.json` staged automatically):
```bash See the [Git Workflow rules](../.cursorrules) for version management details.
# 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 ### Submitting to Official Registry
@@ -680,5 +667,5 @@ For your plugin to work well in the plugin store:
- [Advanced Plugin Development](ADVANCED_PLUGIN_DEVELOPMENT.md) - Advanced patterns and examples - [Advanced Plugin Development](ADVANCED_PLUGIN_DEVELOPMENT.md) - Advanced patterns and examples
- [Plugin Quick Reference](PLUGIN_QUICK_REFERENCE.md) - Quick development reference - [Plugin Quick Reference](PLUGIN_QUICK_REFERENCE.md) - Quick development reference
- [Plugin Configuration Guide](PLUGIN_CONFIGURATION_GUIDE.md) - Configuration setup - [Plugin Configuration Guide](PLUGIN_CONFIGURATION_GUIDE.md) - Configuration setup
- [Plugin Store Guide](PLUGIN_STORE_GUIDE.md) - Using the plugin store - [Plugin Store User Guide](PLUGIN_STORE_USER_GUIDE.md) - Using the plugin store
+6 -8
View File
@@ -14,10 +14,8 @@ and [PLUGIN_DEVELOPMENT_GUIDE.md](PLUGIN_DEVELOPMENT_GUIDE.md).
**GitHub Store**: Discovery from `ledmatrix-plugins` registry plus **GitHub Store**: Discovery from `ledmatrix-plugins` registry plus
any GitHub URL any GitHub URL
**Plugin Location**: configured by `plugin_system.plugins_directory` **Plugin Location**: configured by `plugin_system.plugins_directory`
in `config.json` (default `plugin-repos/`). Plugin discovery scans in `config.json` (default `plugin-repos/`; the loader also searches
only this directory — there is no loader fallback to `plugins/` `plugins/` as a fallback)
(only Plugin Store operations and schema lookup additionally probe
`plugins/`)
## File Structure ## File Structure
@@ -111,7 +109,7 @@ git push -u origin main
git tag v1.0.0 git tag v1.0.0
git push origin v1.0.0 git push origin v1.0.0
# Submit to registry (PR to ChuckBuilds/ledmatrix-plugins) # Submit to registry (PR to ChuckBuilds/ledmatrix-plugin-registry)
``` ```
## Using Plugins ## Using Plugins
@@ -122,12 +120,12 @@ git push origin v1.0.0
2. **Install**: Click **Install** in the plugin's row 2. **Install**: Click **Install** in the plugin's row
3. **Configure**: open the plugin's tab in the second nav row 3. **Configure**: open the plugin's tab in the second nav row
4. **Enable/Disable**: toggle switch in the **Installed Plugins** list 4. **Enable/Disable**: toggle switch in the **Installed Plugins** list
5. **Reorder**: use the drag-and-drop **Rotation Order** list in the 5. **Reorder**: order is set by the position in `display_modes` /
**Rotation** tab (saved to `display.plugin_rotation_order`) plugin order; rearranging via drag-and-drop is not yet supported
### REST API ### REST API
The API is mounted at `/api/v3` (`web_interface/app.py:199`). The API is mounted at `/api/v3` (`web_interface/app.py:144`).
```bash ```bash
# Install plugin from the registry # Install plugin from the registry
+8 -14
View File
@@ -323,22 +323,16 @@ curl -X POST http://pi:5000/api/v3/plugins/install-from-url \
### Regular Updates ### Regular Updates
```bash ```bash
# Refresh local clones of all plugin repos # Update stars/downloads counts
python3 scripts/update_plugin_repos.py python3 scripts/update_stats.py
# (Re-)create local plugin repo checkouts from the registry # Validate all plugin entries
python3 scripts/setup_plugin_repos.py python3 scripts/validate_registry.py
# Audit installed plugins for manifest/schema problems # Check for plugin updates
python3 scripts/audit_plugins.py python3 scripts/check_updates.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 ## Converting Existing Plugins
To convert your existing plugins (hello-world, clock-simple) to this system: To convert your existing plugins (hello-world, clock-simple) to this system:
@@ -406,7 +400,7 @@ print(f'Found {len(registry[\"plugins\"])} plugins')
## References ## References
- Plugin Store Implementation: See `PLUGIN_IMPLEMENTATION_SUMMARY.md` - Plugin Store Implementation: See `PLUGIN_STORE_IMPLEMENTATION_SUMMARY.md`
- User Guide: See `PLUGIN_STORE_GUIDE.md` - User Guide: See `PLUGIN_STORE_USER_GUIDE.md`
- Architecture: See `PLUGIN_ARCHITECTURE_SPEC.md` - Architecture: See `PLUGIN_ARCHITECTURE_SPEC.md`
+3 -3
View File
@@ -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. A: Most plugins are small (1-5MB). Check individual plugin documentation for specific requirements.
**Q: Can I create my own plugin?** **Q: Can I create my own plugin?**
A: Yes! See [PLUGIN_DEVELOPMENT_GUIDE.md](PLUGIN_DEVELOPMENT_GUIDE.md) for instructions. A: Yes! See [PLUGIN_DEVELOPMENT.md](PLUGIN_DEVELOPMENT.md) for instructions.
--- ---
## Related Documentation ## Related Documentation
- [PLUGIN_DEVELOPMENT_GUIDE.md](PLUGIN_DEVELOPMENT_GUIDE.md) - Create your own plugins - [PLUGIN_DEVELOPMENT.md](PLUGIN_DEVELOPMENT.md) - Create your own plugins
- [PLUGIN_API_REFERENCE.md](PLUGIN_API_REFERENCE.md) - Plugin API documentation - [PLUGIN_API_REFERENCE.md](PLUGIN_API_REFERENCE.md) - Plugin API documentation
- [PLUGIN_ARCHITECTURE_SPEC.md](PLUGIN_ARCHITECTURE_SPEC.md) - Plugin system architecture (historical) - [PLUGIN_ARCHITECTURE.md](PLUGIN_ARCHITECTURE.md) - Plugin system architecture
- [REST_API_REFERENCE.md](REST_API_REFERENCE.md) - Complete REST API reference - [REST_API_REFERENCE.md](REST_API_REFERENCE.md) - Complete REST API reference
+3 -8
View File
@@ -29,16 +29,15 @@ Start here:
Going deeper: Going deeper:
- [ADVANCED_PLUGIN_DEVELOPMENT.md](ADVANCED_PLUGIN_DEVELOPMENT.md) — advanced patterns - [ADVANCED_PLUGIN_DEVELOPMENT.md](ADVANCED_PLUGIN_DEVELOPMENT.md) — advanced patterns
- [PLUGIN_ARCHITECTURE_SPEC.md](PLUGIN_ARCHITECTURE_SPEC.md) — original plugin-system design spec (historical; see its banner for what has drifted) - [PLUGIN_ARCHITECTURE_SPEC.md](PLUGIN_ARCHITECTURE_SPEC.md) — full plugin-system spec
- [PLUGIN_DEPENDENCY_GUIDE.md](PLUGIN_DEPENDENCY_GUIDE.md) / - [PLUGIN_DEPENDENCY_GUIDE.md](PLUGIN_DEPENDENCY_GUIDE.md) /
[PLUGIN_DEPENDENCY_TROUBLESHOOTING.md](PLUGIN_DEPENDENCY_TROUBLESHOOTING.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_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.md](PLUGIN_CUSTOM_ICONS.md) /
[PLUGIN_CUSTOM_ICONS_FEATURE.md](PLUGIN_CUSTOM_ICONS_FEATURE.md)
- [PLUGIN_REGISTRY_SETUP_GUIDE.md](PLUGIN_REGISTRY_SETUP_GUIDE.md) (+ [registry template](plugin_registry_template.json)) - [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 - [STARLARK_APPS_GUIDE.md](STARLARK_APPS_GUIDE.md) — Starlark-based mini-apps
- [widget-guide.md](widget-guide.md) — widget development - [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 ## Configuring plugins
@@ -53,12 +52,9 @@ Going deeper:
- [ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) — Vegas scroll, on-demand display, - [ADVANCED_FEATURES.md](ADVANCED_FEATURES.md) — Vegas scroll, on-demand display,
cache management, background services, permissions cache management, background services, permissions
- [FONT_MANAGER.md](FONT_MANAGER.md) — font system - [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 ## 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 - [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 - [PLUGIN_API_REFERENCE.md](PLUGIN_API_REFERENCE.md) — Python APIs available to plugins
- [DEVELOPER_QUICK_REFERENCE.md](DEVELOPER_QUICK_REFERENCE.md) — common dev tasks - [DEVELOPER_QUICK_REFERENCE.md](DEVELOPER_QUICK_REFERENCE.md) — common dev tasks
@@ -70,7 +66,6 @@ Going deeper:
- [HOW_TO_RUN_TESTS.md](HOW_TO_RUN_TESTS.md) — running the test suite - [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 - [MULTI_ROOT_WORKSPACE_SETUP.md](MULTI_ROOT_WORKSPACE_SETUP.md) — multi-repo workspace
- [MIGRATION_GUIDE.md](MIGRATION_GUIDE.md) — breaking changes between releases - [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 ## Archive
+2 -2
View File
@@ -31,9 +31,9 @@ All endpoints return JSON responses with a standard format:
- [Plugin-specific endpoints](#plugin-specific-endpoints) - [Plugin-specific endpoints](#plugin-specific-endpoints)
- [Starlark Apps](#starlark-apps) - [Starlark Apps](#starlark-apps)
> The API blueprint is mounted at `/api/v3` (`web_interface/app.py:199`). > The API blueprint is mounted at `/api/v3` (`web_interface/app.py:144`).
> SSE stream endpoints (`/api/v3/stream/*`) are defined directly on the > SSE stream endpoints (`/api/v3/stream/*`) are defined directly on the
> Flask app at `app.py:799-809`. There are 94 routes total — see > Flask app at `app.py:607-615`. There are about 92 routes total — see
> `web_interface/blueprints/api_v3.py` for the canonical list. > `web_interface/blueprints/api_v3.py` for the canonical list.
--- ---
+1 -1
View File
@@ -33,7 +33,7 @@ crashing) simply restores the built-in look.
## The render funnel ## The render funnel
Every sports scoreboard (baseball, football, basketball, hockey — anything Every sports scoreboard (baseball, football, basketball, hockey — anything
built on the `src/base_classes/sports/` package, `core.py`) renders through exactly one seam: built on `src/base_classes/sports.py`) renders through exactly one seam:
`SportsCore._render_game(game, force_clear)`. `SportsCore._render_game(game, force_clear)`.
1. The mode class's `display()` (live, `SportsUpcoming`, `SportsRecent`) 1. The mode class's `display()` (live, `SportsUpcoming`, `SportsRecent`)
-387
View File
@@ -1,387 +0,0 @@
# 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 96100% 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
B0B3 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.
+50 -108
View File
@@ -82,70 +82,6 @@ python3 web_interface/start.py
## Common Issues by Category ## 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 ### Web Interface & Service Issues
#### Service Not Running/Starting #### Service Not Running/Starting
@@ -330,8 +266,8 @@ sudo systemctl cat ledmatrix-web | grep User
6. **Manually enable AP mode:** 6. **Manually enable AP mode:**
```bash ```bash
# Via API (the WiFi blueprint is mounted under /api/v3) # Via API
curl -X POST http://localhost:5000/api/v3/wifi/ap/enable curl -X POST http://localhost:5000/api/wifi/ap/enable
# Via Python # Via Python
python3 -c " python3 -c "
@@ -482,19 +418,19 @@ sudo systemctl cat ledmatrix-web | grep User
1. **Check plugin directory exists:** 1. **Check plugin directory exists:**
```bash ```bash
ls -ld plugin-repos/plugin-id/ ls -ld plugins/plugin-id/
``` ```
2. **Verify manifest.json:** 2. **Verify manifest.json:**
```bash ```bash
cat plugin-repos/plugin-id/manifest.json cat plugins/plugin-id/manifest.json
# Verify all required fields present # Verify all required fields present
``` ```
3. **Check dependencies installed:** 3. **Check dependencies installed:**
```bash ```bash
if [ -f plugin-repos/plugin-id/requirements.txt ]; then if [ -f plugins/plugin-id/requirements.txt ]; then
pip3 install --break-system-packages -r plugin-repos/plugin-id/requirements.txt pip3 install --break-system-packages -r plugins/plugin-id/requirements.txt
fi fi
``` ```
@@ -507,7 +443,7 @@ sudo systemctl cat ledmatrix-web | grep User
```bash ```bash
python3 -c " python3 -c "
import sys import sys
sys.path.insert(0, 'plugin-repos/plugin-id') sys.path.insert(0, 'plugins/plugin-id')
from manager import PluginClass from manager import PluginClass
print('Plugin imports successfully') print('Plugin imports successfully')
" "
@@ -523,18 +459,12 @@ sudo systemctl cat ledmatrix-web | grep User
**Solutions:** **Solutions:**
1. **Manual cache clearing:** 1. **Manual cache clearing:**
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 ```bash
# Clear the cache with the helper script # Remove plugin-specific cache
sudo python3 scripts/utils/clear_cache.py rm -rf cache/plugin-id*
# Or remove files manually from the cache dir in use, e.g.: # Or remove all cache
sudo rm -rf /var/cache/ledmatrix/* rm -rf cache/*
# Restart display # Restart display
sudo systemctl restart ledmatrix sudo systemctl restart ledmatrix
@@ -542,8 +472,8 @@ sudo systemctl cat ledmatrix-web | grep User
2. **Check cache permissions:** 2. **Check cache permissions:**
```bash ```bash
ls -ld /var/cache/ledmatrix ls -ld cache/
sudo ./scripts/fix_perms/fix_cache_permissions.sh sudo chown -R ledpi:ledpi cache/
``` ```
--- ---
@@ -778,11 +708,11 @@ nmcli device status
```bash ```bash
# Check file exists # Check file exists
ls -l config/config.json ls -l config/config.json
ls -l plugin-repos/plugin-id/manifest.json ls -l plugins/plugin-id/manifest.json
# Check directory structure # Check directory structure
ls -la web_interface/ ls -la web_interface/
ls -la plugin-repos/ ls -la plugins/
# Check file permissions # Check file permissions
ls -l config/config_secrets.json ls -l config/config_secrets.json
@@ -810,7 +740,7 @@ python3 -c "from src.wifi_manager import WiFiManager; print('OK')"
# Test plugin import # Test plugin import
python3 -c " python3 -c "
import sys import sys
sys.path.insert(0, 'plugin-repos/plugin-id') sys.path.insert(0, 'plugins/plugin-id')
from manager import PluginClass from manager import PluginClass
print('Plugin imports OK') print('Plugin imports OK')
" "
@@ -818,28 +748,39 @@ print('Plugin imports OK')
--- ---
## Reinstalling Service Files ## Service File Template
If a systemd service file is corrupted or missing, do NOT hand-write If your systemd service file is corrupted or missing, use this template:
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 ```ini
# Reinstall the display service unit [Unit]
sudo ./scripts/install/install_service.sh Description=LEDMatrix Web Interface
After=network.target
# Reinstall the web interface service unit [Service]
sudo ./scripts/install/install_web_service.sh 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
``` ```
Note that `ledmatrix-web.service` runs as root via Save to `/etc/systemd/system/ledmatrix-web.service` and run:
`scripts/utils/start_web_conditionally.py` — root is needed for
system operations (service control, WiFi management), and the wrapper ```bash
honors the `web_display_autostart` config flag before actually sudo systemctl daemon-reload
starting the web server. sudo systemctl enable ledmatrix-web
sudo systemctl start ledmatrix-web
```
--- ---
@@ -873,7 +814,7 @@ echo ""
echo "5. File Structure:" echo "5. File Structure:"
ls -la web_interface/ | head -10 ls -la web_interface/ | head -10
ls -la plugin-repos/ | head -10 ls -la plugins/ | head -10
echo "" echo ""
echo "6. Python Imports:" echo "6. Python Imports:"
@@ -949,11 +890,12 @@ sudo systemctl restart ledmatrix-web
# Reinstall WiFi monitor # Reinstall WiFi monitor
sudo ./scripts/install/install_wifi_monitor.sh sudo ./scripts/install/install_wifi_monitor.sh
# Recreate service files (substitutes __PROJECT_ROOT_DIR__ in systemd/ units) # Recreate service files from templates
sudo ./scripts/install/install_service.sh sudo cp templates/ledmatrix.service /etc/systemd/system/
sudo ./scripts/install/install_web_service.sh sudo cp templates/ledmatrix-web.service /etc/systemd/system/
# Restart # Reload and restart
sudo systemctl daemon-reload
sudo systemctl restart ledmatrix ledmatrix-web sudo systemctl restart ledmatrix ledmatrix-web
``` ```
+18 -23
View File
@@ -39,18 +39,12 @@ present:
- **WiFi** — Network selection and AP-mode setup - **WiFi** — Network selection and AP-mode setup
- **Schedule** — Power and dim schedules - **Schedule** — Power and dim schedules
- **Display** — Matrix hardware configuration (rows, cols, hardware - **Display** — Matrix hardware configuration (rows, cols, hardware
mapping, GPIO slowdown, brightness, PWM) and Vegas Scroll Mode mapping, GPIO slowdown, brightness, PWM)
settings
- **Rotation** — drag-and-drop **Rotation Order** list and per-plugin
**Screen Durations**
- **Config Editor** — Raw `config.json` editor with validation - **Config Editor** — Raw `config.json` editor with validation
- **Backup & Restore** — back up and restore your configuration
- **Fonts** — Upload and manage fonts - **Fonts** — Upload and manage fonts
- **Logs** — Real-time log streaming - **Logs** — Real-time log streaming
- **Cache** — Cached data inspection and cleanup - **Cache** — Cached data inspection and cleanup
- **Operation History** — Recent service operations - **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: A second nav row holds plugin tabs:
@@ -117,12 +111,6 @@ Configure your LED matrix hardware:
- Dynamic Duration — global cap for plugins that extend their display - Dynamic Duration — global cap for plugins that extend their display
time based on content 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. Changes require **Restart Display Service** from the Overview tab.
### Plugin Manager Tab ### Plugin Manager Tab
@@ -171,10 +159,9 @@ Manage fonts for your display:
- See font previews - See font previews
- Check font sizes and styles - Check font sizes and styles
**Font Overrides:** **Plugin Font Overrides:**
- Overrides are set per display *element* (e.g. a specific score or - Set custom fonts for specific plugins
clock text element), not per plugin - Override default font choices
- Override default font choices for individual elements
- Preview font changes - Preview font changes
**Delete Fonts:** **Delete Fonts:**
@@ -196,11 +183,9 @@ View real-time system logs:
- Filter by plugin or component - Filter by plugin or component
**Actions:** **Actions:**
- **Refresh**: Reload the log view
- **Clear**: Clear the current view - **Clear**: Clear the current view
- **Download**: Download logs for offline analysis - **Download**: Download logs for offline analysis
- **Auto-scroll** checkbox: toggle automatic scrolling to the latest - **Pause**: Pause auto-scrolling
entries
--- ---
@@ -263,8 +248,7 @@ The web interface uses Server-Sent Events (SSE) for real-time updates:
**Performance:** **Performance:**
- Minimal bandwidth usage - Minimal bandwidth usage
- Server-side rendering for fast load times - Server-side rendering for fast load times
- The UI is built on Alpine.js and HTMX, so JavaScript must be enabled - Progressive enhancement - works without JavaScript
in the browser
--- ---
@@ -283,6 +267,17 @@ 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 ## API Access
The web interface is built on a REST API that you can access programmatically: The web interface is built on a REST API that you can access programmatically:
@@ -293,7 +288,7 @@ http://your-pi-ip:5000/api/v3
``` ```
The API blueprint mounts at `/api/v3` (see The API blueprint mounts at `/api/v3` (see
`web_interface/app.py:199`). All endpoints below are relative to that `web_interface/app.py:144`). All endpoints below are relative to that
base. base.
**Common Endpoints:** **Common Endpoints:**
-41
View File
@@ -206,47 +206,6 @@ 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. The widget will be automatically rendered when the plugin configuration form is loaded.
## Labelling Enum Options (`x-options.labels`)
A plain `enum` renders as a dropdown whose option text is the value with
underscores replaced and title case applied — `day_first` becomes "Day First".
That is fine for values that read as their own label, and wrong for values that
do not: `vs` becomes "Vs", and `abbrev` says nothing about the `Sep 19` it
actually produces.
Supply `x-options.labels` to set the visible text. This is the same convention
the `checkbox-group` widget uses:
```json
{
"date_format": {
"type": "string",
"enum": ["abbrev", "numeric", "day_first"],
"default": "abbrev",
"x-options": {
"labels": {
"abbrev": "Sep 19",
"numeric": "9/19",
"day_first": "19 Sep"
}
}
}
}
```
Labels are **display only** — the stored value is still the enum value, so
adding them never changes a saved config. The map may be partial: any value
without a label keeps the humanised fallback. Older cores that predate this
support ignore `x-options` and render the fallback for every option, so a
plugin can ship labels without requiring a core upgrade.
Array-table columns (`x-widget: array-table`) accept the same
`x-options.labels` on a column definition, but their fallback is the **raw
value** rather than the humanised one, because those columns hold values such
as ticker symbols where `aapl` → "Aapl" would be wrong. Rows added in the
browser use the labels too (`array-table.js`), so a column reads the same
before and after a page reload.
## Marking Fields as Advanced (`x-advanced`) ## Marking Fields as Advanced (`x-advanced`)
Add `"x-advanced": true` to any top-level, non-object property to move it out Add `"x-advanced": true` to any top-level, non-object property to move it out
+43 -278
View File
@@ -152,8 +152,6 @@ ASSUME_YES=${LEDMATRIX_ASSUME_YES:-0}
SKIP_SOUND=${LEDMATRIX_SKIP_SOUND:-0} SKIP_SOUND=${LEDMATRIX_SKIP_SOUND:-0}
SKIP_PERF=${LEDMATRIX_SKIP_PERF:-0} SKIP_PERF=${LEDMATRIX_SKIP_PERF:-0}
SKIP_REBOOT_PROMPT=${LEDMATRIX_SKIP_REBOOT_PROMPT:-0} SKIP_REBOOT_PROMPT=${LEDMATRIX_SKIP_REBOOT_PROMPT:-0}
SKIP_SWAP=${LEDMATRIX_SKIP_SWAP:-0}
BUILD_JOBS_OVERRIDE=${LEDMATRIX_BUILD_JOBS:-}
usage() { usage() {
cat <<USAGE cat <<USAGE
@@ -165,21 +163,11 @@ Options:
--skip-sound Skip sound module configuration --skip-sound Skip sound module configuration
--skip-perf Skip performance tweaks (isolcpus/audio) --skip-perf Skip performance tweaks (isolcpus/audio)
--no-reboot-prompt Do not prompt for reboot at the end --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 -h, --help Show this help message and exit
Environment variables (same effect as flags): Environment variables (same effect as flags):
LEDMATRIX_ASSUME_YES=1, RPI_RGB_FORCE_REBUILD=1, LEDMATRIX_SKIP_SOUND=1, 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 USAGE
} }
@@ -190,38 +178,12 @@ while [ $# -gt 0 ]; do
--skip-sound) SKIP_SOUND=1 ;; --skip-sound) SKIP_SOUND=1 ;;
--skip-perf) SKIP_PERF=1 ;; --skip-perf) SKIP_PERF=1 ;;
--no-reboot-prompt) SKIP_REBOOT_PROMPT=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 ;; -h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1"; usage; exit 1 ;; *) echo "Unknown option: $1"; usage; exit 1 ;;
esac esac
shift shift
done 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 # Helpers
retry() { retry() {
local attempt=1 local attempt=1
@@ -301,144 +263,15 @@ check_disk_space() {
fi 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 ""
echo "This script will perform the following steps:" echo "This script will perform the following steps:"
echo "1. Check prerequisites (network, disk, memory) and install system dependencies" echo "1. Install system dependencies"
echo "2. Fix cache permissions" echo "2. Fix cache permissions"
echo "3. Fix assets directory permissions" echo "3. Fix assets directory permissions"
echo "3.1. Fix plugin directory permissions" echo "3.1. Fix plugin directory permissions"
echo "4. Ensure configuration files exist" echo "4. Ensure configuration files exist"
echo "5. Install Python project dependencies (requirements.txt)" echo "5. Install Python project dependencies (requirements.txt)"
echo "6. Build and install rpi-rgb-led-matrix and test import" 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. Install web interface dependencies"
echo "7.5. Install main LED Matrix service" echo "7.5. Install main LED Matrix service"
echo "8. Install web interface service" echo "8. Install web interface service"
@@ -482,16 +315,9 @@ echo "----------------------------------------"
# Pre-flight checks before APT operations # Pre-flight checks before APT operations
check_network check_network
check_disk_space check_disk_space
check_memory
# Update package list. The one-shot installer refreshes the lists moments # Update package list
# before invoking this script and exports LEDMATRIX_APT_UPDATED=1, so skip the apt_update
# 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 # Install required system packages
echo "Installing Python packages and dependencies..." echo "Installing Python packages and dependencies..."
@@ -821,6 +647,10 @@ if [ ! -f "$PROJECT_ROOT_DIR/config/config_secrets.json" ]; then
echo "⚠ Template config/config_secrets.template.json not found; creating a minimal secrets file" echo "⚠ Template config/config_secrets.template.json not found; creating a minimal secrets file"
cat > "$PROJECT_ROOT_DIR/config/config_secrets.json" <<'EOF' cat > "$PROJECT_ROOT_DIR/config/config_secrets.json" <<'EOF'
{ {
"youtube": {
"api_key": "YOUR_YOUTUBE_API_KEY",
"channel_id": "YOUR_YOUTUBE_CHANNEL_ID"
},
"github": { "github": {
"api_token": "YOUR_GITHUB_PERSONAL_ACCESS_TOKEN" "api_token": "YOUR_GITHUB_PERSONAL_ACCESS_TOKEN"
} }
@@ -1072,66 +902,29 @@ else
fi fi
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 pushd "$PROJECT_ROOT_DIR/rpi-rgb-led-matrix-master" >/dev/null
echo "Installing rpi-rgb-led-matrix Python package (scikit-build-core + cmake)..." echo "Installing rpi-rgb-led-matrix Python package (scikit-build-core + cmake)..."
echo " Build deps required: python-dev-is-python3 cmake" echo " Build deps required: python-dev-is-python3 cmake"
echo " Compiling C++ with ${BUILD_JOBS} parallel job(s)..." echo " This compiles C++ — may take 2-5 minutes on Pi 4/5..."
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_OUTPUT=$(mktemp)
BUILD_SUCCESS=false BUILD_SUCCESS=false
if run_rgbmatrix_build "$BUILD_JOBS" "$BUILD_OUTPUT"; then if python3 -m pip install --break-system-packages . > "$BUILD_OUTPUT" 2>&1; then
BUILD_SUCCESS=true BUILD_SUCCESS=true
fi fi
cat "$BUILD_OUTPUT" >> "$LOG_FILE" cat "$BUILD_OUTPUT" >> "$LOG_FILE"
if [ "$BUILD_SUCCESS" != true ]; then if [ "$BUILD_SUCCESS" != true ]; then
print_rgbmatrix_build_failure "$BUILD_OUTPUT" 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 "" echo ""
echo "-- Last 50 lines of build output --" echo "-- Last 50 lines of build output --"
tail -n 50 "$BUILD_OUTPUT" tail -n 50 "$BUILD_OUTPUT"
rm -f "$BUILD_OUTPUT" rm -f "$BUILD_OUTPUT"
if [ -n "$BUILD_TMPDIR" ]; then rm -rf "$BUILD_TMPDIR"; fi
popd >/dev/null popd >/dev/null
lm_remove_build_swap
exit 1 exit 1
fi fi
rm -f "$BUILD_OUTPUT" rm -f "$BUILD_OUTPUT"
if [ -n "$BUILD_TMPDIR" ]; then rm -rf "$BUILD_TMPDIR"; fi
popd >/dev/null popd >/dev/null
# Hand the memory back well before Step 14's reboot.
lm_remove_build_swap
else else
echo "✗ rpi-rgb-led-matrix-master directory not found at $PROJECT_ROOT_DIR" echo "✗ rpi-rgb-led-matrix-master directory not found at $PROJECT_ROOT_DIR"
echo "Failed to initialize submodule or clone repository" echo "Failed to initialize submodule or clone repository"
@@ -1183,26 +976,25 @@ else
cd "$PROJECT_ROOT_DIR" cd "$PROJECT_ROOT_DIR"
# Try to install dependencies using the smart installer if available # Try to install dependencies using the smart installer if available
WEB_DEPS_OK=true
if [ -f "$PROJECT_ROOT_DIR/scripts/install_dependencies_apt.py" ]; then if [ -f "$PROJECT_ROOT_DIR/scripts/install_dependencies_apt.py" ]; then
echo "Using smart dependency installer..." echo "Using smart dependency installer..."
# -u: unbuffered stdout/stderr so output is captured in $LOG_FILE in # -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 # real time and in order relative to this script's own echo statements
if ! python3 -u "$PROJECT_ROOT_DIR/scripts/install_dependencies_apt.py"; then python3 -u "$PROJECT_ROOT_DIR/scripts/install_dependencies_apt.py"
WEB_DEPS_OK=false
fi
else else
echo "Web dependencies already installed from web_interface/requirements.txt in Step 5" echo "Using pip to install dependencies..."
if [ -f "$PROJECT_ROOT_DIR/requirements_web_v2.txt" ]; then
# --ignore-installed: see the Step 5 web_interface/requirements.txt
# install above — same apt/pip RECORD-file conflict applies here.
python3 -m pip install --break-system-packages --prefer-binary --ignore-installed -r requirements_web_v2.txt
else
echo "⚠ requirements_web_v2.txt not found; skipping web dependency install"
fi
fi fi
# Create the marker only when installation actually succeeded, so a # Create marker file to indicate dependencies are installed
# re-run retries instead of silently skipping missing dependencies. touch "$PROJECT_ROOT_DIR/.web_deps_installed"
if [ "$WEB_DEPS_OK" = true ]; then echo "✓ Web interface dependencies installed"
touch "$PROJECT_ROOT_DIR/.web_deps_installed"
echo "✓ Web interface dependencies installed"
else
echo "⚠ Web interface dependency install reported errors; not creating .web_deps_installed (will retry on next run)"
fi
fi fi
echo "" echo ""
@@ -1480,54 +1272,27 @@ if [ -f "$PROJECT_ROOT_DIR/config/config.json" ]; then
fi fi
# Set proper permissions for secrets file (restrictive: owner rw, group r) # Set proper permissions for secrets file (restrictive: owner rw, group r)
# Owned by whoever WRITES the file, which is the web interface. # If service runs as root, set ownership to root so it can read as owner
# # Otherwise, use ACTUAL_USER and rely on group membership
# This used to read the User= of ledmatrix.service — the display service —
# and, finding root, hand the file to root:ledmatrix 640. But the display
# service only ever reads secrets, and root can read any file regardless of
# mode. The account that *writes* them is the web interface: it saves config
# edits and performs backup restores, and it deliberately does not run as root
# (a web server should not). So a root-owned, group-read-only file left the web
# UI unable to write its own secrets, and restoring a backup failed with
# "Permission denied: config_secrets.json" while every other file in the same
# backup restored fine.
#
# Owning by the writer keeps the tighter 640 rather than loosening to
# group-writable, and root still reads it as superuser.
if [ -f "$PROJECT_ROOT_DIR/config/config_secrets.json" ]; then if [ -f "$PROJECT_ROOT_DIR/config/config_secrets.json" ]; then
# The web service is the writer; fall back to the display service, then to # Check if service runs as root (from service file or template)
# the installing user, so an unusual layout still lands somewhere sensible. SERVICE_USER="root"
SECRETS_OWNER="" if [ -f "/etc/systemd/system/ledmatrix.service" ]; then
for unit in "/etc/systemd/system/ledmatrix-web.service" \ SERVICE_USER=$(grep "^User=" /etc/systemd/system/ledmatrix.service | cut -d'=' -f2 || echo "root")
"$PROJECT_ROOT_DIR/systemd/ledmatrix-web.service"; do elif [ -f "$PROJECT_ROOT_DIR/systemd/ledmatrix.service" ]; then
if [ -f "$unit" ]; then SERVICE_USER=$(grep "^User=" "$PROJECT_ROOT_DIR/systemd/ledmatrix.service" | cut -d'=' -f2 || echo "root")
SECRETS_OWNER=$(grep -m1 "^User=" "$unit" | cut -d'=' -f2)
[ -n "$SECRETS_OWNER" ] && break
fi
done
if [ -z "$SECRETS_OWNER" ]; then
SECRETS_OWNER="$ACTUAL_USER"
fi fi
SECRETS_FILE="$PROJECT_ROOT_DIR/config/config_secrets.json"
# A root-owned file is only correct when the writer really is root. if [ "$SERVICE_USER" = "root" ]; then
if ! chown "$SECRETS_OWNER:$LEDMATRIX_GROUP" "$SECRETS_FILE"; then # Service runs as root - set ownership to root so it can read as owner
echo "✗ ERROR: Failed to set ownership on $SECRETS_FILE to $SECRETS_OWNER:$LEDMATRIX_GROUP" >&2 chown "root:$LEDMATRIX_GROUP" "$PROJECT_ROOT_DIR/config/config_secrets.json" || true
echo " Try: sudo chown $SECRETS_OWNER:$LEDMATRIX_GROUP $SECRETS_FILE" >&2 echo "✓ Secrets file permissions set (root:ledmatrix for root service)"
exit 1 else
# Service runs as regular user - use ACTUAL_USER and rely on group membership
chown "$ACTUAL_USER:$LEDMATRIX_GROUP" "$PROJECT_ROOT_DIR/config/config_secrets.json" || true
echo "✓ Secrets file permissions set ($ACTUAL_USER:ledmatrix)"
fi fi
if ! chmod 640 "$SECRETS_FILE"; then chmod 640 "$PROJECT_ROOT_DIR/config/config_secrets.json"
echo "✗ ERROR: Failed to set permissions on $SECRETS_FILE to 640" >&2
echo " Try: sudo chmod 640 $SECRETS_FILE" >&2
exit 1
fi
ACTUAL_OWNERSHIP=$(stat -c '%U:%G' "$SECRETS_FILE" 2>/dev/null || echo "unknown")
ACTUAL_MODE=$(stat -c '%a' "$SECRETS_FILE" 2>/dev/null || echo "unknown")
if [ "$ACTUAL_OWNERSHIP" != "$SECRETS_OWNER:$LEDMATRIX_GROUP" ] || [ "$ACTUAL_MODE" != "640" ]; then
echo "✗ ERROR: $SECRETS_FILE ended up as $ACTUAL_OWNERSHIP mode $ACTUAL_MODE, expected $SECRETS_OWNER:$LEDMATRIX_GROUP mode 640" >&2
echo " The web interface may be unable to read or write config_secrets.json." >&2
exit 1
fi
echo "✓ Secrets file owned by the web service user ($SECRETS_OWNER:$LEDMATRIX_GROUP, mode 640)"
fi fi
# Set proper permissions for YTM auth file (readable by all users including root service) # Set proper permissions for YTM auth file (readable by all users including root service)
+6 -3
View File
@@ -10,13 +10,16 @@ python_functions = test_*
testpaths = test testpaths = test
# Output options # Output options
# Coverage is deliberately NOT configured here: a bare local `pytest` should # Note: Coverage options require pytest-cov to be installed
# be fast and dependency-light. Coverage is measured and enforced in exactly # Run: pip install pytest-cov
# one place — the unit-tests job in .github/workflows/test.yml.
addopts = addopts =
-v -v
--strict-markers --strict-markers
--tb=short --tb=short
--cov=src
--cov-report=term-missing
--cov-report=html
--cov-fail-under=30
# Markers # Markers
markers = markers =
+7 -7
View File
@@ -1,9 +1,9 @@
# Test/dev-only dependencies (not needed on a running display). # Test-only dependencies for the plugin safety harness and pytest suite.
# Install alongside requirements.txt: pip install -r requirements.txt -r requirements-test.txt # 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, pytest-cov, pytest-mock, and jsonschema are already pinned (with
pytest-mock>=3.11.0,<4.0.0 # major-version caps) in requirements.txt, so they are intentionally NOT
# repeated here — re-pinning pytest to <9 collided with requirements.txt's
# pytest>=9.0.3,<10 and made the two files impossible to install together.
# Only declare what requirements.txt doesn't already provide.
freezegun>=1.2,<2 # deterministic time for golden-image tests freezegun>=1.2,<2 # deterministic time for golden-image tests
psutil>=6.0.0,<8.0.0 # optional at runtime; installed for tests so the
# /system/status endpoint's real path is exercised
mypy>=1.5.0,<2.0.0 # static type checking (also pinned in .pre-commit-config.yaml)
+16 -10
View File
@@ -11,22 +11,27 @@ pytz>=2024.2,<2025.0 # Updated for latest timezone data
# HTTP requests # HTTP requests
requests>=2.33.0,<3.0.0 requests>=2.33.0,<3.0.0
urllib3>=2.7.0,<3.0.0 # requests transitive, but imported directly (urllib3.util.retry.Retry); floor is a security floor, not the API floor — 1.26.x carries ~10 CVEs
# Google API integration # Google API integration
# Font rendering # Font rendering
freetype-py>=2.5.1,<3.0.0 freetype-py>=2.5.1,<3.0.0
# Spotify integration (used by web_interface/blueprints/api_v3.py OAuth endpoints) # Spotify integration
spotipy>=2.25.2,<3.0.0 spotipy>=2.25.2,<3.0.0
# Flask web framework # Flask web framework
Flask>=3.1.3,<4.0.0 Flask>=3.1.3,<4.0.0
# WebSocket support: intentionally NOT declared here. Plugins that need # Text processing
# it (e.g. ledmatrix-music's Socket.IO client) declare it in their own
# requirements.txt, which the plugin store installs. # Calendar integration
# WebSocket support
python-socketio>=5.14.0,<6.0.0
python-engineio>=4.9.0,<5.0.0
websockets>=12.0,<14.0
websocket-client>=1.8.0,<2.0.0
# JSON Schema validation # JSON Schema validation
jsonschema>=4.20.0,<5.0.0 jsonschema>=4.20.0,<5.0.0
@@ -34,8 +39,11 @@ jsonschema>=4.20.0,<5.0.0
# Requirement specifier parsing (plugin dependency satisfaction checks) # Requirement specifier parsing (plugin dependency satisfaction checks)
packaging>=23.0,<27.0 packaging>=23.0,<27.0
# Testing dependencies live in requirements-test.txt: # Testing dependencies
# 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
mypy>=1.5.0,<2.0.0
# ─────────────────────────────────────────────────────────────────────── # ───────────────────────────────────────────────────────────────────────
# Optional dependencies — the code imports these inside try/except # Optional dependencies — the code imports these inside try/except
@@ -51,9 +59,7 @@ packaging>=23.0,<27.0
# psutil — per-plugin resource monitoring in # psutil — per-plugin resource monitoring in
# src/plugin_system/resource_monitor.py. The monitor # src/plugin_system/resource_monitor.py. The monitor
# silently no-ops when missing (PSUTIL_AVAILABLE = False). # silently no-ops when missing (PSUTIL_AVAILABLE = False).
# Note: web_interface/requirements.txt requires this # pip install 'psutil>=5.9.0,<6.0.0'
# range as a hard dependency — keep the two in sync.
# pip install 'psutil>=6.0.0,<7.0.0'
# #
# Flask-Limiter — request rate limiting in web_interface/app.py # Flask-Limiter — request rate limiting in web_interface/app.py
# (accidental-abuse protection, not security). The # (accidental-abuse protection, not security). The
+1 -1
View File
@@ -201,7 +201,7 @@ def process_schema_file(schema_path: Path) -> bool:
def main(): def main():
"""Main entry point.""" """Main entry point."""
project_root = Path(__file__).parent.parent project_root = Path(__file__).parent.parent
plugins_dir = project_root / 'plugin-repos' plugins_dir = project_root / 'plugins'
if not plugins_dir.exists(): if not plugins_dir.exists():
print(f"Error: Plugins directory not found: {plugins_dir}") print(f"Error: Plugins directory not found: {plugins_dir}")
+1 -1
View File
@@ -193,7 +193,7 @@ def analyze_schema(schema_path: Path) -> Dict[str, Any]:
def main(): def main():
"""Main analysis function.""" """Main analysis function."""
project_root = Path(__file__).parent.parent project_root = Path(__file__).parent.parent
plugins_dir = project_root / "plugin-repos" plugins_dir = project_root / "plugins"
if not plugins_dir.exists(): if not plugins_dir.exists():
print(f"Plugins directory not found: {plugins_dir}") print(f"Plugins directory not found: {plugins_dir}")
-122
View File
@@ -1,122 +0,0 @@
#!/usr/bin/env python3
"""Assert that a release tag, the CHANGELOG, and `src.__version__` all agree.
Run it *before* creating a tag to check yourself:
python scripts/check_release_version.py v3.2.0
Wiring it into CI (on pushed `v*` tags and published releases) is a follow-up
PR, so for now it is a manual pre-flight: run it before creating the tag and a
mismatch shows up here rather than as a silent wrong answer on user devices.
Why this exists: `v3.1.0` was tagged 2026-05-31 while `src/__init__.py` still
said `"1.0.0"`; the bump to `"3.1.0"` did not land until 2026-07-12. Devices
installed from that release report `1.0.0`, which is below the `(2, 0, 0)` floor
in `PluginLoader._warn_if_incompatible`, so they are silently exempt from every
plugin compatibility warning. Plugin `ledmatrix_min_version` floors are only as
trustworthy as this agreement. See `docs/SPORTS_UNIFICATION.md`, phase B4.
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT))
# [0-9] rather than \d, and [ \t] rather than \s: \d also matches non-ASCII
# decimal digits (which int() parses), and \s matches newlines, so "##\n3.2.0"
# would otherwise read as a version heading. Keep these in step with
# test/test_version_consistency.py.
SEMVER = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+$")
HEADING = re.compile(
r"^##[ \t]+(?P<version>[0-9]+\.[0-9]+\.[0-9]+)[ \t]*$", re.MULTILINE)
def normalize(tag: str) -> str:
"""`v3.2.0` and `3.2.0` are the same release; tags here carry the `v`."""
return tag[1:] if tag.startswith("v") else tag
def newest_changelog_version(changelog: Path) -> str | None:
"""Newest version heading, or None when there is none.
Raises OSError if the file cannot be read; main() turns that into a clear
message rather than a traceback, because this runs as a release gate and a
traceback there reads as "the tooling is broken", not "your CHANGELOG is
missing".
"""
headings = HEADING.findall(changelog.read_text(encoding="utf-8"))
return headings[0] if headings else None
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"tag",
help="Release tag to check, with or without the leading 'v' (e.g. v3.2.0)",
)
args = parser.parse_args()
from src import __version__ as core_version
tag_version = normalize(args.tag)
changelog_path = REPO_ROOT / "CHANGELOG.md"
problems: list[str] = []
try:
changelog_version = newest_changelog_version(changelog_path)
except OSError as e:
print(
f"Release version check FAILED for tag {args.tag}:\n"
f" - could not read {changelog_path}: {e}\n"
f" Restore the file (git checkout -- CHANGELOG.md) and re-run.",
file=sys.stderr,
)
return 1
if not SEMVER.match(tag_version):
problems.append(
f"tag {args.tag!r} is not vX.Y.Z. Older tags (v2.5) predate this "
"check; new releases must be full semver so floors can parse them."
)
if not SEMVER.match(core_version):
problems.append(f"src.__version__ is {core_version!r}, which is not X.Y.Z")
if tag_version != core_version:
problems.append(
f"tag says {tag_version} but src.__version__ says {core_version}. "
"Bump src/__init__.py to match the tag before releasing — devices "
"report __version__, not the tag, and plugin floors compare "
"against it."
)
if changelog_version is None:
problems.append("CHANGELOG.md has no '## X.Y.Z' version heading")
elif changelog_version != core_version:
problems.append(
f"CHANGELOG.md's newest heading is {changelog_version} but "
f"src.__version__ is {core_version}. Plugin authors read the "
"CHANGELOG to pick a ledmatrix_min_version floor."
)
if problems:
print(f"Release version check FAILED for tag {args.tag}:", file=sys.stderr)
for problem in problems:
print(f" - {problem}", file=sys.stderr)
return 1
print(
f"OK: tag {args.tag}, src.__version__ {core_version}, and the CHANGELOG "
"all agree."
)
return 0
if __name__ == "__main__":
sys.exit(main())
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""
Check what imports are actually in the app.py file on the Pi
"""
from pathlib import Path
# Read the app.py file and check the import lines
app_py_path = Path.home() / 'LEDMatrix' / 'web_interface' / 'app.py'
print(f"🔍 Checking imports in: {app_py_path}")
print(f"📁 File exists: {app_py_path.exists()}")
if app_py_path.exists():
with open(app_py_path, 'r') as f:
lines = f.readlines()
print("\n🔍 Import lines in app.py:")
for i, line in enumerate(lines, 1):
if 'from' in line and 'blueprints' in line and 'import' in line:
print(f" Line {i}: {line.strip()}")
print("\n🔍 Blueprint registration lines:")
for i, line in enumerate(lines, 1):
if 'register_blueprint' in line:
print(f" Line {i}: {line.strip()}")
else:
print("❌ app.py file not found!")
+2 -2
View File
@@ -13,8 +13,8 @@ def main():
print("🔍 LED Matrix Web Interface Debug Tool") print("🔍 LED Matrix Web Interface Debug Tool")
print("=" * 50) print("=" * 50)
# Change to project root (two levels up from scripts/debug/) # Change to project root (where this script is located)
project_root = Path(__file__).parent.parent.parent.resolve() project_root = Path(__file__).parent.resolve()
os.chdir(project_root) os.chdir(project_root)
print(f"📁 Working directory: {os.getcwd()}") print(f"📁 Working directory: {os.getcwd()}")
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""
Direct fix for import issues - manually edit the app.py file
"""
import os
from pathlib import Path
def fix_imports():
app_py_path = Path.home() / 'LEDMatrix' / 'web_interface' / 'app.py'
print(f"🔧 Directly fixing imports in: {app_py_path}")
# Read the file
with open(app_py_path, 'r') as f:
lines = f.readlines()
# Find and fix the import lines
fixed = False
for i, line in enumerate(lines, 1):
if 'from blueprints.pages_v3 import' in line:
lines[i-1] = "from web_interface.blueprints.pages_v3 import pages_v3\n"
print(f"✅ Fixed line {i}: from blueprints.pages_v3 import → from web_interface.blueprints.pages_v3 import")
fixed = True
elif 'from blueprints.api_v3 import' in line:
lines[i-1] = "from web_interface.blueprints.api_v3 import api_v3\n"
print(f"✅ Fixed line {i}: from blueprints.api_v3 import → from web_interface.blueprints.api_v3 import")
fixed = True
if not fixed:
print("❌ No import lines found to fix")
return False
# Write the fixed file back
with open(app_py_path, 'w') as f:
f.writelines(lines)
print("✅ File updated successfully")
return True
def verify_fix():
print("\n🔍 Verifying the fix...")
os.system("python3 check_imports.py")
if __name__ == "__main__":
if fix_imports():
print("\n🧹 Clearing Python cache...")
os.system("find ~/LEDMatrix -type d -name '__pycache__' -exec rm -rf {} + 2>/dev/null || true")
os.system("find ~/LEDMatrix -name '*.pyc' -delete 2>/dev/null || true")
print("\n✅ Imports fixed and cache cleared!")
verify_fix()
print("\n🚀 Now try running the web interface:")
print("cd ~/LEDMatrix")
print("python3 web_interface/start.py")
else:
print("\n❌ Fix failed")
+2 -6
View File
@@ -156,13 +156,9 @@ echo ""
echo "6. Check disk space - building packages requires temporary space" echo "6. Check disk space - building packages requires temporary space"
echo " df -h" echo " df -h"
echo "" echo ""
echo "7. For slow builds or out-of-memory kills, increase swap space." echo "7. For slow builds, increase swap space:"
echo " first_time_install.sh already adds temporary swap on low-memory devices;"
echo " this makes it permanent. Set CONF_MAXSWAP too - it defaults to 2048 and"
echo " silently clamps CONF_SWAPSIZE, so raising CONF_SWAPSIZE alone does nothing."
echo " sudo dphys-swapfile swapoff" echo " sudo dphys-swapfile swapoff"
echo " sudo sed -i 's/^#\\?CONF_SWAPSIZE=.*/CONF_SWAPSIZE=2048/' /etc/dphys-swapfile" echo " sudo nano /etc/dphys-swapfile # Set CONF_SWAPSIZE=2048"
echo " sudo sed -i 's/^#\\?CONF_MAXSWAP=.*/CONF_MAXSWAP=2048/' /etc/dphys-swapfile"
echo " sudo dphys-swapfile setup" echo " sudo dphys-swapfile setup"
echo " sudo dphys-swapfile swapon" echo " sudo dphys-swapfile swapon"
echo "" echo ""
+3 -3
View File
@@ -7,8 +7,8 @@ import os
import logging import logging
from typing import Tuple from typing import Tuple
# Add the project root to Python path so we can import the logo downloader # Add the src directory to Python path so we can import the logo downloader
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
# Set up logging # Set up logging
logging.basicConfig( logging.basicConfig(
@@ -28,7 +28,7 @@ def download_nba_logos(force_download: bool = False) -> Tuple[int, int]:
Tuple of (downloaded_count, failed_count) Tuple of (downloaded_count, failed_count)
""" """
try: try:
from src.logo_downloader import download_all_logos_for_league from logo_downloader import download_all_logos_for_league
logger.info("🏀 Starting NBA logo download...") logger.info("🏀 Starting NBA logo download...")
logger.info(f"Target directory: assets/sports/nba_logos/") logger.info(f"Target directory: assets/sports/nba_logos/")
+3
View File
@@ -31,6 +31,9 @@ owned by the `ledmatrix` service user or by `root`.
systemd journal access, and the sudoers entries the web interface systemd journal access, and the sudoers entries the web interface
needs to control the display service. needs to control the display service.
- **`fix_nhl_cache.sh`** — Targeted fix for NHL plugin cache issues
(clears the NHL cache and restarts the display service).
- **`safe_plugin_rm.sh`** — Validates that a plugin removal path is - **`safe_plugin_rm.sh`** — Validates that a plugin removal path is
inside an allowed base directory before deleting it. Used by the web inside an allowed base directory before deleting it. Used by the web
interface (via sudo) when a user clicks **Uninstall** on a plugin — interface (via sudo) when a user clicks **Uninstall** on a plugin —
View File
View File
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
"""
Script to fix NHL cache issues on Raspberry Pi.
This will clear the NHL cache and restart the display service.
"""
echo "=========================================="
echo "Fixing NHL Cache Issues"
echo "=========================================="
# Clear NHL cache
echo "Clearing NHL cache..."
python3 clear_nhl_cache.py
# Restart the display service to force fresh data fetch
echo "Restarting display service..."
sudo systemctl restart ledmatrix.service
echo "NHL cache cleared and service restarted!"
echo "NHL managers should now fetch fresh data from ESPN API."
echo "Check the logs to see if NHL games are now being displayed."
View File
View File
+356
View File
@@ -0,0 +1,356 @@
#!/usr/bin/env python3
"""
Security Report Generator
Aggregates JSON output from all CI security audit jobs into a single
Markdown report suitable for PR comments and artifact storage.
Expected artifact layout (from actions/download-artifact@v4):
<artifact-dir>/
sast-results/
bandit-results.json
semgrep-results.json
dependency-audit-results/
pip-audit-results.json
safety-results.json
secrets-scan-results/
gitleaks-results.json
security-proofs-results/
security-proofs-results.json
plugin-audit-results/
plugin-audit-results.json
Usage:
python scripts/generate_report.py --artifact-dir audit-artifacts/ --output report.md
python scripts/generate_report.py --artifact-dir audit-artifacts/ --output report.md --verbose
"""
import argparse
import json
import sys
from pathlib import Path
from datetime import datetime, timezone
PROJECT_ROOT = Path(__file__).resolve().parent.parent
# Gitleaks matches exactly equal to one of these (not a substring match -- a
# real secret that merely contains one of these words as part of its actual
# value must still be reported) are known template placeholders.
_GITLEAKS_SUPPRESS_EXACT_VALUES = {
"YOUR_YOUTUBE_API_KEY",
"YOUR_YOUTUBE_CHANNEL_ID",
"YOUR_GITHUB_PERSONAL_ACCESS_TOKEN",
}
# Findings in these files are suppressed regardless of value -- they are
# template/example files that are expected to only ever contain placeholders.
_GITLEAKS_SUPPRESS_PATHS = [
"config_secrets.template.json",
"config.template.json",
]
# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────
def _load(path: Path) -> tuple[dict | list | None, str | None]:
"""Load a JSON artifact file.
Returns (data, error): error is None on success (data is whatever was
parsed, which may legitimately be an empty list/dict for a clean scan);
otherwise error is a human-readable reason the artifact is unavailable,
distinguishing "missing/malformed artifact" from "valid empty result" so
callers don't silently treat a broken CI job as a clean pass.
"""
if not path.exists():
return None, f"artifact not found: {path}"
try:
return json.loads(path.read_text(encoding="utf-8")), None
except (json.JSONDecodeError, OSError) as exc:
return None, f"could not read/parse {path}: {exc}"
def _md_sanitize_cell(value: object) -> str:
"""Escape/normalize a value so scanner-controlled content (a matched
secret, a bandit issue_text, a file path) can't alter the Markdown
table's structure: pipes would add bogus columns, newlines would break
out of the row (or forge a fake header/separator line)."""
text = str(value)
text = text.replace("\\", "\\\\").replace("|", "\\|")
text = text.replace("\r\n", " ").replace("\n", " ").replace("\r", " ")
return text
def _md_table_row(*cells: str) -> str:
return "| " + " | ".join(_md_sanitize_cell(c) for c in cells) + " |"
# ─────────────────────────────────────────────────────────────────────────────
# Per-tool summarizers
# Returns: (markdown_lines: list[str], critical_count: int, available: bool)
# `available=False` means the artifact was missing or malformed -- distinct
# from a valid scan that simply found nothing -- so the caller can report
# INCOMPLETE instead of silently counting it as a clean pass.
# ─────────────────────────────────────────────────────────────────────────────
def _summarize_bandit(artifact_dir: Path) -> tuple[list[str], int, bool]:
data, error = _load(artifact_dir / "sast-results" / "bandit-results.json")
if error:
return [f"_bandit results unavailable: {error}_"], 0, False
results = data.get("results", [])
high = [r for r in results if r.get("issue_severity") == "HIGH"]
medium = [r for r in results if r.get("issue_severity") == "MEDIUM"]
low = [r for r in results if r.get("issue_severity") == "LOW"]
lines = [
f"**Bandit**: {len(high)} HIGH · {len(medium)} MEDIUM · {len(low)} LOW"
]
if high:
lines += [
"",
"| Severity | File | Line | Issue |",
"| --- | --- | --- | --- |",
]
for r in high[:10]:
fname = Path(r.get("filename", "")).name
lines.append(_md_table_row(
"HIGH", f"`{fname}`",
str(r.get("line_number", "?")),
r.get("issue_text", "")
))
if len(high) > 10:
lines.append(f"_… and {len(high) - 10} more HIGH findings_")
return lines, len(high), True
def _summarize_pip_audit(artifact_dir: Path) -> tuple[list[str], int, bool]:
data, error = _load(artifact_dir / "dependency-audit-results" / "pip-audit-results.json")
if error:
return [f"_pip-audit results unavailable: {error}_"], 0, False
# pip-audit JSON format: {"dependencies": [{"name": ..., "vulns": [...]}]}
vulns: list[dict] = []
for dep in data.get("dependencies", []):
for v in dep.get("vulns", []):
vulns.append({"package": dep.get("name", "?"), **v})
lines = [f"**pip-audit**: {len(vulns)} vulnerabilities found"]
if vulns:
lines += ["", "| Package | ID | Fix |", "| --- | --- | --- |"]
for v in vulns[:10]:
fix = v.get("fix_versions", ["none"])
fix_str = ", ".join(fix) if fix else "none"
lines.append(_md_table_row(
v.get("package", "?"),
v.get("id", "?"),
fix_str,
))
# Treat known vulnerabilities as warnings, not critical (they may be unavoidable)
return lines, 0, True
def _summarize_gitleaks(artifact_dir: Path) -> tuple[list[str], int, bool]:
data, error = _load(artifact_dir / "secrets-scan-results" / "gitleaks-results.json")
if error:
return [f"_gitleaks results unavailable: {error}_"], 0, False
if not isinstance(data, list):
data = []
real_findings = []
suppressed = 0
for finding in data:
secret_val = str(finding.get("Secret", "") or finding.get("Match", ""))
file_name = Path(finding.get("File", "")).name
if (secret_val in _GITLEAKS_SUPPRESS_EXACT_VALUES
or file_name in _GITLEAKS_SUPPRESS_PATHS):
suppressed += 1
else:
real_findings.append(finding)
lines = [
f"**Gitleaks**: {len(real_findings)} finding(s) "
f"({suppressed} suppressed as template placeholders)"
]
if real_findings:
lines += ["", "| Rule | File | Line | Description |", "| --- | --- | --- | --- |"]
for f in real_findings[:10]:
fname = Path(f.get("File", "")).name
lines.append(_md_table_row(
f.get("RuleID", "?"),
f"`{fname}`",
str(f.get("StartLine", "?")),
f.get("Description", ""),
))
critical = len(real_findings) # any real secret is critical
return lines, critical, True
def _summarize_security_proofs(artifact_dir: Path) -> tuple[list[str], int, bool]:
data, error = _load(artifact_dir / "security-proofs-results" / "security-proofs-results.json")
if error:
return [f"_security proofs results unavailable: {error}_"], 0, False
if not isinstance(data, list):
data = []
critical = [r for r in data if r.get("severity") == "CRITICAL"]
warnings = [r for r in data if r.get("severity") == "WARNING"]
passed = [r for r in data if r.get("severity") == "PASS"]
skipped = [r for r in data if r.get("severity") == "SKIP"]
lines = [
f"**Security Proofs**: "
f"{len(passed)} PASS · {len(warnings)} WARN · "
f"{len(critical)} CRITICAL · {len(skipped)} SKIP",
"",
]
_icon = {"PASS": "", "INFO": "", "WARNING": "⚠️", # nosec B105 - severity labels, not credentials
"CRITICAL": "🚨", "SKIP": "⏭️"}
for r in data:
icon = _icon.get(r.get("severity", ""), "")
lines.append(
f"- {icon} **{r.get('test_id', '?')}**: {r.get('message', '')}"
)
if r.get("details") and r.get("severity") in ("CRITICAL", "WARNING"):
lines.append(f" - _{r['details']}_")
return lines, len(critical), True
def _summarize_plugin_audit(artifact_dir: Path) -> tuple[list[str], int, bool]:
data, error = _load(artifact_dir / "plugin-audit-results" / "plugin-audit-results.json")
if error:
return [f"_plugin audit results unavailable: {error}_"], 0, False
summary = data.get("summary", {})
findings = data.get("findings", [])
critical_findings = [f for f in findings if f.get("severity") == "CRITICAL"]
warning_findings = [f for f in findings if f.get("severity") == "WARNING"]
lines = [
f"**Plugin Audit**: {data.get('plugins_scanned', '?')} plugins scanned — "
f"{summary.get('critical', 0)} CRITICAL · {summary.get('warnings', 0)} WARNINGS"
]
if critical_findings:
lines += ["", "| Plugin | File | Line | Rule | Message |",
"| --- | --- | --- | --- | --- |"]
for f in critical_findings[:10]:
fname = Path(f.get("file", "")).name
lines.append(_md_table_row(
f.get("plugin_id", "?"),
f"`{fname}`",
str(f.get("line", "?")),
f.get("rule", "?"),
f.get("message", ""),
))
if warning_findings and not critical_findings:
lines.append(f"\n_{len(warning_findings)} warning(s) found — see artifact for details_")
return lines, summary.get("critical", 0), True
# ─────────────────────────────────────────────────────────────────────────────
# Main
# ─────────────────────────────────────────────────────────────────────────────
def main() -> int:
parser = argparse.ArgumentParser(
description="Generate consolidated security audit report",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("--artifact-dir", required=True,
help="Directory containing downloaded CI artifacts")
parser.add_argument("--output", "-o", required=True,
help="Output Markdown file path")
parser.add_argument("--verbose", "-v", action="store_true")
args = parser.parse_args()
artifact_dir = Path(args.artifact_dir)
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
bandit_lines, bandit_crit, bandit_ok = _summarize_bandit(artifact_dir)
pip_audit_lines, pip_audit_crit, pip_audit_ok = _summarize_pip_audit(artifact_dir)
gitleaks_lines, gitleaks_crit, gitleaks_ok = _summarize_gitleaks(artifact_dir)
proofs_lines, proofs_crit, proofs_ok = _summarize_security_proofs(artifact_dir)
plugins_lines, plugins_crit, plugins_ok = _summarize_plugin_audit(artifact_dir)
unavailable_tools = [
name for name, ok in [
("bandit", bandit_ok), ("pip-audit", pip_audit_ok),
("gitleaks", gitleaks_ok), ("security-proofs", proofs_ok),
("plugin-audit", plugins_ok),
] if not ok
]
total_critical = bandit_crit + pip_audit_crit + gitleaks_crit + proofs_crit + plugins_crit
if unavailable_tools:
# A missing/malformed artifact means that tool's checks never
# actually ran -- this must not be reported as a clean PASS just
# because the *artifacts that did load* found nothing.
overall = "INCOMPLETE ⚠️"
elif total_critical > 0:
overall = "ACTION REQUIRED 🚨"
else:
overall = "PASSED ✅"
def section(title: str, lines: list[str]) -> str:
return f"### {title}\n\n" + "\n".join(lines) + "\n"
incomplete_note = (
f"\n_⚠️ Incomplete: results unavailable for {', '.join(unavailable_tools)} "
f"— see the corresponding section(s) below for details_\n"
if unavailable_tools else ""
)
report = f"""## 🔒 Security Audit — {overall}
_Generated: {timestamp}_
{incomplete_note}
| Critical | High/Warn | Overall |
| :---: | :---: | :---: |
| {'🚨 ' + str(total_critical) if total_critical else '✅ 0'} | see below | {overall} |
---
{section('SAST — Bandit', bandit_lines)}
{section('Dependencies — pip-audit', pip_audit_lines)}
{section('Secrets — Gitleaks', gitleaks_lines)}
{section('LEDMatrix Security Proofs', proofs_lines)}
{section('Plugin Security Audit', plugins_lines)}
---
_Total critical findings: **{total_critical}**_
"""
output_path = Path(args.output)
output_path.write_text(report, encoding="utf-8")
if args.verbose:
print(f" Report written to: {output_path}")
print(f" Status: {overall}")
print(f" Critical findings: {total_critical}")
print(f" bandit={bandit_crit} pip-audit={pip_audit_crit} "
f"gitleaks={gitleaks_crit} proofs={proofs_crit} plugins={plugins_crit}")
if unavailable_tools:
print(f" Unavailable: {', '.join(unavailable_tools)}")
if unavailable_tools:
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
-283
View File
@@ -1,283 +0,0 @@
#!/bin/bash
#
# Low-memory build helpers for the LED Matrix installer.
#
# Sourced by first_time_install.sh. These live in a separate, sourceable file
# so the pure sizing/detection functions can be unit-tested
# (test/test_install_lowmem.py); first_time_install.sh itself is not sourceable
# because it self-elevates and runs top to bottom.
#
# Why this exists: the rgbmatrix build compiles ~45 C++ translation units, two
# of them Cython-generated (a single cc1plus on those peaks around 400-800MB at
# -O3). Upstream's pyproject.toml sets no [tool.scikit-build] options, so
# scikit-build-core uses Ninja at its default of nproc+2 jobs -- six concurrent
# compiles on a 4-core Pi. On a 512MB-1GB Pi the OOM killer reaps cc1plus and
# pip reports only "Failed building wheel for rgbmatrix".
#
# The caller runs under `set -Eeuo pipefail` with an ERR trap, and these are
# invoked from the middle of numbered steps, so nothing here may call exit and
# the swap helpers must always return 0.
# Overridable so tests can point at fixture files instead of /proc.
LM_MEMINFO="${LM_MEMINFO:-/proc/meminfo}"
LM_SWAPS="${LM_SWAPS:-/proc/swaps}"
# Temporary swapfile created for the build and removed afterwards. Deliberately
# never added to /etc/fstab: a malformed fstab can leave a novice with an
# unbootable Pi, and this swap only needs to outlive the compile.
LM_SWAPFILE="${LM_SWAPFILE:-/var/swap.ledmatrix-install}"
# Bring RAM + real swap up to this much before compiling, capped per swapfile.
LM_SWAP_TARGET_MB="${LM_SWAP_TARGET_MB:-3072}"
LM_SWAP_MAX_MB="${LM_SWAP_MAX_MB:-2048}"
# Worst-case cc1plus footprint on the Cython translation unit, used to size
# build parallelism against available RAM.
LM_MB_PER_JOB="${LM_MB_PER_JOB:-768}"
# Set to 1 once swap is live, so lm_remove_build_swap (wired up as an EXIT
# trap) knows whether there is anything to undo.
LM_TEMP_SWAP_ACTIVE=0
# Human-readable reason no swapfile was created, quoted back in the failure
# message so a user who still OOMs is told why the safety net was absent.
LM_SWAP_SKIP_REASON=""
# ---------------------------------------------------------------------------
# Pure helpers (no side effects; unit-tested)
# ---------------------------------------------------------------------------
# Total physical RAM in MB, or 0 if it cannot be determined.
lm_total_ram_mb() {
# Defaults are re-resolved here as well as at source time so the function
# stays safe under the installer's `set -u`.
awk '/^MemTotal:/ {printf "%d\n", $2 / 1024; found = 1; exit} END {if (!found) print 0}' \
"${LM_MEMINFO:-/proc/meminfo}" 2>/dev/null || echo 0
}
# Total swap in MB, EXCLUDING zram devices.
#
# zram swap is compressed RAM: it consumes the very resource that is already
# exhausted and does nothing for a build OOM. Counting it would let a
# zram-enabled image decide it has enough swap and then fail exactly as before.
lm_total_swap_mb() {
awk 'NR > 1 && $1 !~ /^\/dev\/zram/ {total += $3} END {printf "%d\n", total / 1024}' \
"${LM_SWAPS:-/proc/swaps}" 2>/dev/null || echo 0
}
# lm_build_jobs <ram_mb> <cores> -> max(1, min(cores, ram_mb / LM_MB_PER_JOB))
#
# Computed from RAM alone and never RAM+swap: handing out extra jobs because
# swap exists just guarantees SD-card thrash, which is far slower than
# compiling serially.
lm_build_jobs() {
local ram_mb="${1:-0}" cores="${2:-1}" jobs
local per_job="${LM_MB_PER_JOB:-768}"
if [ "$cores" -lt 1 ]; then
cores=1
fi
jobs=$(( ram_mb / per_job ))
if [ "$jobs" -lt 1 ]; then
jobs=1
fi
if [ "$jobs" -gt "$cores" ]; then
jobs="$cores"
fi
echo "$jobs"
}
# lm_swap_needed_mb <ram_mb> <existing_swap_mb> -> swapfile size in MB, or 0.
#
# Brings RAM + real swap up to LM_SWAP_TARGET_MB, capped at LM_SWAP_MAX_MB and
# rounded up to a 256MB multiple. Machines with enough memory get 0 and are
# left completely untouched.
lm_swap_needed_mb() {
local ram_mb="${1:-0}" swap_mb="${2:-0}" needed
local target="${LM_SWAP_TARGET_MB:-3072}" max="${LM_SWAP_MAX_MB:-2048}"
needed=$(( target - ram_mb - swap_mb ))
if [ "$needed" -le 0 ]; then
echo 0
return 0
fi
if [ "$needed" -gt "$max" ]; then
needed="$max"
fi
echo $(( ( (needed + 255) / 256 ) * 256 ))
}
# lm_build_failed_on_oom <build_output_file> -> 0 if the build was OOM-killed.
#
# Two independent evidence sources, because neither alone is reliable: the
# compiler sometimes reports its own allocation failure, but when the kernel
# OOM killer fires it writes nothing to the build's stdout. That silence is
# exactly why the old handler misdiagnosed this as missing build tools.
lm_build_failed_on_oom() {
local build_output="${1:-}" kernel_log=""
if [ -n "$build_output" ] && [ -f "$build_output" ]; then
if grep -qiE 'cc1plus: out of memory|virtual memory exhausted|Cannot allocate memory|MemoryError|fatal error: Killed signal terminated program|signal 9' \
"$build_output"; then
return 0
fi
fi
# LM_KERNEL_LOG_FILE lets tests supply a fixture instead of the real kernel
# ring buffer, which on a shared CI machine may hold unrelated OOM events.
if [ -n "${LM_KERNEL_LOG_FILE:-}" ]; then
if [ -f "$LM_KERNEL_LOG_FILE" ]; then
kernel_log=$(cat "$LM_KERNEL_LOG_FILE" 2>/dev/null || true)
fi
elif command -v dmesg >/dev/null 2>&1; then
kernel_log=$(dmesg -T 2>/dev/null || dmesg 2>/dev/null || true)
fi
if [ -z "$kernel_log" ] && [ -z "${LM_KERNEL_LOG_FILE:-}" ] && command -v journalctl >/dev/null 2>&1; then
kernel_log=$(journalctl -k --since "30 min ago" --no-pager 2>/dev/null || true)
fi
if [ -n "$kernel_log" ]; then
if printf '%s\n' "$kernel_log" | tail -n 300 | \
grep -qiE 'Out of memory: Kill|oom_kill|oom-kill|Killed process'; then
return 0
fi
fi
return 1
}
# lm_disk_backed_tmpdir [candidate] -> a disk-backed temp dir, or nothing.
#
# pip builds in $TMPDIR. Debian 13 mounts /tmp as tmpfs, so the default puts the
# whole C++ build tree in RAM, competing with the compiler we are already trying
# to keep under the limit. Prints a replacement only when the current TMPDIR is
# memory-backed and the candidate is not; otherwise prints nothing and the
# caller keeps its default.
lm_disk_backed_tmpdir() {
local candidate="${1:-/var/tmp}"
local current="${TMPDIR:-/tmp}"
local current_fs="" candidate_fs=""
current_fs=$(lm_fstype_of "$current")
case "$current_fs" in
tmpfs|ramfs) ;;
*) return 0 ;;
esac
candidate_fs=$(lm_fstype_of "$candidate")
case "$candidate_fs" in
tmpfs|ramfs|"") return 0 ;;
esac
echo "$candidate"
}
# Filesystem type backing a path, or empty if it cannot be determined.
lm_fstype_of() {
local path="${1:-/}"
if command -v findmnt >/dev/null 2>&1; then
findmnt -no FSTYPE --target "$path" 2>/dev/null | head -n 1
return 0
fi
if command -v stat >/dev/null 2>&1; then
stat -f -c %T "$path" 2>/dev/null | head -n 1
return 0
fi
return 0
}
# ---------------------------------------------------------------------------
# Swap management (requires root; not unit-tested)
# ---------------------------------------------------------------------------
# lm_ensure_build_swap <needed_mb>
#
# Always returns 0. On any refusal it sets LM_SWAP_SKIP_REASON and leaves the
# system untouched -- swap is a safety net for the build, never a precondition.
lm_ensure_build_swap() {
local needed_mb="${1:-0}"
local swap_dir free_mb budget
LM_SWAP_SKIP_REASON=""
if [ "$needed_mb" -le 0 ]; then
LM_SWAP_SKIP_REASON="not needed (RAM and existing swap are sufficient)"
return 0
fi
if ! command -v mkswap >/dev/null 2>&1 || ! command -v swapon >/dev/null 2>&1; then
LM_SWAP_SKIP_REASON="mkswap/swapon are not available on this system"
echo "⚠ Cannot add build swap: $LM_SWAP_SKIP_REASON"
return 0
fi
# Clear a stale swapfile left by a run that was killed before its cleanup
# ran, so this is safe to call repeatedly.
if [ -e "$LM_SWAPFILE" ]; then
echo "Removing a leftover swapfile from a previous run: $LM_SWAPFILE"
swapoff "$LM_SWAPFILE" >/dev/null 2>&1 || true
rm -f "$LM_SWAPFILE" || true
fi
# Keep a working margin for the build tree itself; never eat the last GB.
swap_dir=$(dirname "$LM_SWAPFILE")
free_mb=$(df -m "$swap_dir" 2>/dev/null | awk 'NR==2{print $4}')
free_mb=${free_mb:-0}
budget=$(( free_mb - 1024 ))
if [ "$budget" -lt 256 ]; then
LM_SWAP_SKIP_REASON="only ${free_mb}MB free on ${swap_dir}, need about $(( needed_mb + 1024 ))MB"
echo "⚠ Skipping the build swapfile: $LM_SWAP_SKIP_REASON"
return 0
fi
if [ "$needed_mb" -gt "$budget" ]; then
echo "⚠ Trimming the build swapfile from ${needed_mb}MB to leave 1GB free on ${swap_dir}"
needed_mb=$(( ( budget / 256 ) * 256 ))
fi
echo "Adding a temporary ${needed_mb}MB swapfile for the build: $LM_SWAPFILE"
echo " This is removed automatically once the build finishes."
# fallocate can produce a sparse file that mkswap rejects, and is not
# supported on every filesystem; dd always yields a usable file.
if ! fallocate -l "${needed_mb}M" "$LM_SWAPFILE" 2>/dev/null; then
if ! dd if=/dev/zero of="$LM_SWAPFILE" bs=1M count="$needed_mb" status=none 2>/dev/null; then
LM_SWAP_SKIP_REASON="could not allocate ${needed_mb}MB at $LM_SWAPFILE"
echo "$LM_SWAP_SKIP_REASON"
rm -f "$LM_SWAPFILE" || true
return 0
fi
fi
chmod 600 "$LM_SWAPFILE" || true
if ! mkswap "$LM_SWAPFILE" >/dev/null 2>&1; then
LM_SWAP_SKIP_REASON="mkswap failed on $LM_SWAPFILE"
echo "$LM_SWAP_SKIP_REASON"
rm -f "$LM_SWAPFILE" || true
return 0
fi
if ! swapon "$LM_SWAPFILE" >/dev/null 2>&1; then
LM_SWAP_SKIP_REASON="swapon failed on $LM_SWAPFILE"
echo "$LM_SWAP_SKIP_REASON"
rm -f "$LM_SWAPFILE" || true
return 0
fi
LM_TEMP_SWAP_ACTIVE=1
echo "✓ Temporary build swap active (${needed_mb}MB; total swap is now $(lm_total_swap_mb)MB)"
return 0
}
# Remove the temporary swapfile. Safe to call unconditionally and repeatedly.
#
# Wired up as an EXIT trap, so it must never return non-zero -- a failing trap
# would surface as a spurious installer error.
lm_remove_build_swap() {
if [ "${LM_TEMP_SWAP_ACTIVE:-0}" != "1" ]; then
return 0
fi
LM_TEMP_SWAP_ACTIVE=0
echo "Removing the temporary build swapfile: $LM_SWAPFILE"
swapoff "$LM_SWAPFILE" >/dev/null 2>&1 || true
rm -f "$LM_SWAPFILE" || true
return 0
}
+3 -39
View File
@@ -145,34 +145,6 @@ check_disk_space() {
fi fi
} }
# Report available memory so the user knows what to expect before the wait.
#
# Informational only — first_time_install.sh does the real work of capping
# build parallelism and adding temporary swap. Never fatal: a low-RAM Pi is
# supported, it is just slower.
check_memory() {
CURRENT_STEP="Memory check"
if [ ! -r /proc/meminfo ]; then
print_warning "Cannot read /proc/meminfo, skipping memory check"
return 0
fi
TOTAL_RAM_MB=$(awk '/^MemTotal:/ {printf "%d\n", $2 / 1024; exit}' /proc/meminfo 2>/dev/null || echo 0)
TOTAL_RAM_MB=${TOTAL_RAM_MB:-0}
if [ "$TOTAL_RAM_MB" -eq 0 ]; then
print_warning "Could not determine system memory, continuing"
elif [ "$TOTAL_RAM_MB" -lt 2048 ]; then
print_warning "Low memory: ${TOTAL_RAM_MB}MB RAM"
echo " The rpi-rgb-led-matrix C++ build needs more memory than this Pi has."
echo " The installer will compile with fewer parallel jobs and add a temporary"
echo " swapfile for the build, removing it afterwards. That step will take"
echo " 15-25 minutes rather than the usual 2-5."
else
print_success "Memory sufficient: ${TOTAL_RAM_MB}MB RAM"
fi
}
# Ensure sudo access # Ensure sudo access
check_sudo() { check_sudo() {
CURRENT_STEP="Sudo access check" CURRENT_STEP="Sudo access check"
@@ -232,7 +204,7 @@ main() {
print_step "LED Matrix One-Shot Installation" print_step "LED Matrix One-Shot Installation"
echo "This script will:" echo "This script will:"
echo " 1. Check prerequisites (network, disk space, memory, sudo)" echo " 1. Check prerequisites (network, disk space, sudo)"
echo " 2. Install system dependencies (git, python3, build tools)" echo " 2. Install system dependencies (git, python3, build tools)"
echo " 3. Clone the LEDMatrix repository" echo " 3. Clone the LEDMatrix repository"
echo " 4. Run the first-time installation script" echo " 4. Run the first-time installation script"
@@ -241,7 +213,6 @@ main() {
# Check prerequisites # Check prerequisites
check_network check_network
check_disk_space check_disk_space
check_memory
check_sudo check_sudo
# Note: /tmp permissions are checked and fixed inline before running first_time_install.sh # Note: /tmp permissions are checked and fixed inline before running first_time_install.sh
# (only if actually wrong, not preemptively) # (only if actually wrong, not preemptively)
@@ -257,14 +228,12 @@ main() {
exit 1 exit 1
fi fi
# Update package list first. first_time_install.sh is told the lists are # Update package list first
# already fresh so it does not repeat this a minute later.
if [ "$EUID" -eq 0 ]; then if [ "$EUID" -eq 0 ]; then
retry apt-get update -qq retry apt-get update -qq
else else
retry sudo apt-get update -qq retry sudo apt-get update -qq
fi fi
export LEDMATRIX_APT_UPDATED=1
# Install git and curl (needed for cloning and the script itself) # Install git and curl (needed for cloning and the script itself)
if ! command -v git >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1; then if ! command -v git >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1; then
@@ -403,12 +372,7 @@ main() {
# Pass both -y flag AND environment variable for non-interactive mode # Pass both -y flag AND environment variable for non-interactive mode
# This ensures it works even if the script re-executes itself with sudo # This ensures it works even if the script re-executes itself with sudo
# Also ensure stdin is properly handled for non-interactive mode # Also ensure stdin is properly handled for non-interactive mode
# LEDMATRIX_APT_UPDATED is passed explicitly rather than relying on sudo -E env TMPDIR=/tmp LEDMATRIX_ASSUME_YES=1 bash ./first_time_install.sh -y </dev/null
# -E: a sudoers env_reset/env_keep policy can strip exported variables,
# which would silently reinstate the duplicate apt update.
sudo -E env TMPDIR=/tmp LEDMATRIX_ASSUME_YES=1 \
LEDMATRIX_APT_UPDATED="${LEDMATRIX_APT_UPDATED:-0}" \
bash ./first_time_install.sh -y </dev/null
fi fi
INSTALL_EXIT_CODE=$? INSTALL_EXIT_CODE=$?
trap 'on_error $LINENO' ERR # Re-enable ERR trap trap 'on_error $LINENO' ERR # Re-enable ERR trap
+28 -49
View File
@@ -44,12 +44,17 @@ def install_via_apt(package_name: str) -> Tuple[bool, str]:
apt_package_map = { apt_package_map = {
'flask': 'python3-flask', 'flask': 'python3-flask',
'PIL': 'python3-pil', 'PIL': 'python3-pil',
'freetype-py': 'python3-freetype', 'freetype': 'python3-freetype',
'psutil': 'python3-psutil', 'psutil': 'python3-psutil',
'werkzeug': 'python3-werkzeug', 'werkzeug': 'python3-werkzeug',
'numpy': 'python3-numpy', 'numpy': 'python3-numpy',
'requests': 'python3-requests', 'requests': 'python3-requests',
'pytz': 'python3-tz' 'python-dateutil': 'python3-dateutil',
'pytz': 'python3-tz',
'geopy': 'python3-geopy',
'unidecode': 'python3-unidecode',
'websockets': 'python3-websockets',
'websocket-client': 'python3-websocket-client'
} }
apt_package = apt_package_map.get(package_name, f'python3-{package_name}') apt_package = apt_package_map.get(package_name, f'python3-{package_name}')
@@ -76,8 +81,8 @@ def install_via_pip(package_name: str) -> Tuple[bool, str]:
pip RECORD file, so an uninstall attempt fails with "uninstall-no-record-file" pip RECORD file, so an uninstall attempt fails with "uninstall-no-record-file"
and aborts the whole install. With --ignore-installed, pip lays the new and aborts the whole install. With --ignore-installed, pip lays the new
version down in /usr/local where it shadows the apt copy instead of removing version down in /usr/local where it shadows the apt copy instead of removing
it. This matters when a pip dependency needs to upgrade an apt-managed it. This matters when a pip dependency (google-api-python-client pulls a
package (e.g. a package that pulls a newer requests). newer requests) needs to upgrade an apt-managed package.
Returns (success, output). Returns (success, output).
""" """
@@ -96,35 +101,13 @@ def install_via_pip(package_name: str) -> Tuple[bool, str]:
# Distribution (pip/apt) names whose importable module name differs. # Distribution (pip/apt) names whose importable module name differs.
IMPORT_NAME_MAP = { IMPORT_NAME_MAP = {
'freetype-py': 'freetype', 'python-dateutil': 'dateutil',
'websocket-client': 'websocket',
} }
# Minimum versions that must be met for an already-installed package to count
# as satisfied. Debian Bookworm's python3-freetype is 2.3.0, below the
# freetype-py>=2.5.1 pin in requirements.txt, so an import-only check would
# wrongly skip the pip upgrade.
MIN_VERSIONS = {
'freetype-py': (2, 5, 1),
}
def _installed_version_tuple(dist_name: str) -> tuple:
"""Return the installed distribution version as an int tuple, or () if unknown."""
try:
from importlib.metadata import version
parts = []
for part in version(dist_name).split('.'):
digits = ''.join(ch for ch in part if ch.isdigit())
if not digits:
break
parts.append(int(digits))
return tuple(parts)
except Exception:
return ()
def check_package_installed(package_name: str) -> bool: def check_package_installed(package_name: str) -> bool:
"""Check if a package is already installed (and meets any minimum version).""" """Check if a package is already installed."""
import_name = IMPORT_NAME_MAP.get(package_name, package_name) import_name = IMPORT_NAME_MAP.get(package_name, package_name)
# Suppress deprecation warnings when checking if packages are installed # Suppress deprecation warnings when checking if packages are installed
# (we're just checking, not using them) # (we're just checking, not using them)
@@ -132,16 +115,9 @@ def check_package_installed(package_name: str) -> bool:
warnings.filterwarnings('ignore', category=DeprecationWarning) warnings.filterwarnings('ignore', category=DeprecationWarning)
try: try:
__import__(import_name) __import__(import_name)
return True
except ImportError: except ImportError:
return False return False
minimum = MIN_VERSIONS.get(package_name)
if minimum:
installed = _installed_version_tuple(package_name)
if not installed or installed < minimum:
print(f"{package_name} is installed but below the required "
f"{'.'.join(map(str, minimum))}; will upgrade via pip")
return False
return True
def print_failure_summary(failed_packages: List[str], failure_details: dict) -> None: def print_failure_summary(failed_packages: List[str], failure_details: dict) -> None:
@@ -171,12 +147,17 @@ def main():
required_packages = [ required_packages = [
'flask', 'flask',
'PIL', 'PIL',
'freetype-py', 'freetype',
'psutil', 'psutil',
'werkzeug', 'werkzeug',
'numpy', 'numpy',
'requests', 'requests',
'pytz' 'python-dateutil',
'pytz',
'geopy',
'unidecode',
'websockets',
'websocket-client'
] ]
failed_packages = [] failed_packages = []
@@ -187,13 +168,8 @@ def main():
print(f"{package} is already installed") print(f"{package} is already installed")
continue continue
# Try apt first, then pip. An apt install only counts if it also # Try apt first, then pip
# satisfies any minimum version (Debian's python3-freetype can be
# older than the freetype-py pin), otherwise fall through to pip.
ok, apt_output = install_via_apt(package) ok, apt_output = install_via_apt(package)
if ok and package in MIN_VERSIONS and not check_package_installed(package):
ok = False
apt_output = f"apt version of {package} is below the required minimum"
if not ok: if not ok:
ok, pip_output = install_via_pip(package) ok, pip_output = install_via_pip(package)
if not ok: if not ok:
@@ -201,12 +177,15 @@ def main():
failure_details[package] = pip_output or apt_output failure_details[package] = pip_output or apt_output
# Install packages that don't have apt equivalents # Install packages that don't have apt equivalents
# Packages without apt equivalents. Plugin-specific dependencies
# (timezonefinder, google-api stack, icalevents, socketio, ...) are
# no longer installed here — store plugins declare their own
# requirements.txt, which the plugin store installs.
special_packages = [ special_packages = [
'timezonefinder>=6.5.0,<7.0.0',
'google-auth-oauthlib>=1.2.0,<2.0.0',
'google-auth-httplib2>=0.2.0,<1.0.0',
'google-api-python-client>=2.147.0,<3.0.0',
'spotipy', 'spotipy',
'icalevents',
'python-socketio>=5.11.0,<6.0.0',
'python-engineio>=4.9.0,<5.0.0'
] ]
for package in special_packages: for package in special_packages:
+117
View File
@@ -0,0 +1,117 @@
#!/bin/bash
# Script to safely remove plugin backup directories
# These were created during the plugin-to-submodule conversion
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PLUGINS_DIR="$PROJECT_ROOT/plugins"
# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Verify submodules are working
verify_submodules() {
log_info "Verifying submodules are working..."
local issues=0
for submod in football-scoreboard hockey-scoreboard ledmatrix-flights \
ledmatrix-leaderboard ledmatrix-stocks ledmatrix-weather \
mqtt-notifications; do
if [ ! -d "$PLUGINS_DIR/$submod" ]; then
log_error "Submodule directory missing: $submod"
issues=$((issues + 1))
elif [ ! -f "$PLUGINS_DIR/$submod/.git" ]; then
log_error "Submodule .git file missing: $submod"
issues=$((issues + 1))
elif [ ! -f "$PLUGINS_DIR/$submod/manifest.json" ]; then
log_warn "Submodule manifest missing: $submod (may be OK)"
fi
done
if [ $issues -eq 0 ]; then
log_info "All submodules verified ✓"
return 0
else
log_error "Found $issues issues with submodules"
return 1
fi
}
# Remove backup directories
remove_backups() {
log_info "Removing backup directories..."
local removed=0
local total_size=0
for backup in "$PLUGINS_DIR"/*.backup*; do
if [ -d "$backup" ]; then
local name=$(basename "$backup")
local size=$(du -sb "$backup" 2>/dev/null | awk '{print $1}')
total_size=$((total_size + size))
log_info "Removing: $name"
rm -rf "$backup"
removed=$((removed + 1))
fi
done
if [ $removed -gt 0 ]; then
log_info "Removed $removed backup directory(ies)"
log_info "Freed approximately $(numfmt --to=iec-i --suffix=B $total_size 2>/dev/null || echo "$total_size bytes")"
else
log_info "No backup directories found"
fi
}
# Main
main() {
cd "$PROJECT_ROOT"
echo "=== Plugin Backup Removal Script ==="
echo
# Verify submodules first
if ! verify_submodules; then
log_error "Submodule verification failed. Not removing backups."
log_warn "Please fix submodule issues before removing backups."
exit 1
fi
echo
log_warn "This will permanently delete backup directories:"
ls -1d "$PLUGINS_DIR"/*.backup* 2>/dev/null | sed 's|.*/| - |' || echo " (none found)"
echo
read -p "Continue? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
log_info "Aborted"
exit 0
fi
remove_backups
log_info "Done!"
}
main "$@"
+3 -3
View File
@@ -8,10 +8,10 @@ import os
import sys import sys
import argparse import argparse
# Add the project root to the path so we can import our modules # Add the src directory to the path so we can import our modules
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from src.cache_manager import CacheManager from cache_manager import CacheManager
def list_cache_keys(cache_manager): def list_cache_keys(cache_manager):
"""List all available cache keys.""" """List all available cache keys."""
+1 -1
View File
@@ -4,5 +4,5 @@ LEDMatrix Display System
Core source package for the LED Matrix Display project. Core source package for the LED Matrix Display project.
""" """
__version__ = "3.2.0" __version__ = "3.1.0"
+8 -98
View File
@@ -16,7 +16,6 @@ import json
import logging import logging
import os import os
import shutil import shutil
import stat
import socket import socket
import tempfile import tempfile
import zipfile import zipfile
@@ -83,10 +82,6 @@ BUNDLED_FONTS: frozenset[str] = frozenset({
_CONFIG_REL = Path("config/config.json") _CONFIG_REL = Path("config/config.json")
_SECRETS_REL = Path("config/config_secrets.json") _SECRETS_REL = Path("config/config_secrets.json")
_WIFI_REL = Path("config/wifi_config.json") _WIFI_REL = Path("config/wifi_config.json")
# Sits in config/ next to the three above and is pure user state — a
# YouTube Music session that has to be re-authenticated by hand if lost.
# It was omitted from backups, so a restore silently signed the user out.
_YTM_REL = Path("config/ytm_auth.json")
_FONTS_REL = Path("assets/fonts") _FONTS_REL = Path("assets/fonts")
_PLUGIN_UPLOADS_REL = Path("assets/plugins") _PLUGIN_UPLOADS_REL = Path("assets/plugins")
_STATE_REL = Path("data/plugin_state.json") _STATE_REL = Path("data/plugin_state.json")
@@ -308,9 +303,6 @@ def create_backup(
if (project_root / _WIFI_REL).exists(): if (project_root / _WIFI_REL).exists():
zf.write(project_root / _WIFI_REL, _WIFI_REL.as_posix()) zf.write(project_root / _WIFI_REL, _WIFI_REL.as_posix())
contents.append("wifi") contents.append("wifi")
if (project_root / _YTM_REL).exists():
zf.write(project_root / _YTM_REL, _YTM_REL.as_posix())
contents.append("ytm_auth")
# User-uploaded fonts. # User-uploaded fonts.
user_fonts = iter_user_fonts(project_root) user_fonts = iter_user_fonts(project_root)
@@ -356,7 +348,6 @@ def preview_backup_contents(project_root: Path) -> Dict[str, Any]:
"has_config": (project_root / _CONFIG_REL).exists(), "has_config": (project_root / _CONFIG_REL).exists(),
"has_secrets": (project_root / _SECRETS_REL).exists(), "has_secrets": (project_root / _SECRETS_REL).exists(),
"has_wifi": (project_root / _WIFI_REL).exists(), "has_wifi": (project_root / _WIFI_REL).exists(),
"has_ytm_auth": (project_root / _YTM_REL).exists(),
"user_fonts": [p.name for p in iter_user_fonts(project_root)], "user_fonts": [p.name for p in iter_user_fonts(project_root)],
"plugin_uploads": len(iter_plugin_uploads(project_root)), "plugin_uploads": len(iter_plugin_uploads(project_root)),
"plugins": list_installed_plugins(project_root), "plugins": list_installed_plugins(project_root),
@@ -438,8 +429,6 @@ def validate_backup(zip_path: Path) -> Tuple[bool, str, Dict[str, Any]]:
detected.append("secrets") detected.append("secrets")
if _WIFI_REL.as_posix() in names: if _WIFI_REL.as_posix() in names:
detected.append("wifi") detected.append("wifi")
if _YTM_REL.as_posix() in names:
detected.append("ytm_auth")
if any(n.startswith(_FONTS_REL.as_posix() + "/") for n in names): if any(n.startswith(_FONTS_REL.as_posix() + "/") for n in names):
detected.append("fonts") detected.append("fonts")
if any( if any(
@@ -492,61 +481,8 @@ def _extract_zip_safe(zip_path: Path, dest_dir: Path) -> None:
def _copy_file(src: Path, dst: Path) -> None: def _copy_file(src: Path, dst: Path) -> None:
"""Replace ``dst`` with ``src``, atomically, without needing to own ``dst``.
``shutil.copy2`` opens the destination for writing, so it needs write
permission on the *existing file*. Several config files are installed
root-owned and group-readable while the web interface which is what runs
a restore deliberately runs as a non-root user. Restoring those failed
with EACCES even though the account could create files in the same
directory perfectly well.
Writing a temporary file alongside and renaming over the target needs only
directory permission, which the web user has. It is also atomic: a crash
mid-restore can no longer leave a half-written config behind.
The destination's existing mode is preserved when there is one, so
restoring secrets does not silently widen them to the umask default.
"""
dst.parent.mkdir(parents=True, exist_ok=True) dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dst)
existing_mode: Optional[int] = None
existing_owner: Optional[Tuple[int, int]] = None
if dst.exists():
try:
info = dst.stat()
existing_mode = stat.S_IMODE(info.st_mode)
existing_owner = (info.st_uid, info.st_gid)
except OSError:
existing_mode = None
existing_owner = None
fd, tmp_name = tempfile.mkstemp(dir=str(dst.parent), prefix=f".{dst.name}.", suffix=".tmp")
os.close(fd)
tmp_path = Path(tmp_name)
try:
shutil.copyfile(src, tmp_path)
if existing_mode is not None:
os.chmod(tmp_path, existing_mode)
else:
shutil.copymode(src, tmp_path)
if existing_owner is not None:
# Replacing a file creates a new inode owned by whoever is running,
# which would silently move a root-owned config to the web user.
# Carry the previous owner across when the OS permits it — only
# root can hand a file to another user, so this is best-effort and
# a plain restore as the web user simply keeps its own ownership.
try:
os.chown(tmp_path, existing_owner[0], existing_owner[1])
except (OSError, PermissionError):
pass
os.replace(tmp_path, dst)
except BaseException:
try:
tmp_path.unlink()
except OSError:
pass
raise
def restore_backup( def restore_backup(
@@ -577,8 +513,7 @@ def restore_backup(
try: try:
_extract_zip_safe(Path(zip_path), tmp_dir) _extract_zip_safe(Path(zip_path), tmp_dir)
except (ValueError, zipfile.BadZipFile, OSError) as e: except (ValueError, zipfile.BadZipFile, OSError) as e:
logger.error("[Backup] Failed to extract backup: %s", e, exc_info=True) result.errors.append(f"Failed to extract backup: {e}")
result.errors.append("Failed to extract backup")
return result return result
# Main config. # Main config.
@@ -587,8 +522,7 @@ def restore_backup(
_copy_file(tmp_dir / _CONFIG_REL, project_root / _CONFIG_REL) _copy_file(tmp_dir / _CONFIG_REL, project_root / _CONFIG_REL)
result.restored.append("config") result.restored.append("config")
except OSError as e: except OSError as e:
logger.error("[Backup] Failed to restore config.json: %s", e, exc_info=True) result.errors.append(f"Failed to restore config.json: {e}")
result.errors.append("Failed to restore config.json")
elif (tmp_dir / _CONFIG_REL).exists(): elif (tmp_dir / _CONFIG_REL).exists():
result.skipped.append("config") result.skipped.append("config")
@@ -598,10 +532,7 @@ def restore_backup(
_copy_file(tmp_dir / _SECRETS_REL, project_root / _SECRETS_REL) _copy_file(tmp_dir / _SECRETS_REL, project_root / _SECRETS_REL)
result.restored.append("secrets") result.restored.append("secrets")
except OSError as e: except OSError as e:
logger.error( result.errors.append(f"Failed to restore config_secrets.json: {e}")
"[Backup] Failed to restore config_secrets.json: %s", e, exc_info=True
)
result.errors.append("Failed to restore config_secrets.json")
elif (tmp_dir / _SECRETS_REL).exists(): elif (tmp_dir / _SECRETS_REL).exists():
result.skipped.append("secrets") result.skipped.append("secrets")
@@ -611,26 +542,10 @@ def restore_backup(
_copy_file(tmp_dir / _WIFI_REL, project_root / _WIFI_REL) _copy_file(tmp_dir / _WIFI_REL, project_root / _WIFI_REL)
result.restored.append("wifi") result.restored.append("wifi")
except OSError as e: except OSError as e:
logger.error( result.errors.append(f"Failed to restore wifi_config.json: {e}")
"[Backup] Failed to restore wifi_config.json: %s", e, exc_info=True
)
result.errors.append("Failed to restore wifi_config.json")
elif (tmp_dir / _WIFI_REL).exists(): elif (tmp_dir / _WIFI_REL).exists():
result.skipped.append("wifi") result.skipped.append("wifi")
# YouTube Music session. Follows restore_wifi rather than getting its
# own flag: it is device-local auth in the same sense, and a separate
# toggle for one file would be noise in the restore dialog.
if options.restore_wifi and (tmp_dir / _YTM_REL).exists():
try:
_copy_file(tmp_dir / _YTM_REL, project_root / _YTM_REL)
result.restored.append("ytm_auth")
except OSError as e:
logger.error("[Backup] Failed to restore ytm_auth.json: %s", e, exc_info=True)
result.errors.append("Failed to restore ytm_auth.json")
elif (tmp_dir / _YTM_REL).exists():
result.skipped.append("ytm_auth")
# User fonts — skip anything that collides with a bundled font. # User fonts — skip anything that collides with a bundled font.
tmp_fonts = tmp_dir / _FONTS_REL tmp_fonts = tmp_dir / _FONTS_REL
if options.restore_fonts and tmp_fonts.exists(): if options.restore_fonts and tmp_fonts.exists():
@@ -645,10 +560,7 @@ def restore_backup(
_copy_file(font, project_root / _FONTS_REL / font.name) _copy_file(font, project_root / _FONTS_REL / font.name)
restored_count += 1 restored_count += 1
except OSError as e: except OSError as e:
logger.error( result.errors.append(f"Failed to restore font {font.name}: {e}")
"[Backup] Failed to restore font %s: %s", font.name, e, exc_info=True
)
result.errors.append(f"Failed to restore font {font.name}")
if restored_count: if restored_count:
result.restored.append(f"fonts ({restored_count})") result.restored.append(f"fonts ({restored_count})")
elif tmp_fonts.exists(): elif tmp_fonts.exists():
@@ -669,8 +581,7 @@ def restore_backup(
_copy_file(src, project_root / rel) _copy_file(src, project_root / rel)
count += 1 count += 1
except OSError as e: except OSError as e:
logger.error("[Backup] Failed to restore %s: %s", rel, e, exc_info=True) result.errors.append(f"Failed to restore {rel}: {e}")
result.errors.append(f"Failed to restore {rel}")
if count: if count:
result.restored.append(f"plugin_uploads ({count})") result.restored.append(f"plugin_uploads ({count})")
elif tmp_uploads.exists(): elif tmp_uploads.exists():
@@ -688,8 +599,7 @@ def restore_backup(
if isinstance(p, dict) and p.get("plugin_id") if isinstance(p, dict) and p.get("plugin_id")
] ]
except (OSError, json.JSONDecodeError) as e: except (OSError, json.JSONDecodeError) as e:
logger.error("[Backup] Could not read plugins.json: %s", e, exc_info=True) result.errors.append(f"Could not read plugins.json: {e}")
result.errors.append("Could not read plugins.json")
result.success = not result.errors result.success = not result.errors
return result return result
+3 -14
View File
@@ -151,12 +151,7 @@ class Baseball(SportsCore):
# Only log detailed information for favorite teams # Only log detailed information for favorite teams
if is_favorite_game: if is_favorite_game:
# Use the validated competition-level `status` here too. MiLB self.logger.debug(f"Full status data: {game_event['status']}")
# events carry no event-level one, so this debug line raised a
# KeyError and dropped the very games it was meant to help
# diagnose -- and only for favourites, which is the worst way
# for it to fail.
self.logger.debug(f"Full status data: {status}")
self.logger.debug(f"Status type: {game_status}, State: {status_state}") self.logger.debug(f"Status type: {game_status}, State: {status_state}")
self.logger.debug(f"Status detail: {status['type'].get('detail', '')}") self.logger.debug(f"Status detail: {status['type'].get('detail', '')}")
self.logger.debug( self.logger.debug(
@@ -169,13 +164,7 @@ class Baseball(SportsCore):
# Get game state information # Get game state information
if status_state == "in": if status_state == "in":
# For live games, get detailed state # For live games, get detailed state
# Use the competition-level `status` already validated by inning = game_event["status"].get(
# _extract_game_details_common. Real ESPN events duplicate
# status at the event top level, but MiLB events (synthesized
# from the MLB Stats API into an ESPN-like shape) populate
# only the competition-level one, so the top-level lookup
# raised a bare KeyError and dropped the event.
inning = status.get(
"period", 1 "period", 1
) # Get inning from status period ) # Get inning from status period
@@ -198,7 +187,7 @@ class Baseball(SportsCore):
if "end" in status_detail or "end" in status_short: if "end" in status_detail or "end" in status_short:
inning_half = "top" inning_half = "top"
inning = ( inning = (
status.get("period", 1) + 1 game_event["status"].get("period", 1) + 1
) # Use period and increment for next inning ) # Use period and increment for next inning
if is_favorite_game: if is_favorite_game:
self.logger.debug( self.logger.debug(
+2 -9
View File
@@ -44,16 +44,9 @@ class DataSource(ABC):
"""Fetch standings for a sport/league.""" """Fetch standings for a sport/league."""
def get_headers(self) -> Dict[str, str]: def get_headers(self) -> Dict[str, str]:
"""Get headers for API requests. """Get headers for API requests."""
The agent carries the project URL deliberately. Around 2026-08-04 ESPN
began returning 403 for bare custom tokens like 'LEDMatrix/1.0' and
for browser-style strings while accepting an agent that identifies
the client and links to it. An Accept header alone does not rescue the
bare form when the request goes out through requests.
"""
return { return {
'User-Agent': 'LEDMatrix/1.0 (+https://github.com/ChuckBuilds/LEDMatrix)', 'User-Agent': 'LEDMatrix/1.0',
'Accept': 'application/json' 'Accept': 'application/json'
} }
+4 -11
View File
@@ -38,17 +38,10 @@ class Hockey(SportsCore):
status = competition["status"] status = competition["status"]
powerplay = False powerplay = False
penalties = "" penalties = ""
# A competitor may legitimately arrive without a "statistics"
# array (pre-game feeds, and some in-progress ones). Reading it
# unguarded raised KeyError inside the generator and dropped the
# WHOLE event, discarding valid scores and status. Default to an
# empty list so the saves/shots figures fall back to 0 instead.
home_stats = home_team.get("statistics", [])
away_stats = away_team.get("statistics", [])
home_team_saves = next( home_team_saves = next(
( (
int(c["displayValue"]) int(c["displayValue"])
for c in home_stats for c in home_team["statistics"]
if c.get("name") == "saves" if c.get("name") == "saves"
), ),
0, 0,
@@ -56,7 +49,7 @@ class Hockey(SportsCore):
home_team_saves_per = next( home_team_saves_per = next(
( (
float(c["displayValue"]) float(c["displayValue"])
for c in home_stats for c in home_team["statistics"]
if c.get("name") == "savePct" if c.get("name") == "savePct"
), ),
0.0, 0.0,
@@ -64,7 +57,7 @@ class Hockey(SportsCore):
away_team_saves = next( away_team_saves = next(
( (
int(c["displayValue"]) int(c["displayValue"])
for c in away_stats for c in away_team["statistics"]
if c.get("name") == "saves" if c.get("name") == "saves"
), ),
0, 0,
@@ -72,7 +65,7 @@ class Hockey(SportsCore):
away_team_saves_per = next( away_team_saves_per = next(
( (
float(c["displayValue"]) float(c["displayValue"])
for c in away_stats for c in away_team["statistics"]
if c.get("name") == "savePct" if c.get("name") == "savePct"
), ),
0.0, 0.0,
File diff suppressed because it is too large Load Diff
-17
View File
@@ -1,17 +0,0 @@
"""Sports scoreboard base classes.
Formerly the single module ``src/base_classes/sports.py``; now a package so
capabilities can be composed instead of accumulating in one class. See
docs/SPORTS_UNIFICATION.md for the architecture. The import path is
unchanged: ``from src.base_classes.sports import SportsCore`` still works.
"""
from .core import SportsCore
from .modes import SportsLive, SportsRecent, SportsUpcoming
__all__ = [
"SportsCore",
"SportsUpcoming",
"SportsRecent",
"SportsLive",
]
@@ -1,32 +0,0 @@
"""Opt-in capabilities for the sports scoreboards.
Each module here is a feature that only *some* sports want. They are composed
by inheritance (mixins) or selected by name (strategies) never enabled by an
``if self.<feature>_enabled:`` branch inside the base classes.
The distinction matters: hockey has no celebrations, so ``HockeyLive`` does not
inherit :class:`~.celebrations.CelebrationMixin` and the celebration code is not
in hockey's MRO at all. A bug in it cannot reach a plugin that never opted in.
See ``docs/SPORTS_UNIFICATION.md`` for the full rationale.
"""
from .celebrations import CelebrationMixin
from .rotation import (
RotationStrategy,
SimpleRotation,
SmoothWeightedRotation,
WeightedCycleRotation,
get_rotation_strategy,
register_rotation_strategy,
)
__all__ = [
"CelebrationMixin",
"RotationStrategy",
"SimpleRotation",
"SmoothWeightedRotation",
"WeightedCycleRotation",
"get_rotation_strategy",
"register_rotation_strategy",
]
@@ -1,418 +0,0 @@
"""Score / win celebration takeover — an opt-in capability.
Four of the nine scoreboards celebrate (afl, nrl, soccer, football); the other
five do not. This is a **mixin** rather than a flag inside ``SportsLive`` so the
five that do not opt in have none of this code in their MRO: a bug here cannot
reach hockey, and hockey's config never grows keys it ignores.
Usage mix in *before* the mode class so its ``display`` runs first::
class SoccerLive(CelebrationMixin, SportsLive):
def score_phrase(self, points, team_abbr):
return secrets.choice(("GOOOOAAALLL!", f"{team_abbr} SCORES!"))
The two lineages spelled this differently (``_check_for_goal`` /
``celebrate_opponent_goals`` in the soccer lineage, ``_check_for_score`` /
``celebrate_opponent_scores`` in football) but the bodies were identical apart
from three things, each of which is a seam here rather than a branch:
* **wording** :meth:`score_phrase`, the hook football uses to say "TOUCHDOWN"
from the points delta and soccer uses to say "GOOOOAAALLL";
* **follow-up suppression** :attr:`COALESCE_SCORING_SEQUENCE`, on for football
where a touchdown lands as +6 then +1 a few seconds later, off elsewhere where
two quick goals are two real events;
* **team identity** matching goes through ``_favorite_key``, so nrl can match
on team id (its abbreviations are ambiguous) without core knowing why.
The config keys are read under both spellings, so a plugin adopting the mixin
keeps working with the ``*_goals`` keys already in its published schema.
"""
from __future__ import annotations
import re
import time
from typing import Any, Dict, List, Optional
from PIL import Image, ImageDraw
class CelebrationMixin:
"""Full-screen takeover when a tracked team scores or wins."""
#: Collapse increments that land while a celebration is already on screen
#: into that one celebration. True for sports where a single scoring play
#: arrives as more than one score update (football: touchdown +6, then the
#: extra point +1). False where consecutive increments are distinct events —
#: suppressing there would swallow a real goal.
COALESCE_SCORING_SEQUENCE = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
mode_config = getattr(self, "mode_config", {}) or {}
self.celebration_enabled = mode_config.get("celebration_enabled", True)
# Coerced and floored at init: this value is compared numerically on the
# display path, where a string from a hand-edited config would raise
# TypeError outside any try block, and a zero or negative value would
# arm a celebration that can never render.
raw_duration = mode_config.get("celebration_duration", 8)
try:
self.celebration_duration = max(1.0, float(raw_duration))
except (TypeError, ValueError):
self.logger.warning(
"[Celebrations] Unusable celebration_duration %r; using 8s. "
"Set a positive number of seconds.",
raw_duration,
)
self.celebration_duration = 8.0
# Both spellings: the soccer lineage ships `celebrate_opponent_goals`,
# football ships `celebrate_opponent_scores`. Whichever the plugin's
# schema declares is the one its users have set.
self.celebrate_opponent_scores = mode_config.get(
"celebrate_opponent_scores",
mode_config.get("celebrate_opponent_goals", False),
)
# Per-game score baselines: {game_id: {"away": int, "home": int}}
self._score_baselines: Dict[str, Dict[str, int]] = {}
# The active celebration (a game *snapshot*, so a win survives the game
# leaving live_games) or None. See _start_celebration for the shape.
self.active_celebration: Optional[Dict[str, Any]] = None
# ------------------------------------------------------------------
# Override points
# ------------------------------------------------------------------
def score_phrase(self, points: int, team_abbr: str) -> str:
"""The wording for a score celebration.
``points`` is the score delta that triggered it, which sports with
variable-value scores use to name the play. The default is deliberately
sport-neutral; every celebrating plugin overrides it.
"""
return f"{team_abbr} SCORES!"
def win_phrase(self, team_abbr: str) -> str:
"""The wording for a win celebration."""
return f"{team_abbr} WINS!"
def _is_favorite(self, key: Optional[str]) -> bool:
"""Whether ``key`` (whatever ``_favorite_key`` returns) is a favorite."""
return bool(self.favorite_teams) and key in self.favorite_teams
# ------------------------------------------------------------------
# Detection
# ------------------------------------------------------------------
@staticmethod
def _score_to_int(score) -> Optional[int]:
"""Coerce an ESPN score value (str / int / dict) to an int, or None."""
try:
if score is None:
return None
if isinstance(score, str):
s = score.strip()
if not s:
return None
try:
return int(float(s))
except ValueError:
numbers = re.findall(r"\d+", s)
return int(numbers[0]) if numbers else None
if isinstance(score, dict):
return int(float(score.get("value", score.get("displayValue", 0))))
return int(float(score))
except (ValueError, TypeError):
return None
def _should_celebrate_for(self, game: Dict, side: str) -> bool:
"""Whether a score by ``side`` in ``game`` should trigger a celebration."""
if self._is_favorite(self._favorite_key(game, side)):
return True
if not self.favorite_teams:
# No favorites configured: the user opted to show this game, so
# celebrate any score in it.
return True
# Favorites exist but this team isn't one -> it's the opponent.
return self.celebrate_opponent_scores
def prune_score_baselines(self, live_games: List[Dict]) -> None:
"""Drop baselines for games no longer live.
Only :meth:`_check_for_win` removes entries, and it only fires for games
seen to go final. A game that vanishes from the live list any other way
postponed, dropped by the feed, or simply still live when the board
restarts leaves its baseline behind forever, so on a board that runs
all season the dict grows without bound.
Call this from ``update()`` with the current live set, alongside the
equivalent pruning in :meth:`SmoothWeightedRotation.next_game`.
"""
live_ids = {g.get("id") for g in live_games}
self._score_baselines = {
gid: baseline
for gid, baseline in self._score_baselines.items()
if gid in live_ids
}
def has_active_celebration(self) -> bool:
"""True while a celebration is within its display window."""
celebration = self.active_celebration
return bool(celebration) and (
time.time() - celebration["started_at"] < self.celebration_duration
)
def _check_for_score(self, game: Dict) -> None:
"""Compare a live game's score against its baseline and arm a
celebration when a celebratable team's score increases."""
if not self.celebration_enabled:
return
game_id = game.get("id")
if not game_id:
return
away = self._score_to_int(game.get("away_score"))
home = self._score_to_int(game.get("home_score"))
if away is None or home is None:
return
baseline = self._score_baselines.get(game_id)
# Always refresh the baseline: a first sighting must never celebrate (a
# game already in progress at boot would false-fire), and a decrement
# (VAR, a correction) just re-bases silently.
self._score_baselines[game_id] = {"away": away, "home": home}
if baseline is None:
return
away_delta = away - baseline["away"]
home_delta = home - baseline["home"]
if away_delta <= 0 and home_delta <= 0:
return
# One takeover per scoring sequence, where the sport has such a thing.
# The baseline is already advanced above, so nothing re-fires later.
if self.COALESCE_SCORING_SEQUENCE and self.has_active_celebration():
return
scored_side = None
points = 0
if away_delta > 0 and self._should_celebrate_for(game, "away"):
scored_side, points = "away", away_delta
if scored_side is None and home_delta > 0 and self._should_celebrate_for(
game, "home"
):
scored_side, points = "home", home_delta
if scored_side is None:
return
self._start_celebration(
game,
"score",
scored_side=scored_side,
team_abbr=game.get(f"{scored_side}_abbr", ""),
away_score=away,
home_score=home,
points=points,
)
def _check_for_win(self, game: Dict) -> None:
"""When a game we were tracking live goes final, arm a win celebration
if a favorite won. Fires at most once per game."""
if not self.celebration_enabled:
return
game_id = game.get("id")
if not game_id:
return
# Only celebrate wins for games we actually watched go live: one seen
# for the first time already-final (the board started after full time)
# has no baseline and must not fire.
if game_id not in self._score_baselines:
return
# Consume the baseline so this can only fire once.
self._score_baselines.pop(game_id, None)
away = self._score_to_int(game.get("away_score"))
home = self._score_to_int(game.get("home_score"))
if away is None or home is None:
return
if away > home:
winner_side = "away"
elif home > away:
winner_side = "home"
else:
return # draw -> no win celebration
# Wins are gated strictly on favorites: every game ends, so the
# "no favorites -> celebrate all" score fallback would be far too noisy.
if not self._is_favorite(self._favorite_key(game, winner_side)):
return
self._start_celebration(
game,
"win",
scored_side=winner_side,
team_abbr=game.get(f"{winner_side}_abbr", ""),
away_score=away,
home_score=home,
)
def _start_celebration(
self,
game: Dict,
kind: str,
scored_side: str,
team_abbr: str,
away_score: int,
home_score: int,
points: int = 0,
) -> None:
"""Arm a celebration. ``scored_side`` ('away'/'home') is the side whose
score digit gets highlighted."""
phrase = (
self.win_phrase(team_abbr)
if kind == "win"
else self.score_phrase(points, team_abbr)
)
self.active_celebration = {
"kind": kind,
"game": dict(game), # snapshot: survives the game leaving live_games
"scored_side": scored_side,
"team_abbr": team_abbr,
"away_score": away_score,
"home_score": home_score,
"started_at": time.time(),
"phrase": phrase,
}
# Pin focus to the involved game so the post-celebration scorebug
# resumes on it.
self.current_game = dict(game)
self.logger.info(
f"[Celebrations] {kind} armed: {phrase} "
f"[{game.get('away_abbr')} {away_score}-{home_score} {game.get('home_abbr')}]"
)
# ------------------------------------------------------------------
# Rendering
# ------------------------------------------------------------------
def _fit_font(self, draw, text: str, max_width: int, fonts: List):
"""The first font whose rendered ``text`` fits ``max_width``, falling
back to the last (smallest) font."""
for font in fonts:
if draw.textlength(text, font=font) <= max_width - 2:
return font
return fonts[-1]
def _draw_celebration_layout(
self, celebration: Dict, force_clear: bool = False
) -> None:
"""Render the full-screen score/win takeover."""
if force_clear:
self.display_manager.clear()
display_width = (
self.display_manager.matrix.width
if hasattr(self.display_manager, "matrix") and self.display_manager.matrix
else self.display_width
)
display_height = (
self.display_manager.matrix.height
if hasattr(self.display_manager, "matrix") and self.display_manager.matrix
else self.display_height
)
elapsed = time.time() - celebration["started_at"]
game = celebration["game"]
# Background: a brief color flash for the first ~1.2s, then black.
bg = (0, 0, 0, 255)
if elapsed < 1.2 and int(elapsed / 0.2) % 2 == 0:
bg = (12, 12, 48, 255)
main_img = Image.new("RGBA", (display_width, display_height), bg)
overlay = Image.new("RGBA", (display_width, display_height), (0, 0, 0, 0))
draw = ImageDraw.Draw(overlay)
# Logos at the edges (best-effort: a logo failure must not blank the
# celebration).
try:
center_y = display_height // 2
home_logo = self._load_and_resize_logo(
game.get("home_id"), game.get("home_abbr"),
game.get("home_logo_path"), game.get("home_logo_url"),
)
away_logo = self._load_and_resize_logo(
game.get("away_id"), game.get("away_abbr"),
game.get("away_logo_path"), game.get("away_logo_url"),
)
if home_logo:
main_img.paste(
home_logo,
(display_width - home_logo.width + 2, center_y - home_logo.height // 2),
home_logo,
)
if away_logo:
main_img.paste(
away_logo, (-2, center_y - away_logo.height // 2), away_logo
)
except Exception as e:
self.logger.debug(f"[Celebrations] Logo load failed: {e}")
# Phrase across the top, shrunk to fit the panel width.
phrase = celebration["phrase"]
phrase_font = self._fit_font(
draw, phrase, display_width, [self.fonts["time"], self.fonts["status"]]
)
phrase_width = draw.textlength(phrase, font=phrase_font)
self._draw_text_with_outline(
draw, phrase, ((display_width - phrase_width) // 2, 1), phrase_font
)
# Score centered low, with the scoring/winning side's digit pulsing in a
# highlight color so the change reads at a glance.
away_text = str(celebration["away_score"])
home_text = str(celebration["home_score"])
score_font = self.fonts["score"]
segments = [
(away_text, celebration["scored_side"] == "away"),
("-", False),
(home_text, celebration["scored_side"] == "home"),
]
total_width = sum(draw.textlength(seg, font=score_font) for seg, _ in segments)
highlight = (255, 255, 0) if int(elapsed * 4) % 2 == 0 else (255, 170, 0)
x = (display_width - total_width) // 2
y = display_height - 14
for seg, is_highlight in segments:
color = highlight if is_highlight else (255, 255, 255)
self._draw_text_with_outline(draw, seg, (int(x), y), score_font, fill=color)
x += draw.textlength(seg, font=score_font)
main_img = Image.alpha_composite(main_img, overlay).convert("RGB")
self.display_manager.image = main_img
self.display_manager.update_display()
def display(self, force_clear: bool = False) -> bool:
"""Render an active celebration as a full-screen takeover; otherwise
defer to the normal live scorebug."""
if not self.is_enabled:
return False
celebration = self.active_celebration
if celebration:
if self.has_active_celebration():
try:
self._draw_celebration_layout(celebration, force_clear)
return True
except Exception as e:
self.logger.error(
f"[Celebrations] Error drawing celebration: {e}", exc_info=True
)
# Disarm rather than retry: the same render would fail on
# every frame for the rest of the window, logging a
# traceback each time and leaving the scorebug off screen.
self.active_celebration = None
self.last_game_switch = time.time()
else:
self.active_celebration = None
# Reset the dwell so the scorebug resumes on the scoring/winning
# game for a full duration before rotation can move on.
self.last_game_switch = time.time()
return super().display(force_clear)
@@ -1,246 +0,0 @@
"""Live-rotation strategies — which live game to show next.
The nine plugin copies grew three spellings of this, and the survey behind
``docs/SPORTS_UNIFICATION.md`` found they are all the *same* Smooth Weighted
Round-Robin algorithm in two shapes:
* an **incremental picker** that holds weight state across calls and answers
"what next?" one game at a time (afl / nrl / soccer's ``_swrr_advance``), and
* a **precomputed cycle** that returns a full list of game ids up front
(football / baseball / basketball's ``_build_weighted_schedule`` and hockey's
``_build_rotation_schedule``, which differ only in loop shape).
They agree *within* a cycle SWRR is deterministic and differ only at cycle
boundaries, where the incremental form has no seam and the precomputed form
restarts. That is a real behavioral difference, so core ships both rather than
declaring a winner, and a plugin picks one by name:
self.rotation = get_rotation_strategy("swrr", weight_for=self._live_weight)
Core never learns which sport is asking. A plugin with a genuinely novel
ordering registers its own strategy instead of core growing a branch::
register_rotation_strategy("my-order", MyRotation)
"""
from __future__ import annotations
from typing import Callable, Dict, List, Optional, Type
def _game_id(game: Dict) -> Optional[str]:
"""The rotation key for a game, or None if it has no usable id."""
return game.get("id")
class RotationStrategy:
"""Base class for live-rotation ordering.
Subclasses implement :meth:`schedule`; :meth:`next_game` has a working
default derived from it. Strategies whose natural shape is incremental
override :meth:`next_game` instead and derive :meth:`schedule`.
:param weight_for: callable mapping a game dict to a positive integer
weight how many turns it gets per turn of a weight-1 game. Supplied by
the host so the *favorites* policy stays with the plugin and this module
stays free of any notion of what a favorite is. Defaults to equal
weights, which makes every strategy a plain round robin.
"""
#: Name this strategy is registered under. Set by :func:`register_rotation_strategy`.
name: str = ""
#: Ceiling on a per-game weight. A cycle is ``sum(weights)`` long and each
#: step scans every game, so an unbounded weight — a misread config field,
#: say — would spin the display thread for an unbounded time. On a Pi that
#: stalls rendering outright, so the bound is clamped like the floor is.
MAX_WEIGHT = 16
def __init__(self, weight_for: Optional[Callable[[Dict], int]] = None):
self._weight_for = weight_for or (lambda game: 1)
def weights(self, games: List[Dict]) -> Dict[str, int]:
"""``{game_id: weight}`` for games that have an id, in ``games`` order.
A weight below 1 is clamped up: a zero or negative weight would starve
a game out of the rotation entirely, which no caller means to express
and which would make ``total_weight`` collapse. It is clamped down at
:attr:`MAX_WEIGHT` for the reason documented there.
"""
weights: Dict[str, int] = {}
for game in games:
gid = _game_id(game)
if gid is None:
continue
try:
weight = int(self._weight_for(game))
except (TypeError, ValueError):
weight = 1
weights[gid] = min(self.MAX_WEIGHT, max(1, weight))
return weights
def schedule(self, games: List[Dict]) -> List[str]:
"""Game ids in display order for one cycle. Ids may repeat."""
raise NotImplementedError
def next_game(self, games: List[Dict]) -> Optional[Dict]:
"""The next game to display, or None when there is nothing to show."""
order = self.schedule(games)
if not order:
return None
by_id = {gid: g for g in games if (gid := _game_id(g)) is not None}
return by_id.get(order[0])
def reset(self) -> None:
"""Drop any accumulated state. Stateless strategies need do nothing."""
class SimpleRotation(RotationStrategy):
"""Plain round robin: every live game once per cycle, weights ignored.
The fallback for a plugin that wants strictly even rotation regardless of
favorites.
"""
def schedule(self, games: List[Dict]) -> List[str]:
return [gid for g in games if (gid := _game_id(g)) is not None]
class WeightedCycleRotation(RotationStrategy):
"""Precomputed SWRR cycle — the football / baseball / basketball / hockey shape.
Returns a full cycle of ``sum(weights)`` ids with repeats spaced evenly
rather than clumped, highest weight scheduled first. When no game carries a
boost the cycle degenerates to a single pass in ``games`` order, which is
exactly the plain round robin it replaced.
"""
def schedule(self, games: List[Dict]) -> List[str]:
weights = self.weights(games)
if not weights:
return []
total_weight = sum(weights.values())
if total_weight <= len(weights):
# No boost in effect — plain order, one pass. (Also the guard that
# keeps the loop below from being O(total_weight) for nothing.)
return list(weights)
current = {gid: 0 for gid in weights}
order: List[str] = []
for _ in range(total_weight):
for gid, weight in weights.items():
current[gid] += weight
picked = max(current, key=lambda gid: current[gid])
current[picked] -= total_weight
order.append(picked)
return order
class SmoothWeightedRotation(RotationStrategy):
"""Incremental SWRR — the afl / nrl / soccer shape.
Weight state persists across calls, so there is no fixed-length cycle and
therefore no clustering seam at a cycle boundary. A game seen for the first
time starts at weight 0 and receives its full weight on the next call, so a
favorite's game that has just gone live naturally wins the first pick after
it appears "queued first on refresh" without a special-cased branch.
State for games no longer live is dropped on each call, so a long-running
board does not accumulate entries for finished games.
"""
def __init__(self, weight_for: Optional[Callable[[Dict], int]] = None):
super().__init__(weight_for)
self._current: Dict[str, int] = {}
def reset(self) -> None:
self._current = {}
def next_game(self, games: List[Dict]) -> Optional[Dict]:
if not games:
return None
weights = self.weights(games)
if not weights:
return None
# Keep state only for games still live.
self._current = {
gid: value for gid, value in self._current.items() if gid in weights
}
for gid, weight in weights.items():
self._current[gid] = self._current.get(gid, 0) + weight
total_weight = sum(weights.values())
# Iterate in `games` order so ties break toward the feed's ordering,
# which is what the plugin copies did and what makes the no-boost case
# identical to a plain round robin.
ids_in_order = [gid for g in games if (gid := _game_id(g)) in weights]
best = max(ids_in_order, key=lambda gid: self._current[gid])
self._current[best] -= total_weight
return next(g for g in games if _game_id(g) == best)
def schedule(self, games: List[Dict]) -> List[str]:
"""One cycle's worth of picks, without disturbing live state.
Derived by running the picker forward on a copy, so the returned order
is exactly what repeated :meth:`next_game` calls would produce from the
current state callers can use it to preview or log the rotation
without perturbing it.
"""
weights = self.weights(games)
if not weights:
return []
# type(self), not this class: a subclass that overrides next_game must
# be previewed through its own ordering, or the returned order is not
# the one repeated next_game calls would produce — which is exactly
# what this method promises.
preview = type(self)(self._weight_for)
preview._current = dict(self._current)
order: List[str] = []
for _ in range(sum(weights.values())):
picked = preview.next_game(games)
if picked is None:
break
order.append(_game_id(picked))
return order
_REGISTRY: Dict[str, Type[RotationStrategy]] = {}
def register_rotation_strategy(name: str, factory: Type[RotationStrategy]) -> None:
"""Register a rotation strategy under ``name``.
When a plugin needs an ordering that core does not ship, it registers its
own here instead of core growing a sport-specific branch. Re-registering a
name replaces it, so a plugin may also override a built-in for itself.
"""
if not name:
raise ValueError("rotation strategy name must be a non-empty string")
# Fail at registration, not at the first schedule() call several frames
# later, where the cause is no longer on the stack.
if not (isinstance(factory, type) and issubclass(factory, RotationStrategy)):
raise TypeError(
f"rotation strategy {name!r} must be a RotationStrategy subclass, "
f"got {factory!r}"
)
factory.name = name
_REGISTRY[name] = factory
def get_rotation_strategy(
name: str, weight_for: Optional[Callable[[Dict], int]] = None
) -> RotationStrategy:
"""Build the strategy registered under ``name``.
Falls back to ``"simple"`` for an unknown name rather than raising: the name
arrives from user config, and a typo should cost the boost, not the
scoreboard.
"""
factory = _REGISTRY.get(name) or _REGISTRY["simple"]
return factory(weight_for=weight_for)
register_rotation_strategy("simple", SimpleRotation)
register_rotation_strategy("weighted", WeightedCycleRotation)
register_rotation_strategy("swrr", SmoothWeightedRotation)
File diff suppressed because it is too large Load Diff
+7 -17
View File
@@ -163,25 +163,19 @@ class BaseOddsManager:
item = data["items"][0] item = data["items"][0]
self.logger.debug(f"First item keys: {list(item.keys())}") self.logger.debug(f"First item keys: {list(item.keys())}")
# The ESPN API returns odds data directly in the item, not in a # The ESPN API returns odds data directly in the item, not in a providers array
# providers array. ESPN sends explicit JSON nulls for absent # Extract the odds data directly from the item
# sides ("homeTeamOdds": null), so every level uses `or {}` —
# .get's default only applies when the key is missing entirely.
home = item.get("homeTeamOdds") or {}
away = item.get("awayTeamOdds") or {}
extracted_data = { extracted_data = {
"details": item.get("details"), "details": item.get("details"),
"over_under": item.get("overUnder"), "over_under": item.get("overUnder"),
"spread": item.get("spread"), "spread": item.get("spread"),
"home_team_odds": { "home_team_odds": {
"money_line": home.get("moneyLine"), "money_line": item.get("homeTeamOdds", {}).get("moneyLine"),
"spread_odds": ((home.get("current") or {}) "spread_odds": item.get("homeTeamOdds", {}).get("current", {}).get("pointSpread", {}).get("value")
.get("pointSpread") or {}).get("value")
}, },
"away_team_odds": { "away_team_odds": {
"money_line": away.get("moneyLine"), "money_line": item.get("awayTeamOdds", {}).get("moneyLine"),
"spread_odds": ((away.get("current") or {}) "spread_odds": item.get("awayTeamOdds", {}).get("current", {}).get("pointSpread", {}).get("value")
.get("pointSpread") or {}).get("value")
} }
} }
self.logger.debug(f"Returning extracted odds data: {json.dumps(extracted_data, indent=2)}") self.logger.debug(f"Returning extracted odds data: {json.dumps(extracted_data, indent=2)}")
@@ -266,11 +260,7 @@ class BaseOddsManager:
Returns: Returns:
Formatted odds summary string Formatted odds summary string
""" """
# Gate only on truly-empty / negative-cached data. is_odds_available if not self.is_odds_available(odds_data):
# deliberately ignores money lines (its callers decide whether to
# RENDER an odds widget), but a summary of money-line-only odds is
# still meaningful — the parts loop below handles them.
if not odds_data or odds_data.get('no_odds'):
return "No odds available" return "No odds available"
parts = [] parts = []
+8 -4
View File
@@ -39,10 +39,14 @@ from src.cache.cache_strategy import CacheStrategy
from src.cache.cache_metrics import CacheMetrics from src.cache.cache_metrics import CacheMetrics
from src.logging_config import get_logger from src.logging_config import get_logger
# Canonical implementation lives in src.cache.disk_cache; re-exported here class DateTimeEncoder(json.JSONEncoder):
# because this module's docstring documents it and external code may import """JSON encoder that serialises ``datetime`` objects as ISO-8601 strings."""
# it from either path.
from src.cache.disk_cache import DateTimeEncoder # noqa: F401 - deliberate re-export def default(self, obj):
"""Return ISO-8601 string for datetime; delegate all other types to the base encoder."""
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
class CacheManager: class CacheManager:
"""Manages caching of API responses to reduce API calls.""" """Manages caching of API responses to reduce API calls."""
+5
View File
@@ -99,6 +99,11 @@ Helpers for ensuring directory permissions and ownership are correct
when running as a service (used by `CacheManager` to set up its when running as a service (used by `CacheManager` to set up its
persistent cache directory). persistent cache directory).
## CLI Helpers (`cli.py`)
Shared CLI argument parsing helpers used by `scripts/dev/*` and other
command-line entry points.
## Best Practices ## Best Practices
1. **Use centralized logging**: Import from `src.logging_config` instead of creating loggers directly 1. **Use centralized logging**: Import from `src.logging_config` instead of creating loggers directly
+12 -29
View File
@@ -56,9 +56,7 @@ class APIHelper:
# Default headers # Default headers
self.session.headers.update({ self.session.headers.update({
# Identifies the client and links to it: ESPN began 403ing bare 'User-Agent': 'LEDMatrix-Common/1.0',
# custom tokens (and browser strings) around 2026-08-04.
'User-Agent': 'LEDMatrix/1.0 (+https://github.com/ChuckBuilds/LEDMatrix)',
'Accept': 'application/json', 'Accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.9', 'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br', 'Accept-Encoding': 'gzip, deflate, br',
@@ -273,34 +271,19 @@ class APIHelper:
""" """
Clear cache data. Clear cache data.
Uses CacheManager's real surface (clear_cache / delete /
list_cache_files); safely no-ops on managers without it. The old
implementation guarded on a nonexistent ``clear`` method, so it
silently never cleared anything.
Args: Args:
pattern: Optional substring to match cache keys; only matching pattern: Optional pattern to match cache keys
entries are deleted.
""" """
if not self.cache_manager: if self.cache_manager:
return if hasattr(self.cache_manager, 'clear'):
if pattern: if pattern:
if (hasattr(self.cache_manager, 'list_cache_files') # Clear only keys matching pattern
and hasattr(self.cache_manager, 'delete')): keys = self.cache_manager.keys()
for entry in self.cache_manager.list_cache_files(): for key in keys:
key = entry.get('key') if isinstance(entry, dict) else None if pattern in key:
if key and pattern in key: self.cache_manager.delete(key)
self.cache_manager.delete(key) else:
else: self.cache_manager.clear()
self.logger.debug(
"Cache manager lacks list_cache_files/delete; "
"cannot clear by pattern")
elif hasattr(self.cache_manager, 'clear_cache'):
self.cache_manager.clear_cache()
elif hasattr(self.cache_manager, 'clear'):
self.cache_manager.clear()
else:
self.logger.debug("Cache manager exposes no clear method; no-op")
def _get_from_cache(self, key: str) -> Optional[Any]: def _get_from_cache(self, key: str) -> Optional[Any]:
"""Get data from cache.""" """Get data from cache."""
+111
View File
@@ -0,0 +1,111 @@
"""
LEDMatrix Common CLI
Command-line interface for LEDMatrix Common utilities.
"""
import argparse
import sys
from pathlib import Path
def main():
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
description="LEDMatrix Common Utilities",
prog="ledmatrix-common"
)
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# Test command
test_parser = subparsers.add_parser('test', help='Test common utilities')
test_parser.add_argument('--display-width', type=int, default=128, help='Display width')
test_parser.add_argument('--display-height', type=int, default=64, help='Display height')
# Validate command
validate_parser = subparsers.add_parser('validate', help='Validate configuration')
validate_parser.add_argument('config_file', help='Configuration file to validate')
args = parser.parse_args()
if args.command == 'test':
test_utilities(args.display_width, args.display_height)
elif args.command == 'validate':
validate_config(args.config_file)
else:
parser.print_help()
def test_utilities(display_width: int, display_height: int):
"""Test common utilities."""
print(f"Testing LEDMatrix Common utilities with {display_width}x{display_height} display")
try:
from ledmatrix_common import LogoHelper, TextHelper, DisplayHelper, GameHelper, ConfigHelper
# Test LogoHelper
print("Testing LogoHelper...")
logo_helper = LogoHelper(display_width, display_height)
print(f"Logo cache stats: {logo_helper.get_cache_stats()}")
# Test TextHelper
print("Testing TextHelper...")
text_helper = TextHelper()
fonts = text_helper.load_fonts()
print(f"Loaded {len(fonts)} fonts")
# Test DisplayHelper
print("Testing DisplayHelper...")
display_helper = DisplayHelper(display_width, display_height)
img = display_helper.create_base_image()
print(f"Created {img.size} base image")
# Test GameHelper
print("Testing GameHelper...")
GameHelper()
print("GameHelper initialized")
# Test ConfigHelper
print("Testing ConfigHelper...")
ConfigHelper()
print("ConfigHelper initialized")
print("All tests passed!")
except ImportError as e:
print(f"Import error: {e}")
sys.exit(1)
except Exception as e:
print(f"Test error: {e}")
sys.exit(1)
def validate_config(config_file: str):
"""Validate configuration file."""
config_path = Path(config_file)
if not config_path.exists():
print(f"Configuration file not found: {config_file}")
sys.exit(1)
try:
from ledmatrix_common import ConfigHelper
config_helper = ConfigHelper()
config = config_helper.load_config(config_path)
if config:
print(f"Configuration loaded successfully from {config_file}")
print(f"Found {len(config)} top-level keys")
else:
print(f"Failed to load configuration from {config_file}")
sys.exit(1)
except Exception as e:
print(f"Validation error: {e}")
sys.exit(1)
if __name__ == '__main__':
main()
+4 -8
View File
@@ -5,7 +5,6 @@ Handles configuration management and validation for LED matrix plugins.
Extracted from LEDMatrix core to provide reusable functionality for plugins. Extracted from LEDMatrix core to provide reusable functionality for plugins.
""" """
import copy
import json import json
import logging import logging
from pathlib import Path from pathlib import Path
@@ -161,20 +160,17 @@ class ConfigHelper:
override_config: Configuration to merge in (takes precedence) override_config: Configuration to merge in (takes precedence)
Returns: Returns:
Merged configuration dictionary (fully independent of both Merged configuration dictionary
inputs a shallow copy would alias un-overridden nested dicts,
so mutating the result would mutate the caller's base config).
""" """
merged = copy.deepcopy(base_config) merged = base_config.copy()
for key, value in override_config.items(): for key, value in override_config.items():
if key in merged and isinstance(merged[key], dict) and isinstance(value, dict): if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
# Recursively merge nested dictionaries # Recursively merge nested dictionaries
merged[key] = self.merge_configs(merged[key], value) merged[key] = self.merge_configs(merged[key], value)
else: else:
# Override with new value — deep-copied so mutating the # Override with new value
# merged result can't reach back into override_config. merged[key] = value
merged[key] = copy.deepcopy(value)
return merged return merged
+29 -18
View File
@@ -115,13 +115,17 @@ class DisplayHelper:
if home_logo and away_logo: if home_logo and away_logo:
self._draw_logos(main_img, home_logo, away_logo) self._draw_logos(main_img, home_logo, away_logo)
# Draw one combined top line (period/status/clock all share y=1 — # Draw status/period text (top center)
# drawing them separately overprinted each other). if status_text or period_text:
top_line = " ".join(p for p in [period_text, status_text, clock] if p) status_display = f"{period_text} {status_text}".strip()
if top_line: if status_display:
self._draw_centered_text(draw, top_line, self._draw_centered_text(draw, status_display,
fonts.get('time', fonts.get('status')), fonts.get('time', fonts.get('status')),
y_position=1) y_position=1)
# Draw clock if available
if clock:
self._draw_centered_text(draw, clock, fonts.get('time'), y_position=1)
# Draw scores (center) # Draw scores (center)
score_text = f"{away_score}-{home_score}" score_text = f"{away_score}-{home_score}"
@@ -149,18 +153,12 @@ class DisplayHelper:
""" """
Draw a ticker/scrolling text layout. Draw a ticker/scrolling text layout.
Renders a single static frame with the text at the left edge; the
caller advances the scroll by re-rendering or shifting. The
scroll_speed parameter is accepted for API compatibility but does
not affect this frame. (Previously the text was drawn starting at
x=display_width entirely off-canvas so every frame was blank.)
Args: Args:
text: Text to display text: Text to display
font: Font to use font: Font to use
background_color: Background color background_color: Background color
text_color: Text color text_color: Text color
scroll_speed: Accepted for compatibility; unused per-frame scroll_speed: Pixels to scroll per frame
Returns: Returns:
PIL Image with ticker layout PIL Image with ticker layout
@@ -168,7 +166,11 @@ class DisplayHelper:
img = self.create_base_image(background_color) img = self.create_base_image(background_color)
draw = ImageDraw.Draw(img) draw = ImageDraw.Draw(img)
self._draw_text_with_outline(draw, text, (0, self.display_height // 2 - 6), # Start text off-screen to the right
x_position = self.display_width
# Draw text
self._draw_text_with_outline(draw, text, (x_position, self.display_height // 2 - 6),
font, fill=text_color) font, fill=text_color)
return img return img
@@ -212,9 +214,15 @@ class DisplayHelper:
Returns: Returns:
PIL Image with error message PIL Image with error message
""" """
# Dark red background, white text img = self.create_base_image((50, 0, 0)) # Dark red background
# Use default font
font = ImageFont.load_default() font = ImageFont.load_default()
return self.draw_centered_text(message, font, (50, 0, 0), (255, 255, 255))
# Draw centered error message
self._draw_centered_text(message, font, (50, 0, 0), (255, 255, 255))
return img
def draw_no_data_message(self, message: str = "No Data") -> Image.Image: def draw_no_data_message(self, message: str = "No Data") -> Image.Image:
""" """
@@ -226,8 +234,11 @@ class DisplayHelper:
Returns: Returns:
PIL Image with no data message PIL Image with no data message
""" """
img = self.create_base_image((0, 0, 0))
font = ImageFont.load_default() font = ImageFont.load_default()
return self.draw_centered_text(message, font, (0, 0, 0), (150, 150, 150)) self._draw_centered_text(message, font, (0, 0, 0), (150, 150, 150))
return img
def get_display_dimensions(self) -> Tuple[int, int]: def get_display_dimensions(self) -> Tuple[int, int]:
""" """
-7
View File
@@ -188,13 +188,6 @@ class LogoHelper:
""" """
Normalize team abbreviation for consistent filename usage. Normalize team abbreviation for consistent filename usage.
NOTE: this deliberately differs from
LogoDownloader.normalize_abbreviation (src/logo_downloader.py),
which replaces filesystem-unsafe characters (/ \\ : * ? " < > |)
but does not strip spaces. Plugins call the LogoDownloader
version; changing either implementation changes which logo
filenames resolve on existing installs.
Args: Args:
team_abbr: Raw team abbreviation team_abbr: Raw team abbreviation
+2 -183
View File
@@ -349,72 +349,13 @@ class ScrollHelper:
if not self.cached_image or self.cached_array is None: if not self.cached_image or self.cached_array is None:
return None return None
# Use integer pixel positioning for high FPS scrolling (like stock ticker)
start_x_int = int(self.scroll_position) start_x_int = int(self.scroll_position)
end_x_int = start_x_int + self.display_width end_x_int = start_x_int + self.display_width
# Integer positioning quantises motion to whole pixels, so the number of # Fast integer pixel path (no interpolation - high frame rate provides smoothness)
# distinct frames per second equals the scroll speed in px/s, no matter
# how fast the loop renders. At 50px/s and 78fps that made 36% of frames
# identical: the extra frames cost work and bought nothing. Blending
# between the two neighbouring positions gives motion at the frame rate
# instead of the step rate.
if self.sub_pixel_scrolling:
fractional = self.scroll_position - start_x_int
if fractional > 0.0:
return self._blend_visible_portion(start_x_int, fractional)
return self._get_visible_portion_integer(start_x_int, end_x_int) return self._get_visible_portion_integer(start_x_int, end_x_int)
def _blend_visible_portion(self, start_x: int, fractional: float) -> Image.Image:
"""
Linear blend between the frames at ``start_x`` and ``start_x + 1``.
Implemented with numpy rather than scipy.ndimage.shift: scipy is not
installed on the target devices (HAS_SCIPY is False there), which is why
the pre-existing sub-pixel path was dead code get_visible_portion never
consulted the flag, and the scipy fallback would not have interpolated
anyway.
Args:
start_x: Left column of the earlier of the two frames
fractional: How far between the two, in [0, 1)
Returns:
The blended frame
"""
width = self.display_width
strip_width = self.cached_array.shape[1]
if start_x + width + 1 <= strip_width:
# Slice the backing array directly. Going via
# _get_visible_portion_integer would build two PIL images only for
# them to be converted straight back to arrays, which measured 15x
# the cost of the integer path.
near = self.cached_array[:, start_x:start_x + width]
far = self.cached_array[:, start_x + 1:start_x + 1 + width]
else:
# Close enough to the end that one of the slices wraps; let the
# integer path handle that and pay the conversion. Continuous mode
# extends the strip before reaching here, so this is the rare case.
near = np.asarray(
self._get_visible_portion_integer(start_x, start_x + width))
far = np.asarray(
self._get_visible_portion_integer(start_x + 1, start_x + 1 + width))
# Fixed-point rather than float32: integer multiply-add on uint16 is
# markedly faster than float maths on the Pi's ARM cores, and 8 bits of
# weight is finer than the panel can show.
weight = int(fractional * 256.0)
blended = (
(near.astype(np.uint16) * (256 - weight)
+ far.astype(np.uint16) * weight) >> 8
).astype(np.uint8)
return Image.frombytes(
'RGB', (width, self.display_height),
np.ascontiguousarray(blended).tobytes()
)
def _get_visible_portion_integer(self, start_x: int, end_x: int) -> Image.Image: def _get_visible_portion_integer(self, start_x: int, end_x: int) -> Image.Image:
"""Fast integer pixel extraction (no interpolation). """Fast integer pixel extraction (no interpolation).
@@ -707,128 +648,6 @@ class ScrollHelper:
""" """
return self.scroll_complete return self.scroll_complete
def append_content(self, content_items: list,
item_gap: int = 32,
element_gap: int = 0) -> bool:
"""
Append items to the right of the existing strip, preserving scroll state.
Lets a caller keep one continuous strip instead of replacing it. Vegas
mode uses this so the next group of plugins scrolls in from the right
rather than the strip being swapped out underneath the viewer a swap
shows as a flash and a hard cut to already-full-screen content.
``scroll_position`` and ``total_distance_scrolled`` are untouched, so
motion continues uninterrupted; only the strip gets longer. Because
completion is measured against ``total_scroll_width``, extending the
strip also defers completion, which is the intent.
Args:
content_items: Images to append, in order
item_gap: Gap between appended items, and between the existing
content and the first appended item
element_gap: Extra gap after each item, mirroring
create_scrolling_image
Returns:
True if content was appended
"""
if not content_items:
return False
if self.cached_image is None or self.cached_array is None:
# Nothing to extend yet — this is just the first build.
self.create_scrolling_image(
content_items, item_gap=item_gap, element_gap=element_gap, lead_gap=0)
return True
gap = max(0, item_gap)
addition_width = (
sum(img.width for img in content_items)
+ gap * len(content_items) # one leading gap per item
+ element_gap * len(content_items)
)
addition = Image.new('RGB', (addition_width, self.display_height), (0, 0, 0))
x = 0
for img in content_items:
x += gap # separate from whatever precedes
addition.paste(img, (x, 0))
x += img.width + element_gap
# numpy concatenate then one conversion back, rather than allocating a
# full-width PIL image and pasting twice: the strip can be tens of
# thousands of columns wide and this runs on the render path.
self.cached_array = np.concatenate(
(self.cached_array, np.array(addition)), axis=1)
self.cached_image = Image.fromarray(self.cached_array)
self.total_scroll_width = self.cached_image.width
self.scroll_complete = False
self.logger.info(
"Appended %d item(s) (%dpx) to scroll strip: now %dpx, position %.0f",
len(content_items), addition_width, self.total_scroll_width,
self.scroll_position
)
return True
def drop_scrolled_prefix(self, keep_before: int = 0) -> int:
"""
Discard columns that have already scrolled past, to bound memory.
A continuously extended strip would otherwise grow without limit. All
the positional state is shifted by the amount removed so the visible
frame and the completion arithmetic are unchanged:
``total_distance_scrolled`` and ``total_scroll_width`` both shrink by the
same amount, preserving their difference.
Args:
keep_before: Columns to retain behind the current position, as a
safety margin against a caller reading slightly behind it
Returns:
Number of columns actually removed
"""
if self.cached_image is None or self.cached_array is None:
return 0
# While the viewport wraps, get_visible_portion fills its right-hand side
# from the *head* of the strip, so trimming the head would change what
# is on screen. Continuous mode extends before ever reaching that state;
# refusing here keeps "trimming is invisible" true unconditionally.
if self.scroll_position + self.display_width > self.cached_image.width:
return 0
cut = int(self.scroll_position) - max(0, keep_before)
if cut <= 0:
return 0
# Never trim so far that the remaining strip is narrower than the
# viewport, or get_visible_portion has nothing to slice.
cut = min(cut, max(0, self.cached_image.width - self.display_width))
if cut <= 0:
return 0
# .copy() so the original buffer is released rather than kept alive by
# a numpy view.
self.cached_array = self.cached_array[:, cut:].copy()
self.cached_image = Image.fromarray(self.cached_array)
self.total_scroll_width = self.cached_image.width
self.scroll_position -= cut
self.total_distance_scrolled = max(0.0, self.total_distance_scrolled - cut)
self.logger.debug(
"Dropped %dpx of scrolled strip: now %dpx, position %.0f",
cut, self.total_scroll_width, self.scroll_position
)
return cut
def remaining_unscrolled(self) -> int:
"""Columns of strip still to the right of the viewport."""
if self.cached_image is None:
return 0
return max(0, self.total_scroll_width - int(self.scroll_position)
- self.display_width)
def reset_scroll(self) -> None: def reset_scroll(self) -> None:
""" """
Reset scroll position to beginning. Reset scroll position to beginning.
-485
View File
@@ -1,485 +0,0 @@
"""Shared scroll-display scaffolding for the sports scoreboards.
Ten plugins ship a `scroll_display.py`. A method-level comparison of the eight
that share a shape (f1 and ufc are genuine forks) found a sharp split, and this
module is drawn along it rather than around all of it:
* The **orchestration layer is converged** ``get_all_vegas_content_items`` is
byte-identical in all eight, and ``clear_all``, ``get_scroll_info``,
``get_dynamic_duration``, ``is_complete`` and ``display_frame`` are 96-100%
similar. That is what lives here.
* The **content layer has genuinely diverged** ``prepare_scroll_content`` has
eight distinct bodies across eight plugins (145 lines, 53% similarity at
worst) and ``_load_separator_icons`` seven (6% at worst). Those build each
sport's game cards and icon strip; they are *not* drift to be merged but
per-sport rendering. They stay override points here, permanently.
Promoting the content layer would be exactly the mistake
``docs/SPORTS_UNIFICATION.md`` warns against merging on the intuition that
same-named methods are the same method. Same name, different job.
The one behavior this module adds over the plugin copies is native support for
``global_config['target_fps']``: the bundled copies hardcode ~100 FPS via
``scroll_delay=0.01`` and never consult the global smooth-scrolling target. A
plugin inheriting from here gets it for free.
Usage::
class HockeyScrollDisplay(SportsScrollDisplay):
SCROLL_LEAGUE_KEYS = ("nhl", "ncaa_mens", "ncaam_hockey")
def prepare_scroll_content(self, games, game_type, leagues, rankings=None):
... # build this sport's cards
class HockeyScrollDisplayManager(SportsScrollDisplayManager):
display_class = HockeyScrollDisplay
"""
from __future__ import annotations
import logging
import time
from typing import Any, Dict, List, Optional
from PIL import Image
from src.common.scroll_helper import ScrollHelper
logger = logging.getLogger(__name__)
#: Defaults every copy agreed on. A subclass overrides
#: :meth:`SportsScrollDisplay.scroll_settings_defaults` to change them —
#: the soccer lineage uses a 24px gap and min/max duration keys instead.
DEFAULT_SCROLL_SETTINGS: Dict[str, Any] = {
"scroll_speed": 50.0,
"scroll_delay": 0.01,
"gap_between_games": 48,
"show_league_separators": True,
"dynamic_duration": True,
}
#: Bounds on the px/second -> px/frame conversion, applied before the helper
#: sees the value. FPS is *not* clamped here — ScrollHelper.set_target_fps
#: already does that, and a second copy of the range would drift from it.
MIN_PIXELS_PER_FRAME = 0.1
MAX_PIXELS_PER_FRAME = 5.0
#: Pacing to assume when scroll_delay is 0, i.e. the plugin has not set one.
ASSUMED_FPS_WHEN_UNPACED = 100.0
class SportsScrollDisplay:
"""One scrolling strip of game cards.
Subclasses supply the content (:meth:`prepare_scroll_content`) and,
optionally, the per-sport league ladder and separator icons. Everything
else helper configuration, frame pumping, completion, state is here.
"""
#: Config keys to walk when looking for per-league ``scroll_settings``,
#: most-preferred first. A sport's own league names, which is the *only*
#: reason the eight copies of ``_get_scroll_settings`` differ. Empty means
#: the plugin has no per-league scroll settings.
SCROLL_LEAGUE_KEYS: tuple = ()
#: Config block holding scroll settings when the plugin keeps them in one
#: place rather than per league (the afl/nrl/soccer shape).
SCROLL_CONFIG_KEY: Optional[str] = None
def __init__(
self,
display_manager,
config: Dict[str, Any],
custom_logger: Optional[logging.Logger] = None,
global_config: Optional[Dict[str, Any]] = None,
):
"""
:param display_manager: the core display manager
:param config: the plugin's configuration
:param custom_logger: the plugin's logger, so scroll lines are attributed
:param global_config: the LEDMatrix global config the source of
``target_fps``. Optional so an older caller that does not pass it
keeps working at the config-derived pacing.
"""
self.display_manager = display_manager
self.config = config
self.logger = custom_logger or logger
self.global_config = global_config or {}
if getattr(display_manager, "matrix", None) is not None:
self.display_width = display_manager.matrix.width
self.display_height = display_manager.matrix.height
else:
self.display_width = getattr(display_manager, "width", 128)
self.display_height = getattr(display_manager, "height", 32)
self.scroll_helper = ScrollHelper(
self.display_width, self.display_height, self.logger
)
self._configure_scroll_helper()
self._logo_cache: Dict[str, Image.Image] = {}
self._separator_icons: Dict[str, Image.Image] = {}
self._load_separator_icons()
self._current_games: List[Dict] = []
self._current_game_type: str = ""
self._current_leagues: List[str] = []
self._vegas_content_items: List[Image.Image] = []
self._is_scrolling = False
self._scroll_start_time: Optional[float] = None
self._last_log_time: float = 0
self._log_interval: float = 5.0
self._frame_count: int = 0
self._fps_sample_start: float = time.time()
# ------------------------------------------------------------------
# Override points
# ------------------------------------------------------------------
def prepare_scroll_content(
self,
games: List[Dict],
game_type: str,
leagues: List[str],
rankings_cache: Optional[Dict[str, int]] = None,
) -> bool:
"""Render ``games`` into one wide image and hand it to the scroll helper.
**Per-sport by nature, not by drift** the eight plugin copies have
eight different bodies because each draws its own card. Implementations
build the strip, hand it over with
``self.scroll_helper.set_scrolling_image(...)`` (or
``create_scrolling_image(...)`` from a list of cards), and record
``self._current_games`` / ``_current_game_type`` / ``_current_leagues``.
:returns: True when there is content to scroll.
"""
raise NotImplementedError(
f"{type(self).__name__} must implement prepare_scroll_content(); "
"it builds this sport's game cards and is not shared code."
)
def _load_separator_icons(self) -> None:
"""Populate ``self._separator_icons``. Per-sport; no-op by default."""
def scroll_settings_defaults(self) -> Dict[str, Any]:
"""The baseline scroll settings before any config is applied."""
defaults = dict(DEFAULT_SCROLL_SETTINGS)
defaults["game_card_width"] = self.display_width
return defaults
# ------------------------------------------------------------------
# Settings
# ------------------------------------------------------------------
def _get_scroll_settings(self, league: Optional[str] = None) -> Dict[str, Any]:
"""Resolve scroll settings: defaults, then the most specific override.
Precedence: the named ``league``, then each entry of
:attr:`SCROLL_LEAGUE_KEYS` in order, then :attr:`SCROLL_CONFIG_KEY`.
The eight plugin copies implement exactly this and differ only in which
league names they walk which is why the ladder is data here rather
than a body per sport.
"""
settings = self.scroll_settings_defaults()
candidates: List[str] = []
if league:
candidates.append(league)
candidates.extend(self.SCROLL_LEAGUE_KEYS)
for key in candidates:
override = (self.config.get(key) or {}).get("scroll_settings")
if override:
return {**settings, **override}
if self.SCROLL_CONFIG_KEY:
override = self.config.get(self.SCROLL_CONFIG_KEY) or {}
if override:
return {**settings, **override}
return settings
def _resolve_target_fps(self) -> Optional[float]:
"""The global smooth-scrolling FPS target, or None to keep config pacing.
Coerced before use: a malformed value in the global config must degrade
to the existing ``scroll_delay`` pacing, never raise on a display path.
"""
raw = self.global_config.get("target_fps") or self.global_config.get(
"scroll_target_fps"
)
try:
return float(raw) if raw is not None else None
except (TypeError, ValueError):
self.logger.debug("Ignoring unusable target_fps: %r", raw)
return None
def _coerce_float(self, value: Any, default: float) -> float:
"""A usable float from config, or ``default``.
``dict.get(key, default)`` only helps when the key is *absent*; a key
present with ``null`` or a string returns that value verbatim and blows
up in the arithmetic below inside ``__init__``, so the whole display
fails to construct.
"""
if value is None:
return default
try:
return float(value)
except (TypeError, ValueError):
self.logger.warning(
"Ignoring unusable scroll setting %r; using %s", value, default
)
return default
def _configure_scroll_helper(self) -> None:
"""Apply config to the scroll helper. Safe to call again after a change."""
settings = self._get_scroll_settings()
scroll_speed = self._coerce_float(settings.get("scroll_speed"), 50.0)
scroll_delay = self._coerce_float(settings.get("scroll_delay"), 0.01)
dynamic_duration = bool(settings.get("dynamic_duration", True))
self.scroll_helper.set_scroll_delay(scroll_delay)
self.scroll_helper.set_dynamic_duration_settings(
enabled=dynamic_duration,
min_duration=settings.get("min_duration", 30),
max_duration=settings.get("max_duration", 600),
buffer=0.2, # ensure the strip clears the panel completely
)
# Frame-based scrolling: motion advances per rendered frame rather than
# per wall-clock second, which is what makes the pacing stable.
self.scroll_helper.set_frame_based_scrolling(True)
# Config states speed in px/second; frame-based mode wants px/frame.
if scroll_delay > 0:
pixels_per_frame = scroll_speed * scroll_delay
else:
pixels_per_frame = scroll_speed / ASSUMED_FPS_WHEN_UNPACED
pixels_per_frame = max(
MIN_PIXELS_PER_FRAME, min(MAX_PIXELS_PER_FRAME, pixels_per_frame)
)
self.scroll_helper.set_scroll_speed(pixels_per_frame)
effective_pps = (
pixels_per_frame / scroll_delay
if scroll_delay > 0
else pixels_per_frame * ASSUMED_FPS_WHEN_UNPACED
)
self.logger.info(
f"ScrollHelper configured: {pixels_per_frame:.2f} px/frame, "
f"delay={scroll_delay}s (effective {effective_pps:.1f} px/s from "
f"{scroll_speed} px/s config), dynamic_duration={dynamic_duration}"
)
# The reason this module exists upstream: the bundled copies hardcode
# ~100 FPS via scroll_delay and never consult the global target.
# No hasattr guard here, unlike the plugin copies: they probe because
# they may run against an older core, whereas this module ships in the
# same release as the ScrollHelper it calls. The helper clamps.
target_fps = self._resolve_target_fps()
if target_fps:
self.scroll_helper.set_target_fps(target_fps)
self.logger.info(f"Target FPS set to {target_fps}")
# ------------------------------------------------------------------
# Frame pumping
# ------------------------------------------------------------------
def display_scroll_frame(self) -> bool:
"""Advance and render one frame.
:returns: True if a frame was drawn; False when there is no content or
the frame could not be rendered.
"""
if not self.scroll_helper.cached_image:
return False
try:
# Inside the try, not before it: advancing the position and cropping
# the visible slice are as capable of raising as the display push,
# and the promise below is that no frame failure reaches the
# plugin's loop.
self.scroll_helper.update_scroll_position()
visible = self.scroll_helper.get_visible_portion()
if not visible:
return False
self.display_manager.image = visible
self.display_manager.update_display()
self._frame_count += 1
self.scroll_helper.log_frame_rate()
self._log_scroll_progress()
except Exception:
# A display failure must not propagate into the plugin's loop.
self.logger.exception("Error displaying scroll frame")
return False
return True
def _log_scroll_progress(self) -> None:
"""Emit a throttled progress line."""
now = time.time()
if now - self._last_log_time < self._log_interval:
return
self._last_log_time = now
elapsed = now - self._fps_sample_start
fps = self._frame_count / elapsed if elapsed > 0 else 0.0
self.logger.debug(
f"Scrolling {len(self._current_games)} {self._current_game_type} "
f"game(s) at {fps:.1f} FPS"
)
def is_scroll_complete(self) -> bool:
"""True when the strip has scrolled fully past the panel."""
return self.scroll_helper.is_scroll_complete()
def reset_scroll(self) -> None:
"""Return the strip to its starting position, keeping the content."""
self.scroll_helper.reset_scroll()
self._frame_count = 0
self._fps_sample_start = time.time()
self.logger.debug("Scroll position reset")
def clear(self) -> None:
"""Drop cached content and reset tracking state."""
self.scroll_helper.clear_cache()
self._current_games = []
self._current_game_type = ""
self._current_leagues = []
self._vegas_content_items = []
self._is_scrolling = False
self._scroll_start_time = None
self.logger.debug("Scroll display cleared")
# ------------------------------------------------------------------
# Introspection
# ------------------------------------------------------------------
def get_dynamic_duration(self) -> int:
"""How long this content needs to scroll fully, in seconds."""
return self.scroll_helper.get_dynamic_duration()
def has_cached_content(self) -> bool:
"""Whether content is prepared and ready to scroll."""
return bool(self.scroll_helper.cached_image)
def get_current_game_count(self) -> int:
return len(self._current_games)
def get_current_leagues(self) -> List[str]:
return list(self._current_leagues)
def get_scroll_info(self) -> Dict[str, Any]:
"""Helper state plus this display's tracking state, for logging/debug."""
info = self.scroll_helper.get_scroll_info()
info.update(
{
"game_count": len(self._current_games),
"game_type": self._current_game_type,
"leagues": self._current_leagues,
"is_scrolling": self._is_scrolling,
}
)
return info
class SportsScrollDisplayManager:
"""One :class:`SportsScrollDisplay` per game type ('live'/'recent'/'upcoming').
Subclasses set :attr:`display_class`; everything else was near-identical
across the eight plugin copies.
"""
#: The SportsScrollDisplay subclass to instantiate per game type.
display_class = SportsScrollDisplay
def __init__(
self,
display_manager,
config: Dict[str, Any],
custom_logger: Optional[logging.Logger] = None,
global_config: Optional[Dict[str, Any]] = None,
):
self.display_manager = display_manager
self.config = config
self.logger = custom_logger or logger
self.global_config = global_config or {}
self._scroll_displays: Dict[str, SportsScrollDisplay] = {}
# "" rather than None, matching SportsScrollDisplay's own empty value —
# both are falsy, so `game_type or self._current_game_type` behaved
# either way, but two spellings of "nothing active" across two classes
# is a trap for anyone comparing state between them.
self._current_game_type: str = ""
def get_scroll_display(self, game_type: str) -> SportsScrollDisplay:
"""The display for ``game_type``, created on first use."""
if game_type not in self._scroll_displays:
self._scroll_displays[game_type] = self.display_class(
self.display_manager,
self.config,
self.logger,
global_config=self.global_config,
)
return self._scroll_displays[game_type]
def prepare_and_display(
self,
games: List[Dict],
game_type: str,
leagues: List[str],
rankings_cache: Optional[Dict[str, int]] = None,
) -> bool:
"""Build content for ``game_type`` and make it the active strip."""
scroll_display = self.get_scroll_display(game_type)
try:
success = scroll_display.prepare_scroll_content(
games, game_type, leagues, rankings_cache
)
except Exception:
# prepare_scroll_content is subclass-implemented and builds cards
# straight from feed data, which is exactly where this PR's other
# crashes came from. One sport's bad payload must not take down the
# shared orchestration for the others.
self.logger.exception(
"Error preparing scroll content for game_type=%s", game_type
)
return False
if success:
self._current_game_type = game_type
return success
def display_frame(self, game_type: Optional[str] = None) -> bool:
"""Advance the active strip (or a named one) by one frame."""
game_type = game_type or self._current_game_type
if not game_type:
return False
scroll_display = self._scroll_displays.get(game_type)
if scroll_display is None:
return False
return scroll_display.display_scroll_frame()
def is_complete(self, game_type: Optional[str] = None) -> bool:
"""True when the strip has finished — including when there isn't one,
so a caller waiting on completion is never wedged."""
game_type = game_type or self._current_game_type
if not game_type:
return True
scroll_display = self._scroll_displays.get(game_type)
if scroll_display is None:
return True
return scroll_display.is_scroll_complete()
def clear_all(self) -> None:
"""Clear every display and forget which one was active."""
for scroll_display in self._scroll_displays.values():
scroll_display.clear()
self._current_game_type = ""
def get_all_vegas_content_items(self) -> List[Image.Image]:
"""Every display's Vegas items, for splicing into the marquee."""
items: List[Image.Image] = []
for scroll_display in self._scroll_displays.values():
vegas_items = getattr(scroll_display, "_vegas_content_items", None)
if vegas_items:
items.extend(vegas_items)
return items
+33 -103
View File
@@ -106,9 +106,14 @@ class ConfigManager:
Returns: Returns:
SaveResult with status and details SaveResult with status and details
""" """
# Load current secrets to preserve them (raises if unreadable — see # Load current secrets to preserve them
# _load_secrets_for_save) secrets_content = {}
secrets_content = self._load_secrets_for_save() if os.path.exists(self.secrets_path):
try:
with open(self.secrets_path, 'r') as f_secrets:
secrets_content = json.load(f_secrets)
except Exception as e:
self.logger.warning(f"Could not load secrets file {self.secrets_path} during save: {e}")
# Strip secrets from main config before saving # Strip secrets from main config before saving
config_to_write = self._strip_secrets_recursive(new_config_data, secrets_content) config_to_write = self._strip_secrets_recursive(new_config_data, secrets_content)
@@ -269,86 +274,35 @@ class ConfigManager:
self.logger.error(error_msg, exc_info=True) self.logger.error(error_msg, exc_info=True)
raise ConfigError(error_msg, config_path=self.config_path) from e raise ConfigError(error_msg, config_path=self.config_path) from e
@staticmethod
def _is_parallel_secrets_list(value: Any) -> bool:
"""True for the parallel-placeholder list shape emitted by
``secret_helpers.separate_secrets`` for array-item secrets: a
non-empty list whose elements are ALL dicts (``{}`` marks an item
with no secrets). Any other list-shaped secrets value is a
whole-key secret (e.g. a list of secret scalars)."""
return (isinstance(value, list) and bool(value)
and all(isinstance(item, dict) for item in value))
def _strip_secrets_recursive(self, data_to_filter: Dict[str, Any], secrets: Dict[str, Any]) -> Dict[str, Any]: def _strip_secrets_recursive(self, data_to_filter: Dict[str, Any], secrets: Dict[str, Any]) -> Dict[str, Any]:
"""Recursively remove secret keys from a dictionary.""" """Recursively remove secret keys from a dictionary."""
result = {} result = {}
for key, value in data_to_filter.items(): for key, value in data_to_filter.items():
if key not in secrets: if key in secrets:
if isinstance(value, dict) and isinstance(secrets[key], dict):
# This key is a shared group, recurse
stripped_sub_dict = self._strip_secrets_recursive(value, secrets[key])
if stripped_sub_dict: # Only add if there's non-secret data left
result[key] = stripped_sub_dict
# Else, it's a secret key at this level, so we skip it
else:
# This key is not in secrets, so we keep it # This key is not in secrets, so we keep it
result[key] = value result[key] = value
continue
sec = secrets[key]
if isinstance(value, dict) and isinstance(sec, dict):
# This key is a shared group, recurse
stripped_sub_dict = self._strip_secrets_recursive(value, sec)
if stripped_sub_dict: # Only add if there's non-secret data left
result[key] = stripped_sub_dict
elif isinstance(value, list) and self._is_parallel_secrets_list(sec):
# Parallel-list shape from separate_secrets: sec[i] holds the
# secret fields of value[i] ({} = item i has none). Strip each
# item and ALWAYS keep the list — indices must survive so the
# merge-on-load can realign secrets with their items. The
# regular list's length is authoritative: extra secrets
# entries are ignored.
stripped_items = []
for i, item in enumerate(value):
s_item = sec[i] if i < len(sec) else {}
if isinstance(item, dict) and s_item:
stripped_items.append(self._strip_secrets_recursive(item, s_item))
else:
stripped_items.append(item)
result[key] = stripped_items
# Else: whole-key secret (scalar, list of secret scalars, or a
# shape mismatch) -> drop the key entirely. Never leak.
return result return result
def _load_secrets_for_save(self) -> Dict[str, Any]:
"""Load config_secrets.json for stripping before a save.
A missing secrets file is fine (nothing to strip). But a file that
EXISTS and cannot be read or parsed means stripping is impossible
and the in-memory config being saved has secrets deep-merged into it,
so proceeding would write them into config.json in plaintext. That
was the historical behavior; it is now a hard refusal. The save
raises so the caller (and user) fixes the secrets file instead of
silently leaking its contents into the world-readable main config.
"""
if not os.path.exists(self.secrets_path):
return {}
try:
with open(self.secrets_path, 'r') as f_secrets:
return json.load(f_secrets)
# Only the expected read/parse failures — an unexpected implementation
# error should propagate as itself, not masquerade as a secrets-file
# problem. (JSONDecodeError and UnicodeDecodeError are ValueErrors.)
except (OSError, ValueError, RecursionError) as e:
error_msg = (
f"Refusing to save config: secrets file {self.secrets_path} exists "
f"but could not be loaded ({e}). Saving without it would write "
f"merged secret values into config.json in plaintext. Fix or "
f"remove the secrets file, then retry."
)
self.logger.error("[Config] %s", error_msg, exc_info=True)
raise ConfigError(error_msg, config_path=self.secrets_path) from e
def save_config(self, new_config_data: Dict[str, Any]) -> None: def save_config(self, new_config_data: Dict[str, Any]) -> None:
"""Save configuration to the main JSON file, stripping out secrets. """Save configuration to the main JSON file, stripping out secrets."""
secrets_content = {}
Raises ConfigError when the secrets file exists but cannot be loaded, if os.path.exists(self.secrets_path):
because stripping would be impossible and secrets would leak into try:
config.json. with open(self.secrets_path, 'r') as f_secrets:
""" secrets_content = json.load(f_secrets)
secrets_content = self._load_secrets_for_save() except Exception as e:
self.logger.warning(f"Could not load secrets file {self.secrets_path} during save: {e}")
# Continue without stripping if secrets can't be loaded, or handle as critical error
# For now, we'll proceed cautiously and save the full new_config_data if secrets are unreadable
# to prevent accidental data loss if the secrets file is temporarily corrupt.
# A more robust approach might be to fail the save or use a cached version of secrets.
config_to_write = self._strip_secrets_recursive(new_config_data, secrets_content) config_to_write = self._strip_secrets_recursive(new_config_data, secrets_content)
@@ -385,39 +339,11 @@ class ConfigManager:
return None return None
def _deep_merge(self, target: Dict[str, Any], source: Dict[str, Any]) -> None: def _deep_merge(self, target: Dict[str, Any], source: Dict[str, Any]) -> None:
"""Deep merge source dict into target dict. """Deep merge source dict into target dict."""
Sole call site: merging config_secrets.json into the loaded config.
Understands the parallel-list shape separate_secrets emits for
array-item secrets (see _is_parallel_secrets_list): each secrets
list item is merged into the config list item at the same index
({} placeholders skipped). The config list's length is
authoritative a user deleting an array item from config.json
must not have it resurrected from a stale secrets entry."""
for key, value in source.items(): for key, value in source.items():
if key in target and isinstance(target[key], dict) and isinstance(value, dict): if key in target and isinstance(target[key], dict) and isinstance(value, dict):
self._deep_merge(target[key], value) self._deep_merge(target[key], value)
elif (key in target and isinstance(target[key], list)
and self._is_parallel_secrets_list(value)):
tlist = target[key]
for i, s_item in enumerate(value):
if i >= len(tlist):
# Interpolate only config-side data here — nothing
# iterated out of the secrets dict (not even the key
# name) may reach the log.
self.logger.warning(
"A secrets list is longer than the config list it "
"parallels (config has %d item(s)); ignoring the "
"extra entries", len(tlist))
break
if not s_item:
continue # {} placeholder: item i has no secrets
if isinstance(tlist[i], dict):
self._deep_merge(tlist[i], s_item)
else:
tlist[i] = s_item # shape drift; the secret wins
else: else:
# Scalars AND whole-secret scalar arrays: replace (legacy).
target[key] = value target[key] = value
def _create_config_from_template(self) -> None: def _create_config_from_template(self) -> None:
@@ -523,6 +449,10 @@ class ConfigManager:
"""Get display configuration.""" """Get display configuration."""
return self.config.get('display', {}) return self.config.get('display', {})
def get_clock_config(self) -> Dict[str, Any]:
"""Get clock configuration."""
return self.config.get('clock', {})
def get_config(self) -> Dict[str, Any]: def get_config(self) -> Dict[str, Any]:
"""Get the full configuration dictionary. """Get the full configuration dictionary.

Some files were not shown because too many files have changed in this diff Show More