Files
LEDMatrix/docs/PLUGIN_ARCHITECTURE_SPEC.md
Chuck 7d71656cf1 Plugins (#145)
Chaotic mega-merge into main. THINGS WILL PROBABLY BE BROKEN


* chore: Update soccer-scoreboard submodule to merged commit

- Update submodule reference to include manifest.json v2 registry format
- Version updated to 1.0.1

* refactor: Remove test_mode and logo_dir config reading from base SportsCore

- Remove test_mode initialization and usage
- Remove logo_dir reading from mode_config
- Use LogoDownloader defaults directly for logo directories

* chore: Update plugin submodules after removing global properties

- Update basketball-scoreboard submodule (removed global test_mode, live_priority, dynamic_duration, logo_dir)
- Update soccer-scoreboard submodule (removed global test_mode, live_priority, dynamic_duration, logo_dir)

* feat(calendar): Add credentials.json file upload via web interface

- Add API endpoint /api/v3/plugins/calendar/upload-credentials for file upload
- Validate JSON format and Google OAuth structure
- Save file to plugin directory with secure permissions (0o600)
- Backup existing credentials.json before overwriting
- Add file upload widget support for string fields in config forms
- Add frontend handler handleCredentialsUpload() for single file uploads
- Update .gitignore to allow calendar submodule
- Update calendar submodule reference

* fix(web): Improve spacing for nested configuration sections

- Add dynamic margin based on nesting depth (mb-6 for deeply nested sections)
- Increase padding in nested content areas (py-3 to py-4)
- Add extra spacing after nested sections to prevent overlap
- Enhance CSS spacing for nested sections (1.5rem for nested, 2rem for deeply nested)
- Add padding-bottom to expanded nested content to prevent cutoff
- Fixes issue where game_limits and other nested settings were hidden under next section header

* chore(plugins): Update sports scoreboard plugins with live update interval fix

- Updated hockey-scoreboard, football-scoreboard, basketball-scoreboard, and soccer-scoreboard submodules
- All plugins now fix the interval selection bug that caused live games to update every 5 minutes instead of 30 seconds
- Ensures all live games update at the configured live_update_interval (30s) for timely score updates

* fix: Initialize test_mode in SportsLive and fix config migration

- Add test_mode initialization in SportsLive.__init__() to prevent AttributeError
- Remove invalid new_secrets parameter from save_config_atomic() call in config migration
- Fixes errors: 'NBALiveManager' object has no attribute 'test_mode'
- Fixes errors: ConfigManager.save_config_atomic() got unexpected keyword argument 'new_secrets'

* chore: Update submodules with test_mode initialization fixes

- Update basketball-scoreboard submodule
- Update soccer-scoreboard submodule

* fix(plugins): Auto-stash local changes before plugin updates

- Automatically stash uncommitted changes before git pull during plugin updates
- Prevents update failures when plugins have local modifications
- Improves error messages for git update failures
- Matches behavior of main LEDMatrix update process

* fix(basketball-scoreboard): Update submodule with timeout fix

- Updated basketball-scoreboard plugin to fix update() timeout issue
- Plugin now uses fire-and-forget odds fetching for upcoming games
- Prevents 30-second timeout when processing many upcoming games

Also fixed permission issue on devpi:
- Changed /var/cache/ledmatrix/display_on_demand_state.json permissions
  from 600 to 660 to allow web service (devpi user) to read the file

* fix(cache): Ensure cache files use 660 permissions for group access

- Updated setup_cache.sh to set file permissions to 660 (not 775)
- Updated first_time_install.sh to properly set cache file permissions
- Modified DiskCache to set 660 permissions when creating cache files
- Ensures display_on_demand_state.json and other cache files are readable
  by web service (devpi user) which is in ledmatrix group

This fixes permission issues where cache files were created with 600
permissions, preventing the web service from reading them. Now files
are created with 660 (rw-rw----) allowing group read access.

* fix(soccer-scoreboard): Update submodule with manifest fix

- Updated soccer-scoreboard plugin submodule
- Added missing entry_point and class_name to manifest.json
- Fixes plugin loading error: 'No class_name in manifest'

Also fixed cache file permissions on devpi server:
- Changed display_on_demand_state.json from 600 to 660 permissions
- Allows web service (devpi user) to read cache files

* fix(display): Remove update_display() calls from clear() to prevent black flash

Previously, display_manager.clear() was calling update_display() twice,
which immediately showed a black screen on the hardware before new
content could be drawn. This caused visible black flashes when switching
between modes, especially when plugins switch from general modes (e.g.,
football_upcoming) to specific sub-modes (e.g., nfl_upcoming).

Now clear() only prepares the buffer without updating the hardware.
Callers can decide when to update the display, allowing smooth transitions
from clear → draw → update_display() without intermediate black flashes.

Places that intentionally show a cleared screen (error cases) already
explicitly call update_display() after clear(), so backward compatibility
is maintained.

* fix(scroll): Prevent wrap-around before cycle completion in dynamic duration

- Check scroll completion BEFORE allowing wrap-around
- Clamp scroll_position when complete to prevent visual loop
- Only wrap-around if cycle is not complete yet
- Fixes issue where stocks plugin showed first stock again at end
- Completion logged only once to avoid spam
- Ensures smooth transition to next mode without visual repeat

* fix(on-demand): Ensure on-demand buttons work and display service runs correctly

- Add early stub functions for on-demand modal to ensure availability when Alpine.js initializes
- Increase on-demand request cache max_age from 5min to 1hr to prevent premature expiration
- Fixes issue where on-demand buttons were not functional due to timing issues
- Ensures display service properly picks up on-demand requests when started

* test: Add comprehensive test coverage (30%+)

- Add 100+ new tests across core components
- Add tests for LayoutManager (27 tests)
- Add tests for PluginLoader (14 tests)
- Add tests for SchemaManager (20 tests)
- Add tests for MemoryCache and DiskCache (24 tests)
- Add tests for TextHelper (9 tests)
- Expand error handling tests (7 new tests)
- Improve coverage from 25.63% to 30.26%
- All 237 tests passing

Test files added:
- test/test_layout_manager.py
- test/test_plugin_loader.py
- test/test_schema_manager.py
- test/test_text_helper.py
- test/test_config_service.py
- test/test_display_controller.py
- test/test_display_manager.py
- test/test_error_handling.py
- test/test_font_manager.py
- test/test_plugin_system.py

Updated:
- pytest.ini: Enable coverage reporting with 30% threshold
- test/conftest.py: Enhanced fixtures for better test isolation
- test/test_cache_manager.py: Expanded cache component tests
- test/test_config_manager.py: Additional config tests

Documentation:
- HOW_TO_RUN_TESTS.md: Guide for running and understanding tests

* test(web): Add comprehensive API endpoint tests

- Add 30 new tests for Flask API endpoints in test/test_web_api.py
- Cover config, system, display, plugins, fonts, and error handling APIs
- Increase test coverage from 30.26% to 30.87%
- All 267 tests passing

Tests cover:
- Config API: GET/POST main config, schedule, secrets
- System API: Status, version, system actions
- Display API: Current display, on-demand start/stop
- Plugins API: Installed plugins, health, config, operations, state
- Fonts API: Catalog, tokens, overrides
- Error handling: Invalid JSON, missing fields, 404s

* test(plugins): Add comprehensive integration tests for all plugins

- Add base test class for plugin integration tests
- Create integration tests for all 6 plugins:
  - basketball-scoreboard (11 tests)
  - calendar (10 tests)
  - clock-simple (11 tests)
  - odds-ticker (9 tests)
  - soccer-scoreboard (11 tests)
  - text-display (12 tests)
- Total: 64 new plugin integration tests
- Increase test coverage from 30.87% to 33.38%
- All 331 tests passing

Tests verify:
- Plugin loading and instantiation
- Required methods (update, display)
- Manifest validation
- Display modes
- Config schema validation
- Graceful handling of missing API credentials

Uses hybrid approach: integration tests in main repo,
plugin-specific unit tests remain in plugin submodules.

* Add mqtt-notifications plugin as submodule

* fix(sports): Respect games_to_show settings for favorite teams

- Fix upcoming games to show N games per team (not just 1)
- Fix recent games to show N games per team (not just 1)
- Add duplicate removal for games involving multiple favorite teams
- Match behavior of basketball-scoreboard plugin
- Affects NFL, NHL, and other sports using base_classes/sports.py

* chore: Remove debug instrumentation logs

- Remove temporary debug logging added during fix verification
- Fix confirmed working by user

* debug: Add instrumentation to debug configuration header visibility issue

* fix: Resolve nested section content sliding under next header

- Remove overflow-hidden from nested-section to allow proper document flow
- Add proper z-index and positioning to prevent overlap
- Add margin-top to nested sections for better spacing
- Remove debug instrumentation that was causing ERR_BLOCKED_BY_CLIENT errors

* fix: Prevent unnecessary plugin tab redraws

- Add check to only update tabs when plugin list actually changes
- Increase debounce timeout to batch rapid changes
- Compare plugin IDs before updating to avoid redundant redraws
- Fix setter to check for actual changes before triggering updates

* fix: Prevent form-groups from sliding out of view when nested sections expand

- Increase margin-bottom on nested-sections for better spacing
- Add clear: both to nested-sections to ensure proper document flow
- Change overflow to visible when expanded to allow natural flow
- Add margin-bottom to expanded content
- Add spacing rules for form-groups that follow nested sections
- Add clear spacer div after nested sections

* fix: Reduce excessive debug logging in generateConfigForm

- Only log once per plugin instead of on every function call
- Prevents log spam when Alpine.js re-renders the form multiple times
- Reduces console noise from 10+ logs per plugin to 1 log per plugin

* fix: Prevent nested section content from sliding out of view when expanded

- Remove overflow-hidden from nested-section in base.html (was causing clipping)
- Add scrollIntoView to scroll expanded sections into view within modal
- Set nested-section overflow to visible to prevent content clipping
- Add min-height to nested-content to ensure proper rendering
- Wait for animation to complete before scrolling into view

* fix: Prevent form-groups from overlapping and appearing outside view

- Change nested-section overflow to hidden by default, visible when expanded
- Add :has() selector to allow overflow when content is expanded
- Ensure form-groups after nested sections have proper spacing and positioning
- Add clear: both and width: 100% to prevent overlap
- Use !important for margin-top to ensure spacing is applied
- Ensure form-groups are in normal document flow with float: none

* fix: Use JavaScript to toggle overflow instead of :has() selector

- :has() selector may not be supported in all browsers
- Use JavaScript to set overflow: visible when expanded, hidden when collapsed
- This ensures better browser compatibility while maintaining functionality

* fix: Make parent sections expand when nested sections expand

- Add updateParentNestedContentHeight() helper to recursively update parent heights
- When a nested section expands, recalculate all parent nested-content max-heights
- Ensures parent sections (like NFL) expand to accommodate expanded child sections
- Updates parent heights both on expand and collapse for proper animation

* refactor: Simplify parent section expansion using CSS max-height: none

- Remove complex recursive parent height update function
- Use CSS max-height: none when expanded to allow natural expansion
- Parent sections automatically expand because nested-content has no height constraint
- Simpler and more maintainable solution

* refactor: Remove complex recursive parent height update function

- CSS max-height: none already handles parent expansion automatically
- No need for JavaScript to manually update parent heights
- Much simpler and cleaner solution

* debug: Add instrumentation to debug auto-collapse issue

- Add logging to track toggle calls and state changes
- Add guard to prevent multiple simultaneous toggles
- Pass event object to prevent bubbling
- Improve state detection logic
- Add return false to onclick handlers

* chore: Remove debug instrumentation from toggleNestedSection

- Remove all debug logging code
- Keep functional fixes: event handling, toggle guard, improved state detection
- Code is now clean and production-ready

* fix(web): Add browser refresh note to plugin fetch errors

* refactor(text-display): Update submodule to use ScrollHelper

* fix(text-display): Fix scrolling display issue - update position in display()

* feat(text-display): Add scroll_loop option and improve scroll speed control

* debug: Add instrumentation to track plugin enabled state changes

Added debug logging to investigate why plugins appear to disable themselves:
- Track enabled state during plugin load (before/after schema merge)
- Track enabled state during plugin reload
- Track enabled state preservation during config save
- Track state reconciliation fixes
- Track enabled state updates in on_config_change

This will help identify which code path is causing plugins to disable.

* debug: Fix debug log path to work on Pi

Changed hardcoded log path to use dynamic project root detection:
- Uses LEDMATRIX_ROOT env var if set
- Falls back to detecting project root by looking for config directory
- Creates .cursor directory if it doesn't exist
- Falls back to /tmp/ledmatrix_debug.log if all else fails
- Added better error handling with logger fallback

* Remove debug instrumentation for plugin enabled state tracking

Removed all debug logging that was added to track plugin enabled state changes.
The instrumentation has been removed as requested.

* Reorganize documentation and cleanup test files

- Move documentation files to docs/ directory
- Remove obsolete test files
- Update .gitignore and README

* feat(text-display): Switch to frame-based scrolling with high FPS support

* fix(text-display): Add backward compatibility for ScrollHelper sub-pixel scrolling

* feat(scroll_helper): Add sub-pixel scrolling support for smooth movement

- Add sub-pixel interpolation using scipy (if available) or numpy fallback
- Add set_sub_pixel_scrolling() method to enable/disable feature
- Implement _get_visible_portion_subpixel() for fractional pixel positioning
- Implement _interpolate_subpixel() for linear interpolation
- Prevents pixel skipping at slow scroll speeds
- Maintains backward compatibility with integer pixel path

* fix(scroll_helper): Reset last_update_time in reset_scroll() to prevent jump-ahead

- Reset last_update_time when resetting scroll position
- Prevents large delta_time on next update after reset
- Fixes issue where scroll would immediately complete again after reset
- Ensures smooth scrolling continuation after loop reset

* fix(scroll_helper): Fix numpy broadcasting error in sub-pixel interpolation

- Add output_width parameter to _interpolate_subpixel() for variable widths
- Fix wrap-around case to use correct widths for interpolation
- Handle edge cases where source array is smaller than expected
- Prevent 'could not broadcast input array' errors in sub-pixel scrolling
- Ensure proper width matching in all interpolation paths

* feat(scroll): Add frame-based scrolling mode for smooth LED matrix movement

- Add frame_based_scrolling flag to ScrollHelper
- When enabled, moves fixed pixels per step, throttled by scroll_delay
- Eliminates time-based jitter by ignoring frame timing variations
- Provides stock-ticker-like smooth, predictable scrolling
- Update text-display plugin to use frame-based mode

This addresses stuttering issues where time-based scrolling caused
visual jitter due to frame timing variations in the main display loop.

* fix(scroll): Fix NumPy broadcasting errors in sub-pixel wrap-around

- Ensure _interpolate_subpixel always returns exactly requested width
- Handle cases where scipy.ndimage.shift produces smaller arrays
- Add padding logic for wrap-around cases when arrays are smaller than expected
- Prevents 'could not broadcast input array' errors during scrolling

* refactor(scroll): Remove sub-pixel interpolation, use high FPS integer scrolling

- Disable sub-pixel scrolling by default in ScrollHelper
- Simplify get_visible_portion to always use integer pixel positioning
- Restore frame-based scrolling logic for smooth high FPS movement
- Use high frame rate (like stock ticker) for smoothness instead of interpolation
- Reduces complexity and eliminates broadcasting errors

* fix(scroll): Prevent large pixel jumps in frame-based scrolling

- Initialize last_step_time properly to prevent huge initial jumps
- Clamp scroll_speed to max 5 pixels/frame in frame-based mode
- Prevents 60-pixel jumps when scroll_speed is misconfigured
- Simplified step calculation to avoid lag catch-up jumps

* fix(text-display): Align config schema and add validation

- Update submodule reference
- Adds warning and logging for scroll_speed config issues

* fix(scroll): Simplify frame-based scrolling to match stock ticker behavior

- Remove throttling logic from frame-based scrolling
- Move pixels every call (DisplayController's loop timing controls rate)
- Add enable_scrolling attribute to text-display plugin for high-FPS treatment
- Matches stock ticker: simple, predictable movement every frame
- Eliminates jitter from timing mismatches between DisplayController and ScrollHelper

* fix(scroll): Restore scroll_delay throttling in frame-based mode

- Restore time-based throttling using scroll_delay
- Move pixels only when scroll_delay has passed
- Handle lag catch-up with reasonable caps to prevent huge jumps
- Preserve fractional timing for smooth operation
- Now scroll_delay actually controls the scroll speed as intended

* feat(text-display): Add FPS counter logging

- Update submodule reference
- Adds FPS tracking and logging every 5 seconds

* fix(text-display): Add display-width buffer so text scrolls completely off

- Update submodule reference
- Adds end buffer to ensure text exits viewport before looping

* fix: Prevent premature game switching in SportsLive

- Set last_game_switch when games load even if current_game already exists
- Set last_game_switch when same games update but it's still 0
- Add guard to prevent switching check when last_game_switch is 0
- Fixes issue where first game shows for only ~2 seconds before switching
- Also fixes random screen flickering when games change prematurely

* feat(plugins): Add branch selection support for plugin installation

- Add optional branch parameter to install_plugin() and install_from_url() in store_manager
- Update API endpoints to accept and pass branch parameter
- Update frontend JavaScript to support branch selection in install calls
- Maintain backward compatibility - branch parameter is optional everywhere
- Falls back to default branch logic if specified branch doesn't exist

* feat(plugins): Add UI for branch selection in plugin installation

- Add branch input field in 'Install Single Plugin' section
- Add global branch input for store installations
- Update JavaScript to read branch from input fields
- Branch input applies to all store installations when specified

* feat(plugins): Change branch selection to be per-plugin instead of global

- Remove global store branch input field
- Add individual branch input field to each plugin card in store
- Add branch input to custom registry plugin cards
- Each plugin can now have its own branch specified independently

* debug: Add logging to _should_exit_dynamic

* feat(display_controller): Add universal get_cycle_duration support for all plugins

UNIVERSAL FEATURE: Any plugin can now implement get_cycle_duration() to dynamically
calculate the total time needed to show all content for a mode.

New method:
- _plugin_cycle_duration(plugin, display_mode): Queries plugin for calculated duration

Integration:
- Display controller calls plugin.get_cycle_duration(display_mode)
- Uses returned duration as target (respecting max cap)
- Falls back to cap if not provided

Benefits:
- Football plugin: Show all games (3 games × 15s = 45s total)
- Basketball plugin: Could implement same logic
- Hockey/Baseball/any sport: Universal support
- Stock ticker: Could calculate based on number of stocks
- Weather: Could calculate based on forecast days

Example plugin implementation:

Result: Plugins control their own display duration based on actual content,
creating a smooth user experience where all content is shown before switching.

* debug: Add logging to cycle duration call

* debug: Change loop exit logs to INFO level

* fix: Change cycle duration logs to INFO level

* fix: Don't exit loop on False for dynamic duration plugins

For plugins with dynamic duration enabled, keep the display loop running
even when display() returns False. This allows games to continue rotating
within the calculated duration.

The loop will only exit when:
- Cycle is complete (plugin reports all content shown)
- Max duration is reached
- Mode is changed externally

* fix(schedule): Improve display scheduling functionality

- Add GET endpoint for schedule configuration retrieval
- Fix mode switching to clean up old config keys (days/start_time/end_time)
- Improve error handling with consistent error_response() usage
- Enhance display controller schedule checking with better edge case handling
- Add validation for time formats and ensure at least one day enabled in per-day mode
- Add debug logging for schedule state changes

Fixes issues where schedule mode switching left stale config causing incorrect behavior.

* fix(install): Add cmake and ninja-build to system dependencies

Resolves h3 package build failure during first-time installation.
The h3 package (dependency of timezonefinder) requires CMake and
Ninja to build from source. Adding these build tools ensures
successful installation of all Python dependencies.

* fix: Pass display_mode in ALL loop calls to maintain sticky manager

CRITICAL FIX: Display controller was only passing display_mode on first call,
causing plugins to fall back to internal mode cycling and bypass sticky
manager logic.

Now consistently passes display_mode=active_mode on every display() call in
both high-FPS and normal loops. This ensures plugins maintain mode context
and sticky manager state throughout the entire display duration.

* feat(install): Add OS check for Raspberry Pi OS Lite (Trixie)

- Verify OS is Raspberry Pi OS (raspbian/debian)
- Require Debian 13 (Trixie) specifically
- Check for Lite version (no desktop environment)
- Exit with clear error message if requirements not met
- Provide instructions for obtaining correct OS version

* fix(web-ui): Add missing notification handlers to quick action buttons

- Added hx-on:htmx:after-request handlers to all quick action buttons in overview.html
- Added hx-ext='json-enc' for proper JSON encoding
- Added missing notification handler for reboot button in index.html
- Users will now see toast notifications when actions complete or fail

* fix(display): Ensure consistent display mode handling in all plugin calls

- Updated display controller to consistently pass display_mode in all plugin display() calls.
- This change maintains the sticky manager state and ensures plugins retain their mode context throughout the display duration.
- Addresses issues with mode cycling and improves overall display reliability.

* fix(display): Enhance display mode persistence across plugin updates

- Updated display controller to ensure display_mode is consistently maintained during plugin updates.
- This change prevents unintended mode resets and improves the reliability of display transitions.
- Addresses issues with mode persistence, ensuring a smoother user experience across all plugins.

* feat: Add Olympics countdown plugin as submodule

- Add olympics-countdown plugin submodule
- Update .gitignore to allow olympics-countdown plugin
- Plugin automatically determines next Olympics and counts down to opening/closing ceremonies

* feat(web-ui): Add checkbox-group widget support for multi-select arrays

- Add checkbox-group widget rendering in plugins_manager.js
- Update form processing to handle checkbox groups with [] naming
- Support for friendly labels via x-options in config schemas
- Update odds-ticker submodule with checkbox-group implementation

* fix(plugins): Preserve enabled state when saving plugin config from main config endpoint

When saving plugin configuration through save_main_config endpoint, the enabled
field was not preserved if missing from the form data. This caused plugins to
be automatically disabled when users saved their configuration from the plugin
manager tab.

This fix adds the same enabled state preservation logic that exists in
save_plugin_config endpoint, ensuring consistent behavior across both endpoints.
The enabled state is preserved from current config, plugin instance, or defaults
to True to prevent unexpected disabling of plugins.

* fix(git): Resolve git status timeout and exclude plugins from base project updates

- Add --untracked-files=no flag to git status for faster execution
- Increase timeout from 5s to 30s for git status operations
- Add timeout exception handling for git status and stash operations
- Filter out plugins directory from git status checks (plugins are separate repos)
- Exclude plugins from stash operations using :!plugins pathspec
- Apply same fixes to plugin store manager update operations

* feat(plugins): Add granular scroll speed control to odds-ticker and leaderboard plugins

- Add display object to both plugins' config schemas with scroll_speed and scroll_delay
- Enable frame-based scrolling mode for precise FPS control (100 FPS for leaderboard)
- Add set_scroll_speed() and set_scroll_delay() methods to both plugins
- Maintain backward compatibility with scroll_pixels_per_second config
- Leaderboard plugin now explicitly sets target_fps to 100 for high-performance scrolling

* fix(scroll): Correct dynamic duration calculation for frame-based scrolling

- Fix calculate_dynamic_duration() to properly handle frame-based scrolling mode
- Convert scroll_speed from pixels/frame to pixels/second when in frame-based mode
- Prevents incorrect duration calculations (e.g., 2609s instead of 52s)
- Affects all plugins using ScrollHelper: odds-ticker, leaderboard, stocks, text-display
- Add debug logging to show scroll mode and effective speed

* Remove version logic from plugin system, use git commits instead

- Remove version parameter from install_plugin() method
- Rename fetch_latest_versions to fetch_commit_info throughout codebase
- Remove version fields from plugins.json registry (versions, latest_version, download_url_template)
- Remove version logging from plugin manager
- Update web UI to use fetch_commit_info parameter
- Update .gitignore to ignore all plugin folders (remove whitelist exceptions)
- Remove plugin directories from git index (plugins now installed via plugin store only)

Plugins now always install latest commit from default branch. Version fields
replaced with git commit SHA and commit dates. System uses git-based approach
for all plugin metadata.

* feat(plugins): Normalize all plugins as git submodules

- Convert all 18 plugins to git submodules for uniform management
- Add submodules for: baseball-scoreboard, christmas-countdown, football-scoreboard, hockey-scoreboard, ledmatrix-flights, ledmatrix-leaderboard, ledmatrix-music, ledmatrix-stocks, ledmatrix-weather, static-image
- Re-initialize mqtt-notifications as proper submodule
- Update .gitignore to allow all plugin submodules
- Add normalize_plugin_submodules.sh script for future plugin management

All plugins with GitHub repositories are now managed as git submodules,
ensuring consistent version control and easier updates.

* refactor(repository): Reorganize scripts and files into organized directory structure

- Move installation scripts to scripts/install/ (except first_time_install.sh)
- Move development scripts to scripts/dev/
- Move utility scripts to scripts/utils/
- Move systemd service files to systemd/
- Keep first_time_install.sh, start_display.sh, stop_display.sh in root
- Update all path references in scripts, documentation, and service files
- Add README.md files to new directories explaining their purpose
- Remove empty tools/ directory (contents moved to scripts/dev/)
- Add .gitkeep to data/ directory

* fix(scripts): Fix PROJECT_DIR path in start_web_conditionally.py after move to scripts/utils/

* fix(scripts): Fix PROJECT_DIR/PROJECT_ROOT path resolution in moved scripts

- Fix wifi_monitor_daemon.py to use project root instead of scripts/utils/
- Fix shell scripts in scripts/ to correctly resolve project root (go up one more level)
- Fix scripts in scripts/fix_perms/ to correctly resolve project root
- Update diagnose_web_interface.sh to reference moved start_web_conditionally.py path

All scripts now correctly determine project root after reorganization.

* fix(install): Update first_time_install.sh to detect and update service files with old paths

- Check for old paths in service files and reinstall if needed
- Always reinstall main service (install_service.sh is idempotent)
- This ensures existing installations get updated paths after reorganization

* fix(install): Update install_service.sh message to indicate it updates existing services

* fix(wifi): Enable WiFi scan to work when AP mode is active

- Temporarily disable AP mode during network scanning
- Automatically re-enable AP mode after scan completes
- Add proper error handling with try/finally to ensure AP mode restoration
- Add user notification when AP mode is temporarily disabled
- Improve error messages for common scanning failures
- Add timing delays for interface mode switching

* fix(wifi): Fix network parsing to handle frequency with 'MHz' suffix

- Strip 'MHz' suffix from frequency field before float conversion
- Add better error logging for parsing failures
- Fixes issue where all networks were silently skipped due to ValueError

* debug(wifi): Add console logging and Alpine.js reactivity fixes for network display

- Add console.log statements to debug network scanning
- Add x-effect to force Alpine.js reactivity updates
- Add unique keys to x-for template
- Add debug display showing network count
- Improve error handling and user feedback

* fix(wifi): Manually update select options instead of using Alpine.js x-for

- Replace Alpine.js x-for template with manual DOM manipulation
- Add updateSelectOptions() method to directly update select dropdown
- This fixes issue where networks weren't appearing in dropdown
- Alpine.js x-for inside select elements can be unreliable

* feat(web-ui): Add patternProperties support for dynamic key-value pairs

- Add UI support for patternProperties objects (custom_feeds, feed_logo_map)
- Implement key-value pair editor with add/remove functionality
- Add JavaScript functions for managing dynamic key-value pairs
- Update form submission to handle patternProperties JSON data
- Enable easy configuration of feed_logo_map in web UI

* chore: Update ledmatrix-news submodule to latest commit

* fix(plugins): Handle arrays of objects in config normalization

Fix configuration validation failure for static-image plugin by adding
recursive normalization support for arrays of objects. The normalize_config_values
function now properly handles arrays containing objects (like image_config.images)
by recursively normalizing each object in the array using the items schema properties.

This resolves the 'configuration validation failed' error when saving static
image plugin configuration with multiple images.

* fix(plugins): Handle union types in config normalization and form generation

Fix configuration validation for fields with union types like ['integer', 'null'].
The normalization function now properly handles:
- Union types in top-level fields (e.g., random_seed: ['integer', 'null'])
- Union types in array items
- Empty string to None conversion for nullable fields
- Form generation and submission for union types

This resolves validation errors when saving plugin configs with nullable
integer/number fields (e.g., rotation_settings.random_seed in static-image plugin).

Also improves UX by:
- Adding placeholder text for nullable fields explaining empty = use default
- Properly handling empty values in form submission for union types

* fix(plugins): Improve union type normalization with better edge case handling

Enhanced normalization for union types like ['integer', 'null']:
- Better handling of whitespace in string values
- More robust empty string to None conversion
- Fallback to None when conversion fails and null is allowed
- Added debug logging for troubleshooting normalization issues
- Improved handling of nested object fields with union types

This should resolve remaining validation errors for nullable integer/number
fields in nested objects (e.g., rotation_settings.random_seed).

* chore: Add ledmatrix-news plugin to .gitignore exceptions

* Fix web interface service script path in install_service.sh

- Updated ExecStart path from start_web_conditionally.py to scripts/utils/start_web_conditionally.py
- Updated diagnose_web_ui.sh to check for correct script path
- Fixes issue where web UI service fails to start due to incorrect script path

* Fix nested configuration section headers not expanding

Fixed toggleNestedSection function to properly calculate scrollHeight when
expanding nested configuration sections. The issue occurred when sections
started with display:none - the scrollHeight was being measured before the
browser had a chance to lay out the element, resulting in a value of 0.

Changes:
- Added setTimeout to delay scrollHeight measurement until after layout
- Added overflow handling during animations to prevent content jumping
- Added fallback for edge cases where scrollHeight might still be 0
- Set maxHeight to 'none' after expansion completes for natural growth
- Updated function in both base.html and plugins_manager.js

This fix applies to all plugins with nested configuration sections, including:
- Hockey/Football/Basketball/Baseball/Soccer scoreboards (customization, global sections)
- All plugins with transition, display, and other nested configuration objects

Fixes configuration header expansion issues across all plugins.

* Fix syntax error in first_time_install.sh step 8.5

Added missing 'fi' statement to close the if block in the WiFi monitor
service installation section. This resolves the 'unexpected end of file'
error that occurred at line 1385 during step 8.5.

* Fix WiFi UI: Display correct SSID and accurate signal strength

- Fix WiFi network selection dropdown not showing available networks
  - Replace manual DOM manipulation with Alpine.js x-for directive
  - Add fallback watcher to ensure select updates reactively

- Fix WiFi status display showing netplan connection name instead of SSID
  - Query actual SSID from device properties (802-11-wireless.ssid)
  - Add fallback methods to get SSID from active WiFi connection list

- Improve signal strength accuracy
  - Get signal directly from device properties (WIFI.SIGNAL)
  - Add multiple fallback methods for robust signal retrieval
  - Ensure signal percentage is accurate and up-to-date

* Improve WiFi connection UI and error handling

- Fix connect button disabled condition to check both selectedSSID and manualSSID
- Improve error handling to display actual server error messages from 400 responses
- Add step-by-step labels (Step 1, Step 2, Step 3) to clarify connection workflow
- Add visual feedback showing selected network in blue highlight box
- Improve password field labeling with helpful instructions
- Add auto-clear logic between dropdown and manual SSID entry
- Enhance backend validation with better error messages and logging
- Trim SSID whitespace before processing to prevent validation errors

* Add WiFi disconnect functionality for AP mode testing

- Add disconnect_from_network() method to WiFiManager
  - Disconnects from current WiFi network using nmcli
  - Automatically triggers AP mode check if auto_enable_ap_mode is enabled
  - Returns success/error status with descriptive messages

- Add /api/v3/wifi/disconnect API endpoint
  - POST endpoint to disconnect from current WiFi network
  - Includes proper error handling and logging

- Add disconnect button to WiFi status section
  - Only visible when connected to a network
  - Red styling to indicate disconnection action
  - Shows 'Disconnecting...' state during operation
  - Automatically refreshes status after disconnect

- Integrates with AP mode auto-enable functionality
  - When disconnected, automatically enables AP mode if configured
  - Perfect for testing captive portal and AP mode features

* Add explicit handling for broken pipe errors during plugin dependency installation

- Catch BrokenPipeError and OSError (errno 32) explicitly in all dependency installation methods
- Add clear error messages explaining network interruption or buffer overflow causes
- Improves error handling in store_manager, plugin_loader, and plugin_manager
- Helps diagnose 'Errno 32 Broken Pipe' errors during pip install operations

* Add WiFi permissions configuration script and integrate into first-time install

- Create configure_wifi_permissions.sh script
  - Configures passwordless sudo for nmcli commands
  - Configures PolicyKit rules for NetworkManager control
  - Fixes 'Not Authorized to control Networking' error
  - Allows web interface to connect/disconnect WiFi without password prompts

- Integrate WiFi permissions configuration into first_time_install.sh
  - Added as Step 10.1 after passwordless sudo configuration
  - Runs automatically during first-time installation
  - Ensures WiFi management works out of the box

- Resolves authorization errors when connecting/disconnecting WiFi networks
  - NetworkManager requires both sudo and PolicyKit permissions
  - Script configures both automatically for seamless WiFi management

* Add WiFi status LED message display integration

- Integrate WiFi status messages from wifi_manager into display_controller
- WiFi status messages interrupt normal rotation (but respect on-demand)
- Priority: on-demand > wifi-status > live-priority > normal rotation
- Safe implementation with comprehensive error handling
- Automatic cleanup of expired/corrupted status files
- Word-wrapping for long messages (max 2 lines)
- Centered text display with small font
- Non-intrusive: all errors are caught and logged, never crash controller

* Fix display loop issues: reduce log spam and handle missing plugins

- Change _should_exit_dynamic logging from INFO to DEBUG to reduce log spam
  in tight loops (every 8ms) that was causing high CPU usage
- Fix display loop not running when manager_to_display is None
- Add explicit check to set display_result=False when no plugin manager found
- Fix logic bug where manager_to_display was overwritten after circuit breaker skip
- Ensure proper mode rotation when plugins have no content or aren't found

* Add debug logging to diagnose display loop stuck issue

* Change debug logs to INFO level to diagnose display loop stuck

* Add schedule activation logging and ensure display is blanked when inactive

- Add clear INFO-level log message when schedule makes display inactive
- Track previous display state to detect schedule transitions
- Clear display when schedule makes it inactive to ensure blank screen
  (prevents showing initialization screen when schedule kicks in)
- Initialize _was_display_active state tracking in __init__

* Fix indentation errors in schedule state tracking

* Add rotation between hostname and IP address every 10 seconds

- Added _get_local_ip() method to detect device IP address
- Implemented automatic rotation between hostname and IP every 10 seconds
- Enhanced logging to include both hostname and IP in initialization
- Updated get_info() to expose device_ip and current_display_mode

* Add WiFi connection failsafe system

- Save original connection before attempting new connection
- Automatically restore original connection if new connection fails
- Enable AP mode as last resort if restoration fails
- Enhanced connection verification with multiple attempts
- Verify correct SSID (not just 'connected' status)
- Better error handling and exception recovery
- Prevents Pi from becoming unresponsive on connection failure
- Always ensures device remains accessible via original WiFi or AP mode

* feat(web): Improve web UI startup speed and fix cache permissions

- Defer plugin discovery until first API request (removed from startup)
- Add lazy loading to operation queue, state manager, and operation history
- Defer health monitor initialization until first request
- Fix cache directory permission issue:
  - Add systemd CacheDirectory feature for automatic cache dir creation
  - Add manual cache directory creation in install script as fallback
  - Improve cache manager logging (reduce alarming warnings)
- Fix syntax errors in wifi_manager.py (unclosed try blocks)

These changes significantly improve web UI startup time, especially with many
plugins installed, while maintaining full backward compatibility.

* feat(plugins): Improve GitHub token pop-up UX and combine warning/settings

- Fix visibility toggle to handle inline styles properly
- Remove redundant inline styles from HTML elements
- Combine warning banner and settings panel into unified component
- Add loading states to save/load token buttons
- Improve error handling with better user feedback
- Add token format validation (ghp_ or github_pat_ prefix)
- Auto-refresh GitHub auth status after saving token
- Hide warning banner when settings panel opens
- Clear input field after successful save for security

This creates a smoother UX flow where clicking 'Configure Token'
transitions from warning directly to configuration form.

* fix(wifi): Prevent WiFi radio disabling during AP mode disable

- Make NetworkManager restart conditional (only for hostapd mode)
- Add enhanced WiFi radio enable with retry and verification logic
- Add connectivity safety check before NetworkManager restart
- Ensure WiFi radio enabled after all AP mode disable operations
- Fix indentation bug in dnsmasq backup restoration logic
- Add pre-connection WiFi radio check for safety

Fixes issue where WiFi radio was being disabled when disabling AP mode,
especially when connected via Ethernet, making it impossible to enable
WiFi from the web UI.

* fix(plugin-templates): Fix unreachable fallback to expired cache in update() method

The exception handler in update() checked the cached variable, which would
always be None or falsy at that point. If fresh cached data existed, the
method returned early. If cached data was expired, it was filtered out by
max_age constraint. The fix retrieves cached data again in the exception
handler with a very large max_age (1 year) to effectively bypass expiration
check and allow fallback to expired data when fetch fails.

* fix(plugin-templates): Resolve plugin_id mismatch in test template setUp method

* feat(plugins): Standardize manifest version fields schema

- Consolidate version fields to use consistent naming:
  - compatible_versions: array of semver ranges (required)
  - min_ledmatrix_version: string (optional)
  - max_ledmatrix_version: string (optional)
  - versions[].ledmatrix_min_version: renamed from ledmatrix_min
- Add manifest schema validation (schema/manifest_schema.json)
- Update store_manager to validate version fields and schema
- Update template and all documentation examples to use standardized fields
- Add deprecation warnings for ledmatrix_version and ledmatrix_min fields

* fix(templates): Update plugin README template script path to correct location

* docs(plugin): Resolve conflicting version management guidance in .cursorrules

* chore(.gitignore): Consolidate plugin exclusion patterns

Remove unnecessary !plugins/*/.git pattern and consolidate duplicate
negations by keeping only trailing-slash directory exclusions.

* docs: Add language specifiers to code blocks in STATIC_IMAGE_MULTI_UPLOAD_PLAN.md

* fix(templates): Remove api_key from config.json example in plugin README template

Remove api_key field from config.json example to prevent credential leakage.
API keys should only be stored in config_secrets.json. Added clarifying note
about proper credential storage.

* docs(README): Add plugin installation and migration information

- Add plugin installation instructions via web interface and GitHub URL
- Add plugin migration guide for users upgrading from old managers
- Improve plugin documentation for new users

* docs(readme): Update donation links and add Discord acknowledgment

* docs: Add comprehensive API references and consolidate documentation

- Add API_REFERENCE.md with complete REST API documentation (50+ endpoints)
- Add PLUGIN_API_REFERENCE.md documenting Display Manager, Cache Manager, and Plugin Manager APIs
- Add ADVANCED_PLUGIN_DEVELOPMENT.md with advanced patterns and examples
- Add DEVELOPER_QUICK_REFERENCE.md for quick developer reference
- Consolidate plugin configuration docs into single PLUGIN_CONFIGURATION_GUIDE.md
- Archive completed implementation summaries to docs/archive/
- Enhance PLUGIN_DEVELOPMENT_GUIDE.md with API links and 3rd party submission guidelines
- Update docs/README.md with new API reference sections
- Update root README.md with documentation links

* fix(install): Fix IP detection and network diagnostics after fresh install

- Fix web-ui-info plugin IP detection to handle no internet, AP mode, and network state changes
- Replace socket-based detection with robust interface scanning using hostname -I and ip addr
- Add AP mode detection returning 192.168.4.1 when AP mode is active
- Add periodic IP refresh every 30 seconds to handle network state changes
- Improve network diagnostics in first_time_install.sh showing actual IPs, WiFi status, and AP mode
- Add WiFi connection check in WiFi monitor installation with warnings
- Enhance web service startup logging to show accessible IP addresses
- Update README with network troubleshooting section and fix port references (5001->5000)

Fixes issue where display showed incorrect IP (127.0.11:5000) and users couldn't access web UI after fresh install.

* chore: Add GitHub sponsor button configuration

* fix(wifi): Fix aggressive AP mode enabling and improve WiFi detection

Critical fixes:
- Change auto_enable_ap_mode default from True to False (manual enable only)
- Fixes issue where Pi would disconnect from network after code updates
- Matches documented behavior (was incorrectly defaulting to True in code)

Improvements:
- Add grace period: require 3 consecutive disconnected checks (90s) before enabling AP mode
- Prevents AP mode from enabling on transient network hiccups
- Improve WiFi status detection with retry logic and better nmcli parsing
- Enhanced logging for debugging WiFi connection issues
- Better handling of WiFi device detection (works with any wlan device)

This prevents the WiFi monitor from aggressively enabling AP mode and
disconnecting the Pi from the network when there are brief network issues
or during system initialization.

* fix(wifi): Revert auto_enable_ap_mode default to True with grace period protection

Change default back to True for auto_enable_ap_mode while keeping the grace
period protection that prevents interrupting valid WiFi connections.

- Default auto_enable_ap_mode back to True (useful for setup scenarios)
- Grace period (3 consecutive checks = 90s) prevents false positives
- Improved WiFi detection with retry logic ensures accurate status
- AP mode will auto-enable when truly disconnected, but won't interrupt
  valid connections due to transient detection issues

* fix(news): Update submodule reference for manifest fix

Update ledmatrix-news submodule to include the fixed manifest.json with
required entry_point and class_name fields.

* fix(news): Update submodule reference with validate_config addition

Update ledmatrix-news submodule to include validate_config method for
proper configuration validation.

* feat: Add of-the-day plugin as git submodule

- Add ledmatrix-of-the-day plugin as git submodule
- Rename submodule path from plugins/of-the-day to plugins/ledmatrix-of-the-day to match repository naming convention
- Update .gitignore to allow ledmatrix-of-the-day submodule
- Plugin includes fixes for display rendering and web UI configuration support

* fix(wifi): Make AP mode open network and fix WiFi page loading in AP mode

AP Mode Changes:
- Remove password requirement from AP mode (open network for easier setup)
- Update hostapd config to create open network (no WPA/WPA2)
- Update nmcli hotspot to create open network (no password parameter)

WiFi Page Loading Fixes:
- Download local copies of HTMX and Alpine.js libraries
- Auto-detect AP mode (192.168.4.x) and use local JS files instead of CDN
- Auto-open WiFi tab when accessing via AP mode IP
- Add fallback loading if HTMX fails to load
- Ensures WiFi setup page works in AP mode without internet access

This fixes the issue where the WiFi page wouldn't load on iPhone when
accessing via AP mode (192.168.4.1:5000) because CDN resources couldn't
be fetched without internet connectivity.

* feat(wifi): Add explicit network switching support with clean disconnection

WiFi Manager Improvements:
- Explicitly disconnect from current network before connecting to a new one
- Add skip_ap_check parameter to disconnect_from_network() to prevent AP mode
  from activating during network switches
- Check if already connected to target network to avoid unnecessary work
- Improved logging for network switching operations

Web UI Improvements:
- Detect and display network switching status in UI
- Show 'Switching from [old] to [new]...' message when switching networks
- Enhanced status reloading after connection (multiple checks at 2s, 5s, 10s)
- Better user feedback during network transitions

This ensures clean network switching without AP mode interruptions and
provides clear feedback to users when changing WiFi networks.

* fix(web-ui): Add fallback content loading when HTMX fails to load

Problem:
- After recent updates, web UI showed navigation and CPU status but main
  content tabs never loaded
- Content tabs depend on HTMX's 'revealed' trigger to load
- If HTMX failed to load or initialize, content would never appear

Solutions:
- Enhanced HTMX loading verification with timeout checks
- Added fallback direct fetch for overview tab if HTMX fails
- Added automatic tab content loading when tabs change
- Added loadTabContent() method to manually trigger content loading
- Added global 'htmx-load-failed' event for error handling
- Automatic retry after 5 seconds if HTMX isn't available
- Better error messages and console logging for debugging

This ensures the web UI loads content even if HTMX has issues,
providing graceful degradation and better user experience.

* feat(web-ui): Add support for plugin custom HTML widgets and static file serving

- Add x-widget: custom-html support in config schema generation
- Add loadCustomHtmlWidget() function to load HTML from plugin directories
- Add /api/v3/plugins/<plugin_id>/static/<file_path> endpoint for serving plugin static files
- Enhance execute_plugin_action() to pass params via stdin as JSON for scripts
- Add JSON output parsing for script action responses

These changes enable plugins to provide custom UI components while keeping
all functionality plugin-scoped. Used by of-the-day plugin for file management.

* fix(web-ui): Resolve Alpine.js initialization errors

- Prevent Alpine.js from auto-initializing before app() function is defined
- Add deferLoadingAlpine to ensure proper initialization order
- Make app() function globally available via window.app
- Fix 'app is not defined' and 'activeTab is not defined' errors
- Remove duplicate Alpine.start() calls that caused double initialization warnings

* fix(web-ui): Fix IndentationError in api_v3.py OAuth flow

- Fix indentation in if action_def.get('oauth_flow') block
- Properly indent try/except block and all nested code
- Resolves IndentationError that prevented web interface from starting

* fix(web-ui): Fix SyntaxError in api_v3.py else block

- Fix indentation of OAuth flow code inside else block
- Properly indent else block for simple script execution
- Resolves SyntaxError at line 3458 that prevented web interface from starting

* fix(web-ui): Restructure OAuth flow check to fix SyntaxError

- Move OAuth flow check before script execution in else block
- Remove unreachable code that was causing syntax error
- OAuth check now happens first, then falls back to script execution
- Resolves SyntaxError at line 3458

* fix(web-ui): Define app() function in head for Alpine.js initialization

- Define minimal app() function in head before Alpine.js loads
- Ensures app() is available when Alpine initializes
- Full implementation in body enhances/replaces the stub
- Fixes 'app is not defined' and 'activeTab is not defined' errors

* fix(web-ui): Ensure plugin tabs load when full app() implementation is available

- Update stub init() to detect and use full implementation when available
- Ensure full implementation properly replaces stub methods
- Call init() after merging to load plugins and set up watchers
- Fixes issue where installed plugins weren't showing in navigation bar

* fix(web-ui): Prevent 'Cannot redefine property' error for installedPlugins

- Check if window.installedPlugins property already exists before defining
- Make property configurable to allow redefinition if needed
- Add _initialized flag to prevent multiple init() calls
- Fixes TypeError when stub tries to enhance with full implementation

* fix(web-ui): Fix variable redeclaration errors in logs tab

- Replace let/const declarations with window properties to avoid redeclaration
- Use window._logsEventSource, window._allLogs, etc. to persist across HTMX reloads
- Clean up existing event source before reinitializing
- Remove and re-add event listeners to prevent duplicates
- Fixes 'Identifier has already been declared' error when accessing logs tab multiple times

* feat(web-ui): Add support for additionalProperties object rendering

- Add handler for objects with additionalProperties containing object schemas
- Render dynamic category controls with enable/disable toggles
- Display category metadata (display name, data file path)
- Used by of-the-day plugin for category management

* fix(wifi): Ensure AP mode hotspot is always open (no password)

Problem:
- LEDMatrix-Setup WiFi AP was still asking for password despite code changes
- Existing hotspot connections with passwords weren't being fully cleaned up
- NetworkManager might reuse old connection profiles with passwords

Solutions:
- More thorough cleanup: Delete all hotspot-related connections, not just known names
- Verification: Check if hotspot has password after creation
- Automatic fix: Remove password and restart connection if security is detected
- Better logging: Log when password is detected and removed

This ensures the AP mode hotspot is always open for easy setup access,
even if there were previously saved connections with passwords.

* fix(wifi): Improve network switching reliability and device state handling

Problem:
- Pi failing to switch WiFi networks via web UI
- Connection attempts happening before device is ready
- Disconnect not fully completing before new connection attempt
- Connection name lookup issues when SSID doesn't match connection name

Solutions:
- Improved disconnect logic: Disconnect specific connection first, then device
- Device state verification: Wait for device to be ready (disconnected/unavailable) before connecting
- Better connection lookup: Search by SSID, not just connection name
- Increased wait times: 2 seconds for disconnect to complete
- State checking before activating existing connections
- Enhanced error handling and logging throughout

This ensures network switching works reliably by properly managing device
state transitions and using correct connection identifiers.

* debug(web-ui): Add debug logging for custom HTML widget loading

- Add console logging to track widget generation
- Improve error messages with missing configuration details
- Help diagnose why file manager widget may not be appearing

* fix(web-ui): Fix [object Object] display in categories field

- Add type checking to ensure category values are strings before rendering
- Safely extract data_file and display_name properties
- Prevent object coercion issues in category display

* perf(web-ui): Optimize plugin loading in navigation bar

- Reduce stub init timeout from 100ms to 10ms for faster enhancement
- Change full implementation merge from 50ms setTimeout to requestAnimationFrame
- Add direct plugin loading in stub while waiting for full implementation
- Skip plugin reload in full implementation if already loaded by stub
- Significantly improves plugin tab loading speed in navigation bar

* feat(web-ui): Adapt file-upload widget for JSON files in of-the-day plugin

- Add specialized JSON upload/delete endpoints for of-the-day plugin
- Modify file-upload widget to support JSON files (file_type: json)
- Render JSON files with file-code icon instead of image preview
- Show entry count for JSON files
- Store files in plugins/ledmatrix-of-the-day/of_the_day/ directory
- Automatically update categories config when files are uploaded/deleted
- Populate uploaded_files array from categories on form load
- Remove custom HTML widget, use standard file-upload widget instead

* fix(web-ui): Add working updatePluginTabs to stub for immediate plugin tab rendering

- Stub's updatePluginTabs was empty, preventing tabs from showing
- Add basic implementation that creates plugin tabs in navigation bar
- Ensures plugin tabs appear immediately when plugins load, even before full implementation merges
- Fixes issue where plugin navigation bar wasn't working

* feat(api): Populate uploaded_files and categories from disk for of-the-day plugin

- Scan of_the_day directory for existing JSON files when loading config
- Populate uploaded_files array from files on disk
- Populate categories from files on disk if not in config
- Categories default to disabled, user can enable them
- Ensures existing JSON files (word_of_the_day.json, slovenian_word_of_the_day.json) appear in UI

* fix(api): Improve category merging logic for of-the-day plugin

- Preserve existing category enabled state when merging with files from disk
- Ensure all JSON files from disk appear in categories section
- Categories from files default to disabled, preserving user choices
- Properly merge existing config with scanned files

* fix(wifi): More aggressive password removal for AP mode hotspot

Problem:
- LEDMatrix-Setup network still asking for password despite previous fixes
- NetworkManager may add default security settings to hotspots
- Existing connections with passwords may not be fully cleaned up

Solutions:
- Always remove ALL security settings after creating hotspot (not just when detected)
- Remove multiple security settings: key-mgmt, psk, wep-key, auth-alg
- Verify security was removed and recreate connection if verification fails
- Improved cleanup: Delete connections by SSID match, not just by name
- Disconnect connections before deleting them
- Always restart connection after removing security to apply changes
- Better logging for debugging

This ensures the AP mode hotspot is always open, even if NetworkManager
tries to add default security settings.

* perf(web): Optimize web interface performance and fix JavaScript errors

- Add resource hints (preconnect, dns-prefetch) for CDN resources to reduce DNS lookup delays
- Fix duplicate response parsing bug in loadPluginConfig that was parsing JSON twice
- Replace direct fetch() calls with PluginAPI.getInstalledPlugins() to leverage caching and throttling
- Fix Alpine.js function availability issues with defensive checks and $nextTick
- Enhance request deduplication with debug logging and statistics
- Add response caching headers for static assets and API responses
- Add performance monitoring utilities with detailed metrics

Fixes console errors for loadPluginConfig and generateConfigForm not being defined.
Reduces duplicate API calls to /api/v3/plugins/installed endpoint.
Improves initial page load time with resource hints and optimized JavaScript loading.

* perf(web-ui): optimize CSS for Raspberry Pi performance

- Remove backdrop-filter blur from modal-backdrop
- Remove box-shadow transitions (use transform/opacity only)
- Remove button ::before pseudo-element animation
- Simplify skeleton loader (gradient to opacity pulse)
- Optimize transition utility (specific properties, not 'all')
- Improve color contrast for WCAG AA compliance
- Add CSS containment to cards, plugin-cards, modals
- Remove unused CSS classes (duration-300, divider, divider-light)
- Remove duplicate spacing utility classes

All animations now GPU-accelerated (transform/opacity only).
Optimized for low-powered Raspberry Pi devices.

* fix(web): Resolve ReferenceError for getInstalledPluginsSafe in v3 stub initialization

Move getInstalledPluginsSafe() function definition before the app() stub code that uses it. The function was previously defined at line 3756 but was being called at line 849 during Alpine.js initialization, causing a ReferenceError when loadInstalledPluginsDirectly() attempted to load plugins before the full implementation was ready.

* fix(web): Resolve TypeError for installedPlugins.map in plugin loading

Fix PluginAPI.getInstalledPlugins() to properly extract plugins array from API response structure. The API returns {status: 'success', data: {plugins: [...]}}, but the method was returning response.data (the object) instead of response.data.plugins (the array).

Changes:
- api_client.js: Extract plugins array from response.data.plugins
- plugins_manager.js: Add defensive array checks and handle array return value correctly
- base.html: Add defensive check in getInstalledPluginsSafe() to ensure plugins is always an array

This prevents 'installedPlugins.map is not a function' errors when loading plugins.

* style(web-ui): Enhance navigation bar styling for better readability

- Improve contrast: Change inactive tab text from gray-500 to gray-700
- Add gradient background and thicker border for active tabs
- Enhance hover states with background highlights
- Add smooth transitions using GPU-accelerated properties
- Update all navigation buttons (system tabs and plugin tabs)
- Add updatePluginTabStates() method for dynamic tab state management

All changes are CSS-only with zero performance overhead.

* fix(web-ui): Optimize plugin loading and reduce initialization errors

- Make generateConfigForm accessible to inline Alpine components via parent scope
- Consolidate plugin initialization to prevent duplicate API calls
- Fix script execution from HTMX-loaded content by extracting scripts before DOM insertion
- Add request deduplication to loadInstalledPlugins() to prevent concurrent requests
- Improve Alpine component initialization with proper guards and fallbacks

This eliminates 'generateConfigForm is not defined' errors and reduces plugin
API calls from 3-4 duplicate calls to 1 per page load, significantly improving
page load performance.

* fix(web-ui): Add guard check for generateConfigForm to prevent Alpine errors

Add typeof check in x-show to prevent Alpine from evaluating generateConfigForm
before the component methods are fully initialized. This eliminates the
'generateConfigForm is not defined' error that was occurring during component
initialization.

* fix(web-ui): Fix try-catch block structure in script execution code

Correct the nesting of try-catch block inside the if statement for script execution.
The catch block was incorrectly placed after the else clause, causing a syntax error.

* fix(web-ui): Escape quotes in querySelector to avoid HTML attribute conflicts

Change double quotes to single quotes in the CSS selector to prevent conflicts
with HTML attribute parsing when the x-data expression is embedded.

* style(web): Improve button text readability in Quick Actions section

* fix(web): Resolve Alpine.js expression errors in plugin configuration component

- Capture plugin from parent scope into component data to fix parsing errors
- Update all plugin references to use this.plugin in component methods
- Fix x-init to properly call loadPluginConfig method
- Resolves 'Uncaught ReferenceError' for isOnDemandLoading, onDemandLastUpdated, and other component properties

* fix(web): Fix remaining Alpine.js scope issues in plugin configuration

- Use this.generateConfigForm in typeof checks and method calls
- Fix form submission to use this.plugin.id
- Use $root. prefix for parent scope function calls (refreshPlugin, updatePlugin, etc.)
- Fix confirm dialog string interpolation
- Ensures all component methods and properties are properly scoped

* fix(web): Add this. prefix to all Alpine.js component property references

- Fix all template expressions to use this. prefix for component properties
- Update isOnDemandLoading, onDemandLastUpdated, onDemandRefreshing references
- Update onDemandStatusClass, onDemandStatusText, onDemandServiceClass, onDemandServiceText
- Update disableRunButton, canStopOnDemand, showEnableHint, loading references
- Ensures Alpine.js can properly resolve all component getters and properties

* fix(web): Resolve Alpine.js expression errors in plugin configuration

- Move complex x-data object to pluginConfigData() function for better parsing
- Fix all template expressions to use this.plugin instead of plugin
- Add this. prefix to all method calls in event handlers
- Fix duplicate x-on:click attribute on uninstall button
- Add proper loading state management in loadPluginConfig method

This resolves the 'Invalid or unexpected token' and 'Uncaught ReferenceError'
errors in the browser console.

* fix(web): Fix plugin undefined errors in Alpine.js plugin configuration

- Change x-data initialization to capture plugin from loop scope first
- Use Object.assign in x-init to merge pluginConfigData properties
- Add safety check in pluginConfigData function for undefined plugins
- Ensure plugin is available before accessing properties in expressions

This resolves the 'Cannot read properties of undefined' errors by ensuring
the plugin object is properly captured from the x-for loop scope before
any template expressions try to access it.

* style(web): Make Quick Actions button text styling consistent

- Update Start Display, Stop Display, and Reboot System buttons
- Change from text-sm font-medium to text-base font-semibold
- All Quick Actions buttons now have consistent bold, larger text
- Matches the styling of Update Code, Restart Display Service, and Restart Web Service buttons

* fix(wifi): Properly handle AP mode disable during WiFi connection

- Check return value of disable_ap_mode() before proceeding with connection
- Add verification loop to ensure AP mode is actually disabled
- Increase wait time to 5 seconds for NetworkManager restart stabilization
- Return clear error messages if AP mode cannot be disabled
- Prevents connection failures when switching networks from web UI or AP mode

This fixes the issue where WiFi network switching would fail silently when
AP mode disable failed, leaving the system in an inconsistent state.

* fix(web): Handle API response errors in plugin configuration loading

- Add null/undefined checks before accessing API response status
- Set fallback defaults when API responses don't have status 'success'
- Add error handling for batch API requests with fallback to individual requests
- Add .catch() handlers to individual fetch calls to prevent unhandled rejections
- Add console warnings to help debug API response failures
- Fix applies to both main loadPluginConfig and PluginConfigHelpers.loadPluginConfig

This fixes the issue where plugin configuration sections would get stuck
showing the loading animation when API responses failed or returned error status.

* fix(web): Fix Alpine.js reactivity for plugin config by using direct x-data

Changed from Object.assign pattern to direct x-data assignment to ensure
Alpine.js properly tracks reactive properties. The previous approach used
Object.assign to merge properties into the component after initialization,
which caused Alpine to not detect changes to config/schema properties.

The fix uses pluginConfigData(plugin) directly as x-data, ensuring all
properties including config, schema, loading, etc. are reactive from
component initialization.

* fix(web): Ensure plugin variable is captured in x-data scope

Use spread operator to merge pluginConfigData properties while explicitly
capturing the plugin variable from outer x-for scope. This fixes undefined
plugin errors when Alpine evaluates the component data.

* fix(web): Use $data for Alpine.js reactivity when merging plugin config

Use Object.assign with Alpine's $data reactive proxy instead of this to
ensure added properties are properly reactive. This fixes the issue where
plugin variable scoping from x-for wasn't accessible in x-data expressions.

* fix(web): Remove incorrect 'this.' prefix in Alpine.js template expressions

Alpine.js template expressions (x-show, x-html, x-text, x-on) use the
component data as the implicit context, so 'this.' prefix is incorrect.
In template expressions, 'this' refers to the DOM element, not the
component data.

Changes:
- Replace 'this.plugin.' with 'plugin.' in all template expressions (19 instances)
- Replace 'this.loading' with 'loading' in x-show directives
- Replace 'this.generateConfigForm' with 'generateConfigForm' in x-show/x-html
- Replace 'this.savePluginConfig' with 'savePluginConfig' in x-on:submit
- Replace 'this.config/schema/webUiActions' with direct property access
- Use '$data.loadPluginConfig' in x-init for explicit method call

Note: 'this.' is still correct inside JavaScript method definitions within
pluginConfigData() function since those run with proper object context.

* fix(web): Prevent infinite recursion in plugin config methods

Add 'parent !== this' check to loadPluginConfig, generateConfigForm, and
savePluginConfig methods in pluginConfigData to prevent infinite recursion
when the component tries to delegate to a parent that resolves to itself.

This fixes the 'Maximum call stack size exceeded' error that occurred when
the nested Alpine component's $root reference resolved to a component that
had the same delegating methods via Object.assign.

* fix(web): Resolve infinite recursion in plugin config by calling $root directly

The previous implementation had delegating methods (generateConfigForm,
savePluginConfig) in pluginConfigData that tried to call parent.method(),
but the parent detection via getParentApp() was causing circular calls
because multiple components had the same methods.

Changes:
- Template now calls $root.generateConfigForm() and $root.savePluginConfig()
  directly instead of going through nested component delegation
- Removed delegating generateConfigForm and savePluginConfig from pluginConfigData
- Removed getParentApp() helper that was enabling the circular calls
- Simplified loadPluginConfig to use PluginConfigHelpers directly

This fixes the 'Maximum call stack size exceeded' error when rendering
plugin configuration forms.

* fix(web): Use window.PluginConfigHelpers instead of $root for plugin config

The $root magic variable in Alpine.js doesn't correctly reference the
app() component's data scope from nested x-data contexts. This causes
generateConfigForm and savePluginConfig to be undefined.

Changed to use window.PluginConfigHelpers which has explicit logic to
find and use the app component's methods.

* fix(web): Use direct x-data initialization for plugin config reactivity

Changed from Object.assign($data, pluginConfigData(plugin)) to
x-data="pluginConfigData(plugin)" to ensure Alpine.js properly
tracks reactivity for all plugin config properties. This fixes
the issue where all plugin tabs were showing the same config.

* refactor(web): Implement server-side plugin config rendering with HTMX

Major architectural improvement to plugin configuration management:

- Add server-side Jinja2 template for plugin config forms
  (web_interface/templates/v3/partials/plugin_config.html)
- Add Flask route to serve plugin config partials on-demand
- Replace complex client-side form generation with HTMX lazy loading
- Add Alpine.js store for centralized plugin state management
- Mark old pluginConfigData and PluginConfigHelpers as deprecated

Benefits:
- Lazy loading: configs only load when tab is accessed
- Server-side rendering: reduces client-side complexity
- Better performance: especially on Raspberry Pi
- Cleaner code: Jinja2 macros replace JS string templates
- More maintainable: form logic in one place (server)

The old client-side code is preserved for backwards compatibility
but is no longer used by the main plugin configuration UI.

* fix(web): Trigger HTMX manually after Alpine renders plugin tabs

HTMX processes attributes at page load time, before Alpine.js
renders dynamic content. Changed from :hx-get attribute to
x-init with htmx.ajax() to properly trigger the request after
the element is rendered.

* fix(web): Remove duplicate 'enabled' toggle from plugin config form

The 'enabled' field was appearing twice in plugin configuration:
1. Header toggle (quick action, uses HTMX)
2. Configuration form (from schema, requires save)

Now only the header toggle is shown, avoiding user confusion.
The 'enabled' key is explicitly skipped when rendering schema properties.

* perf(web): Optimize plugin manager with request caching and init guards

Major performance improvements to plugins_manager.js:

1. Request Deduplication & Caching
   - Added pluginLoadCache with 3-second TTL
   - Subsequent calls return cached data instead of making API requests
   - In-flight request deduplication prevents parallel duplicate fetches
   - Added refreshInstalledPlugins() for explicit force-refresh

2. Initialization Guards
   - Added pluginsInitialized flag to prevent multiple initializePlugins() calls
   - Added _eventDelegationSetup guard on container to prevent duplicate listeners
   - Added _listenerSetup guards on search/category inputs

3. Debug Logging Control
   - Added PLUGIN_DEBUG flag (localStorage.setItem('pluginDebug', 'true'))
   - Most console.log calls now use pluginLog() which only logs when debug enabled
   - Reduces console noise from ~150 logs to ~10 in production

Expected improvements:
- API calls reduced from 6+ to 2 on page load
- Event listeners no longer duplicated
- Cleaner console output
- Faster perceived performance

* fix(web): Handle missing search elements in searchPluginStore

The searchPluginStore function was failing silently when called before
the plugin-search and plugin-category elements existed in the DOM.
This caused the plugin store to never load.

Now safely checks if elements exist before accessing their values.

* fix(web): Ensure plugin store loads via pluginManager.searchPluginStore

- Exposed searchPluginStore on window.pluginManager for easier access
- Updated base.html to fallback to pluginManager.searchPluginStore
- Added logging when loading plugin store

* fix(web): Expose searchPluginStore from inside the IIFE

The function was defined inside the IIFE but only exposed after the IIFE
ended, where the function was out of scope. Now exposed immediately after
definition inside the IIFE.

* fix(web): Add cache-busting version to plugins_manager.js URL

Static JS files were being aggressively cached, preventing updates
from being loaded by browsers.

* fix(web): Fix pluginLog reference error outside IIFE

pluginLog is defined inside the IIFE, so use _PLUGIN_DEBUG_EARLY and
console.log directly for code outside the IIFE.

* chore(web): Update plugins_manager.js cache version

* fix(web): Defer plugin store render when grid not ready

Instead of showing an error when plugin-store-grid doesn't exist,
store plugins in window.__pendingStorePlugins for later rendering
when the tab loads (consistent with how installed plugins work).

* chore: Bump JS cache version

* fix(web): Restore enabledBool variable in plugin render

Variable was removed during debug logging optimization but was still
being used in the template string for toggle switch rendering.

* fix(ui): Add header and improve categories section rendering

- Add proper header (h4) to categories section with label
- Add debug logging to diagnose categories field rendering
- Improve additionalProperties condition check readability

* fix(ui): Improve additionalProperties condition check

- Explicitly exclude objects with properties to avoid conflicts
- Ensure categories section is properly detected and rendered
- Categories should show as header with toggles, not text box

* fix(web-ui): Fix JSON parsing errors and default value loading for plugin configs

- Fix JSON parsing errors when saving file upload fields by properly unescaping HTML entities
- Merge config with schema defaults when loading plugin config so form shows default values
- Improve default value handling in form generation for nested objects and arrays
- Add better error handling for malformed JSON in file upload fields

* fix(plugins): Return plugins array from getInstalledPlugins() instead of data object

Fixed PluginAPI.getInstalledPlugins() to return response.data.plugins (array)
instead of response.data (object). This was preventing window.installedPlugins
from being set correctly, which caused plugin configuration tabs to not appear
and prevented users from saving plugin configurations via the web UI.

The fix ensures that:
- window.installedPlugins is properly populated with plugin array
- Plugin tabs are created automatically on page load
- Configuration forms and save buttons are rendered correctly
- Save functionality works as expected

* fix(api): Support form data submission for plugin config saves

The HTMX form submissions use application/x-www-form-urlencoded format
instead of JSON. This update allows the /api/v3/plugins/config POST
endpoint to accept both formats:

- JSON: plugin_id and config in request body (existing behavior)
- Form data: plugin_id from query string, config fields from form

Added _parse_form_value helper to properly convert form strings to
appropriate Python types (bool, int, float, JSON arrays/objects).

* debug: Add form data logging to diagnose config save issue

* fix(web): Re-discover plugins before loading config partial

The plugin config partial was returning 'not found' for plugins
because the plugin manifests weren't loaded. The installed plugins
API was working because it calls discover_plugins() first.

Changes:
- Add discover_plugins() call in _load_plugin_config_partial when
  plugin info is not found on first try
- Remove debug logging from form data handling

* fix(web): Comprehensive plugin config save improvements

SWEEPING FIX for plugin configuration saving issues:

1. Form data now MERGES with existing config instead of replacing
   - Partial form submissions (missing fields) no longer wipe out
     existing config values
   - Fixes plugins with complex schemas (football, clock, etc.)

2. Improved nested value handling with _set_nested_value helper
   - Correctly handles deeply nested structures like customization
   - Properly merges when intermediate objects already exist

3. Better JSON parsing for arrays
   - RGB color arrays like [255, 0, 0] now parse correctly
   - Parse JSON before trying number conversion

4. Bump cache version to force JS reload

* fix(web): Add early stubs for updatePlugin and uninstallPlugin

Ensures these functions are available immediately when the page loads,
even before the full IIFE executes. Provides immediate user feedback
and makes API calls directly.

This fixes the 'Update button does not work' issue by ensuring the
function is always defined and callable.

* fix(web): Support form data in toggle endpoint

The toggle endpoint now accepts both JSON and HTMX form submissions.
Also updated the plugin config template to send the enabled state
via hx-vals when the checkbox changes.

Fixes: 415 Unsupported Media Type error when toggling plugins

* fix(web): Prevent config duplication when toggling plugins

Changed handleToggleResponse to update UI in place instead of
refreshing the entire config partial, which was causing duplication.

Also improved refreshPluginConfig with proper container targeting
and concurrent refresh prevention (though it's no longer needed
for toggles since we update in place).

* fix(api): Schema-aware form value parsing for plugin configs

Major fix for plugin config saving issues:

1. Load schema BEFORE processing form data to enable type-aware parsing
2. New _parse_form_value_with_schema() function that:
   - Converts comma-separated strings to arrays when schema says 'array'
   - Parses JSON strings for arrays/objects
   - Handles empty strings for arrays (returns [] instead of None)
   - Uses schema to determine correct number types
3. Post-processing to ensure None arrays get converted to empty arrays
4. Proper handling of nested object fields

Fixes validation errors:
- 'category_order': Expected type array, got str
- 'categories': Expected type object, got str
- 'uploaded_files': Expected type array, got NoneType
- RGB color arrays: Expected type array, got str

* fix(web): Make plugin config handlers idempotent and remove scripts from HTMX partials

CRITICAL FIX for script redeclaration errors:

1. Removed all <script> tags from plugin_config.html partial
   - Scripts were being re-executed on every HTMX swap
   - Caused 'Identifier already declared' errors

2. Moved all handler functions to base.html with idempotent initialization
   - Added window.__pluginConfigHandlersInitialized guard
   - Functions only initialized once, even if script runs multiple times
   - All state stored on window object (e.g., window.pluginConfigRefreshInProgress)

3. Enhanced error logging:
   - Client-side: Logs form payload, response status, and parsed error details
   - Server-side: Logs raw form data and parsed config on validation failures

4. Functions moved to window scope:
   - toggleSection
   - handleConfigSave (with detailed error logging)
   - handleToggleResponse (updates UI in place, no refresh)
   - handlePluginUpdate
   - refreshPluginConfig (with duplicate prevention)
   - runPluginOnDemand
   - stopOnDemand
   - executePluginAction

This ensures HTMX-swapped fragments only contain HTML, and all
scripts run once in the base layout.

* fix(api): Filter config to only schema-defined fields before validation

When merging with existing_config, fields not in the plugin's schema
(like high_performance_transitions, transition, dynamic_duration)
were being preserved, causing validation failures when
additionalProperties is false.

Add _filter_config_by_schema() function to recursively filter config
to only include fields defined in the schema before validation.

This fixes validation errors like:
- 'Additional properties are not allowed (high_performance_transitions, transition were unexpected)'

* fix(web): Improve update plugin error handling and support form data

1. Enhanced updatePlugin JavaScript function:
   - Validates pluginId before sending request
   - Checks response.ok before parsing JSON
   - Better error logging with request/response details
   - Handles both successful and error responses properly

2. Update endpoint now supports both JSON and form data:
   - Similar to config endpoint, accepts plugin_id from query string or form
   - Better error messages and debug logging

3. Prevent duplicate function definitions:
   - Second updatePlugin definition checks if improved version exists
   - Both definitions now have consistent error handling

Fixes: 400 BAD REQUEST 'Request body must be valid JSON' error

* fix(web): Show correct 'update' message instead of 'save' for plugin updates

The handlePluginUpdate function now:
1. Checks actual HTTP status code (not just event.detail.successful)
2. Parses JSON response to get server's actual message
3. Replaces 'save' with 'update' if message incorrectly says 'save'

Fixes: Update button showing 'saved successfully' instead of
'updated successfully'

* fix(web): Execute plugin updates immediately instead of queuing

Plugin updates are now executed directly (synchronously) instead of
being queued for async processing. This provides immediate feedback
to users about whether the update succeeded or failed.

Updates are fast git pull operations, so they don't need async
processing. The operation queue is reserved for longer operations
like install/uninstall.

Fixes: Update button not actually updating plugins (operations were
queued but users didn't see results)

* fix(web): Ensure toggleSection function is always available for collapsible headers

Moved toggleSection outside the initialization guard block so it's
always defined, even if the plugin config handlers have already been
initialized. This ensures collapsible sections in plugin config forms
work correctly.

Added debug logging to help diagnose if sections/icons aren't found.

Fixes: Collapsible headers in plugin config schema not collapsing

* fix(web): Improve toggleSection to explicitly show/hide collapsible content

Changed from classList.toggle() to explicit add/remove of 'hidden' class
based on current state. This ensures the content visibility is properly
controlled when collapsing/expanding sections.

Added better error checking and state detection for more reliable
collapsible section behavior.

* fix(web): Load plugin tabs on page load instead of waiting for plugin manager tab click

The stub's loadInstalledPlugins was an empty function, so plugin tabs
weren't loading until the plugin manager tab was clicked. Now the stub
implementation:
1. Tries to use global window.loadInstalledPlugins if available
2. Falls back to window.pluginManager.loadInstalledPlugins
3. Finally falls back to direct loading via loadInstalledPluginsDirectly
4. Always updates tabs after loading plugins

This ensures plugin navigation tabs are available immediately on page load.

Fixes: Plugin tabs only loading after clicking plugin manager tab

* fix(web): Ensure plugin navigation tabs load on any page regardless of active tab

Multiple improvements to ensure plugin tabs are always visible:

1. Stub's loadInstalledPluginsDirectly now waits for DOM to be ready
   before updating tabs, using requestAnimationFrame for proper timing

2. Stub's init() now has a retry mechanism that periodically checks
   if plugins have been loaded by plugins_manager.js and updates tabs
   accordingly (checks for 2 seconds)

3. Full implementation's init() now properly handles async plugin loading
   and ensures tabs are updated after loading completes, checking
   window.installedPlugins first before attempting to load

4. Both stub and full implementation ensure tabs update using $nextTick
   to wait for Alpine.js rendering cycle

This ensures plugin navigation tabs are visible immediately when the
page loads, regardless of whether the user is on overview, plugin manager,
or any other tab.

Fixes: Plugin tabs only appearing after clicking plugin manager tab

* fix(web): Fix restart display button not working

The initPluginsPage function was returning early before event listeners
were set up, making all the event listener code unreachable. Moved the
return statement to after all event listeners are attached.

This fixes the restart display button and all other buttons in the
plugin manager (refresh plugins, update all, search, etc.) that depend
on event listeners being set up.

Fixes: Restart Display button not working in plugin manager

* fix(web-ui): Improve categories field rendering for of-the-day plugin

- Add more explicit condition checking for additionalProperties objects
- Add debug logging specifically for categories field
- Add fallback handler for objects that don't match special cases (render as JSON textarea)
- Ensure categories section displays correctly with toggle cards instead of plain text

* fix(install): Prevent following broken symlinks during file ownership setup

- Add -P flag to find commands to prevent following symlinks when traversing
- Add -h flag to chown to operate on symlinks themselves rather than targets
- Exclude scripts/dev/plugins directory which contains development symlinks
- Fixes error when chown tries to dereference broken symlinks with extra LEDMatrix in path

* fix(scroll): Ensure scroll completes fully before switching displays

- Add display_width to total scroll distance calculation
- Scroll now continues until content is completely off screen
- Update scroll completion check to use total_scroll_width + display_width
- Prevents scroll from being cut off mid-way when switching to next display

* fix(install): Remove unsupported -P flag from find commands

- Remove -P flag which is not supported on all find versions
- Keep -h flag on chown to operate on symlinks themselves
- Change to {} \; syntax for better error handling
- Add error suppression to continue on broken symlinks
- Exclude scripts/dev/plugins directory to prevent traversal into broken symlinks

* docs(wifi): Add trailing newline to WiFi AP failover setup guide

* fix(web): Suppress non-critical socket errors and fix WiFi permissions script

- Add error filtering in web interface to suppress harmless client disconnection errors
- Downgrade 'No route to host' and broken pipe errors from ERROR to DEBUG level
- Fix WiFi permissions script to use mktemp instead of manual temp file creation
- Add cleanup trap to ensure temp files are removed on script exit
- Resolves permission denied errors when creating temp files during installation

* fix(web): Ensure plugin navigation tabs load on any page by dispatching events

The issue was that when plugins_manager.js loaded and called
loadInstalledPlugins(), it would set window.installedPlugins but the
Alpine.js component wouldn't know to update its tabs unless the plugin
manager tab was clicked.

Changes:
1. loadInstalledPlugins() now always dispatches a 'pluginsUpdated' event
   when it sets window.installedPlugins, not just when plugin IDs change
2. renderInstalledPlugins() also dispatches the event and always updates
   window.installedPlugins for reactivity
3. Cached plugin data also dispatches the event when returned

The Alpine component already listens for the 'pluginsUpdated' event in
its init() method, so tabs will now update immediately when plugins are
loaded, regardless of which tab is active.

Fixes: Plugin navigation tabs only loading after clicking plugin manager tab

* fix(web): Improve input field contrast in plugin configuration forms

Changed input backgrounds from bg-gray-800 to bg-gray-900 (darker) to
ensure high contrast with white text. Added placeholder:text-gray-400
for better placeholder text visibility.

Updated in both server-side template (plugin_config.html) and client-side
form generation (plugins_manager.js):
- Number inputs
- Text inputs
- Array inputs (comma-separated)
- Select dropdowns
- Textareas (JSON objects)
- Fallback inputs without schema

This ensures all form inputs have high contrast white text on dark
background, making them clearly visible and readable.

Fixes: White text on white background in plugin config inputs

* fix(web): Change plugin config input text from white to black

Changed all input fields in plugin configuration forms to use black text
on white background instead of white text on dark background for better
readability and standard form appearance.

Updated:
- Input backgrounds: bg-gray-900 -> bg-white
- Text color: text-white -> text-black
- Placeholder color: text-gray-400 -> text-gray-500

Applied to both server-side template and client-side form generation
for all input types (number, text, select, textarea).

* fix(web): Ensure toggleSection function is available for plugin config collapsible sections

Moved toggleSection function definition to an early script block so it's
available immediately when HTMX loads plugin configuration content. The
function was previously defined later in the page which could cause it
to not be accessible when inline onclick handlers try to call it.

The function toggles the 'hidden' class on collapsible section content
divs and rotates the chevron icon between right (collapsed) and down
(expanded) states.

Fixes: Plugin configuration section headers not collapsing/expanding

* fix(web): Fix collapsible section toggle to properly hide/show content

Updated toggleSection function to explicitly set display style in addition
to toggling the hidden class. This ensures the content is properly hidden
even if CSS specificity or other styles might interfere with just the
hidden class.

The function now:
- Checks both the hidden class and computed display style
- Explicitly sets display: '' when showing and display: 'none' when hiding
- Rotates chevron icon between right (collapsed) and down (expanded)

This ensures collapsible sections in plugin configuration forms properly
hide and show their content when the header is clicked.

Fixes: Collapsible section headers rotate chevron but don't hide content

* fix(web): Fix collapsible section toggle to work on first click

Simplified the toggle logic to rely primarily on the 'hidden' class check
rather than mixing it with computed display styles. When hiding, we now
remove any inline display style to let Tailwind's 'hidden' class properly
control the display property.

This ensures sections respond correctly on the first click, whether they're
starting in a collapsed or expanded state.

Fixes: Sections requiring 2 clicks to collapse

* fix(web): Ensure collapsible sections start collapsed by default

Added explicit display: none style to nested content divs in plugin config
template to ensure they start collapsed. The hidden class should handle this,
but adding the inline style ensures sections are definitely collapsed on
initial page load.

Sections now:
- Start collapsed (hidden) with chevron pointing right
- Expand when clicked (chevron points down)
- Collapse when clicked again (chevron points right)

This ensures a consistent collapsed initial state across all plugin
configuration sections.

* fix(web): Fix collapsible section toggle to properly collapse on second click

Fixed the toggle logic to explicitly set display: block when showing and
display: none when hiding, rather than clearing the display style. This
ensures the section state is properly tracked and the toggle works correctly
on both expand and collapse clicks.

The function now:
- When hidden: removes hidden class, sets display: block, chevron down
- When visible: adds hidden class, sets display: none, chevron right

This fixes the issue where sections would expand but not collapse again.

Fixes: Sections not collapsing on second click

* feat(web): Ensure plugin navigation tabs load automatically on any page

Implemented comprehensive solution to ensure plugin navigation tabs load
automatically without requiring a visit to the plugin manager page:

1. Global event listener for 'pluginsUpdated' - works even if Alpine isn't
   ready yet, updates tabs directly when plugins_manager.js loads plugins

2. Enhanced stub's loadInstalledPluginsDirectly():
   - Sets window.installedPlugins after loading
   - Dispatches 'pluginsUpdated' event for global listener
   - Adds console logging for debugging

3. Event listener in stub's init() method:
   - Listens for 'pluginsUpdated' events
   - Updates component state and tabs when events fire

4. Fallback timer:
   - If plugins_manager.js hasn't loaded after 2 seconds, fetches
     plugins directly via API
   - Ensures tabs appear even if plugins_manager.js fails

5. Improved checkAndUpdateTabs():
   - Better logging
   - Fallback to direct fetch after timeout

6. Enhanced logging throughout plugin loading flow for debugging

This ensures plugin tabs are visible immediately on page load, regardless
of which tab is active or when plugins_manager.js loads.

Fixes: Plugin navigation tabs only loading after visiting plugin manager

* fix(web): Improve plugin tabs update logging and ensure immediate execution

Enhanced logging in updatePluginTabs() and _doUpdatePluginTabs() to help
debug why tabs aren't appearing. Changed debounce behavior to execute
immediately on first call to ensure tabs appear quickly.

Added detailed console logging with [FULL] prefix to track:
- When updatePluginTabs() is called
- When _doUpdatePluginTabs() executes
- DOM element availability
- Tab creation process
- Final tab count

This will help identify if tabs are being created but not visible, or if
the update function isn't being called at all.

Fixes: Plugin tabs loading but not visible in navigation bar

* fix(web): Prevent duplicate plugin tab updates and clearing

Added debouncing and duplicate prevention to stub's updatePluginTabs() to
prevent tabs from being cleared and re-added multiple times. Also checks
if tabs already match before clearing them.

Changes:
1. Debounce stub's updatePluginTabs() with 100ms delay
2. Check if existing tabs match current plugin list before clearing
3. Global event listener only triggers full implementation's updatePluginTabs
4. Stub's event listener only works in stub mode (before enhancement)

This prevents the issue where tabs were being cleared and re-added
multiple times in rapid succession, which could leave tabs empty.

Fixes: Plugin tabs being cleared and not re-added properly

* fix(web): Fix plugin tabs not rendering when plugins are loaded

Fixed _doUpdatePluginTabs() to properly use component's installedPlugins
instead of checking window.installedPlugins first. Also fixed the 'unchanged'
check to not skip when both lists are empty (first load scenario).

Changes:
1. Check component's installedPlugins first (most up-to-date)
2. Only skip update if plugins exist AND match (don't skip empty lists)
3. Retry if no plugins found (in case they're still loading)
4. Ensure window.installedPlugins is set when loading directly
5. Better logging to show which plugin source is being used

This ensures tabs are rendered when plugins are loaded, even on first page load.

Fixes: Plugin tabs not being drawn despite plugins being loaded

* fix(config): Fix array field parsing and validation for plugin config forms

- Added logic to detect and combine indexed array fields (text_color.0, text_color.1, etc.)
- Fixed array fields incorrectly stored as dicts with numeric keys
- Improved handling of comma-separated array values from form submissions
- Ensures array fields meet minItems requirements before validation
- Resolves 400 BAD REQUEST errors when saving plugin config with RGB color arrays

* fix(config): Improve array field handling and secrets error handling

- Use schema defaults when array fields don't meet minItems requirement
- Add debug logging for array field parsing
- Improve error handling for secrets file writes
- Fix arrays stored as dicts with numeric keys conversion
- Better handling of incomplete array values from form submissions

* fix(config): Convert array elements to correct types (numbers not strings)

- Fix array element type conversion when converting dicts to arrays
- Ensure RGB color arrays have integer elements, not strings
- Apply type conversion for both nested and top-level array fields
- Fixes validation errors: 'Expected type number, got str'

* fix(config): Fix array fields showing 'none' when value is null

- Handle None/null values in array field templates properly
- Use schema defaults when array values are None/null
- Fix applies to both Jinja2 template and JavaScript form generation
- Resolves issue where stock ticker plugin shows 'none' instead of default values

* fix(config): Add novalidate to plugin config form to prevent HTML5 validation blocking saves

- Prevents browser HTML5 validation from blocking form submission
- Allows custom validation logic to handle form data properly
- Fixes issue where save button appears unclickable due to invalid form controls
- Resolves problems with plugins like clock-simple that have nested/array fields

* feat(config): Add helpful form validation with detailed error messages

- Keep HTML5 validation enabled (removed novalidate) to prevent broken configs
- Add validatePluginConfigForm function that shows which fields fail and why
- Automatically expands collapsed sections containing invalid fields
- Focuses first invalid field and scrolls to it
- Shows user-friendly error messages with field names and specific issues
- Prevents form submission until all fields are valid

* fix(schema): Remove core properties from required array during validation

- Core properties (enabled, display_duration, live_priority) are system-managed
- SchemaManager now removes them from required array after injection
- Added default values for core properties (enabled=True, display_duration=15, live_priority=False)
- Updated generate_default_config() to ensure live_priority has default
- Resolves 186 validation issues, reducing to 3 non-blocking warnings (98.4% reduction)
- All 19 of 20 plugins now pass validation without errors

Documentation:
- Created docs/PLUGIN_CONFIG_CORE_PROPERTIES.md explaining core property handling
- Updated existing docs to reflect core property behavior
- Removed temporary audit files and scripts

* fix(ui): Improve button text contrast on white backgrounds

- Changed Screenshot button text from text-gray-700 to text-gray-900
- Added global CSS rule to ensure all buttons with white backgrounds use dark text (text-gray-900) for better readability
- Fixes contrast issues where light text on light backgrounds was illegible

* fix(ui): Add explicit text color to form-control inputs

- Added color: #111827 to .form-control class to ensure dark text on white backgrounds
- Fixes issue where input fields had white text on white background after button contrast fix
- Ensures all form inputs are readable with proper contrast

* docs: Update impact explanation and plugin config documentation

* docs: Improve documentation and fix template inconsistencies

- Add migration guide for script path reorganization (scripts moved to scripts/install/ and scripts/fix_perms/)
- Add breaking changes section to README with migration guidance
- Fix config template: set plugins_directory to 'plugins' to match actual plugin locations
- Fix test template: replace Jinja2 placeholders with plain text to match other templates
- Fix markdown linting: add language identifiers to code blocks (python, text, javascript)
- Update permission guide: document setgid bit (0o2775) for directory modes
- Fix example JSON: pin dependency versions and fix compatible_versions range
- Improve readability: reduce repetition in IMPACT_EXPLANATION.md

* feat(web): Make v3 interface production-ready for local deployment

- Phase 2: Real Service Integration
  - Replace sample data with real psutil system monitoring (CPU, memory, disk, temp, uptime)
  - Integrate display controller to read from /tmp/led_matrix_preview.png snapshot
  - Scan assets/fonts directory and extract font metadata with freetype

- Phase 1: Security & Input Validation
  - Add input validation module with URL, file upload, and config sanitization
  - Add optional CSRF protection (gracefully degrades if flask-wtf missing)
  - Add rate limiting (lenient for local use, prevents accidental abuse)
  - Add file upload validation to font upload endpoint

- Phase 3: Error Handling
  - Add global error handlers for 404, 500, and unhandled exceptions
  - All endpoints have comprehensive try/except blocks

- Phase 4: Monitoring & Observability
  - Add structured logging with JSON format support
  - Add request logging middleware (tracks method, path, status, duration, IP)
  - Add /api/v3/health endpoint with service status checks

- Phase 5: Performance & Caching
  - Add in-memory caching system (separate module to avoid circular imports)
  - Cache font catalog (5 minute TTL)
  - Cache system status (10 second TTL)
  - Invalidate cache on config changes

- All changes are non-blocking with graceful error handling
- Optional dependencies (flask-wtf, flask-limiter) degrade gracefully
- All imports protected with try/except blocks
- Verified compilation and import tests pass

* docs: Fix caching pattern logic flaw and merge conflict resolution plan

- Fix Basic Caching Pattern: Replace broken stale cache fallback with correct pattern
  - Re-fetch cache with large max_age (31536000) in except block instead of checking already-falsy cached variable
  - Fixes both instances in ADVANCED_PLUGIN_DEVELOPMENT.md
  - Matches correct pattern from manager.py.template

- Fix MERGE_CONFLICT_RESOLUTION_PLAN.md merge direction
  - Correct Step 1 to checkout main and merge plugins into it (not vice versa)
  - Update commit message to reflect 'Merge plugins into main' direction
  - Fixes workflow to match documented plugins → main merge

---------

Co-authored-by: Chuck <chuck@example.com>
2025-12-27 14:15:49 -05:00

2848 lines
85 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# LEDMatrix Plugin Architecture Specification
## Executive Summary
This document outlines the transformation of the LEDMatrix project into a modular, plugin-based architecture that enables user-created displays. The goal is to create a flexible, extensible system similar to Home Assistant Community Store (HACS) where users can discover, install, and manage custom display managers from GitHub repositories.
### Key Decisions
1. **Gradual Migration**: Existing managers remain in core while new plugin infrastructure is built
2. **Migration Required**: Breaking changes with migration tools provided
3. **GitHub-Based Store**: Simple discovery system, packages served from GitHub repos
4. **Plugin Location**: `./plugins/` directory in project root
---
## Table of Contents
1. [Current Architecture Analysis](#current-architecture-analysis)
2. [Plugin System Design](#plugin-system-design)
3. [Plugin Store & Discovery](#plugin-store--discovery)
4. [Web UI Transformation](#web-ui-transformation)
5. [Migration Strategy](#migration-strategy)
6. [Plugin Developer Guidelines](#plugin-developer-guidelines)
7. [Technical Implementation Details](#technical-implementation-details)
8. [Best Practices & Standards](#best-practices--standards)
9. [Security Considerations](#security-considerations)
10. [Implementation Roadmap](#implementation-roadmap)
---
## 1. Current Architecture Analysis
### Current System Overview
**Core Components:**
- `display_controller.py`: Main orchestrator, hardcoded manager instantiation
- `display_manager.py`: Handles LED matrix rendering
- `config_manager.py`: Loads config from JSON files
- `cache_manager.py`: Caching layer for API calls
- `web_interface_v2.py`: Web UI with hardcoded manager references
**Manager Pattern:**
- All managers follow similar initialization: `__init__(config, display_manager, cache_manager)`
- Common methods: `update()` for data fetching, `display()` for rendering
- Located in `src/` with various naming conventions
- Hardcoded imports in display_controller and web_interface
**Configuration:**
- Monolithic `config.json` with sections for each manager
- Template-based updates via `config.template.json`
- Secrets in separate `config_secrets.json`
### Pain Points
1. **Tight Coupling**: Display controller has hardcoded imports for ~40+ managers
2. **Monolithic Config**: 650+ line config file, hard to navigate
3. **No Extensibility**: Users can't add custom displays without modifying core
4. **Update Conflicts**: Config template merges can fail with custom setups
5. **Scaling Issues**: Adding new displays requires core code changes
---
## 2. Plugin System Design
### Plugin Architecture
```
plugins/
├── clock-simple/
│ ├── manifest.json # Plugin metadata
│ ├── manager.py # Main plugin class
│ ├── requirements.txt # Python dependencies
│ ├── assets/ # Plugin-specific assets
│ │ └── fonts/
│ ├── config_schema.json # JSON schema for validation
│ └── README.md # Documentation
├── nhl-scoreboard/
│ ├── manifest.json
│ ├── manager.py
│ ├── requirements.txt
│ ├── assets/
│ │ └── logos/
│ └── README.md
└── weather-animated/
├── manifest.json
├── manager.py
├── requirements.txt
├── assets/
│ └── animations/
└── README.md
```
### Plugin Manifest Structure
```json
{
"id": "clock-simple",
"name": "Simple Clock",
"version": "1.0.0",
"author": "ChuckBuilds",
"description": "A simple clock display with date",
"homepage": "https://github.com/ChuckBuilds/ledmatrix-clock-simple",
"entry_point": "manager.py",
"class_name": "SimpleClock",
"category": "time",
"tags": ["clock", "time", "date"],
"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": {
"fonts": ["assets/fonts/clock.bdf"],
"images": []
},
"update_interval": 1,
"default_duration": 15,
"display_modes": ["clock"],
"api_requirements": []
}
```
### Base Plugin Interface
```python
# src/plugin_system/base_plugin.py
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
import logging
class BasePlugin(ABC):
"""
Base class that all plugins must inherit from.
Provides standard interface and helper methods.
"""
def __init__(self, plugin_id: str, config: Dict[str, Any],
display_manager, cache_manager, plugin_manager):
"""
Standard initialization for all plugins.
Args:
plugin_id: Unique identifier for this plugin instance
config: Plugin-specific configuration
display_manager: Shared display manager instance
cache_manager: Shared cache manager instance
plugin_manager: Reference to plugin manager for inter-plugin communication
"""
self.plugin_id = plugin_id
self.config = config
self.display_manager = display_manager
self.cache_manager = cache_manager
self.plugin_manager = plugin_manager
self.logger = logging.getLogger(f"plugin.{plugin_id}")
self.enabled = config.get('enabled', True)
@abstractmethod
def update(self) -> None:
"""
Fetch/update data for this plugin.
Called based on update_interval in manifest.
"""
pass
@abstractmethod
def display(self, force_clear: bool = False) -> None:
"""
Render this plugin's display.
Called during rotation or on-demand.
Args:
force_clear: If True, clear display before rendering
"""
pass
def get_display_duration(self) -> float:
"""
Get the display duration for this plugin instance.
Can be overridden based on dynamic content.
Returns:
Duration in seconds
"""
return self.config.get('display_duration', 15.0)
def validate_config(self) -> bool:
"""
Validate plugin configuration against schema.
Called during plugin loading.
Returns:
True if config is valid
"""
# Implementation uses config_schema.json
return True
def cleanup(self) -> None:
"""
Cleanup resources when plugin is unloaded.
Override if needed.
"""
pass
def get_info(self) -> Dict[str, Any]:
"""
Return plugin info for display in web UI.
Returns:
Dict with name, version, status, etc.
"""
return {
'id': self.plugin_id,
'enabled': self.enabled,
'config': self.config
}
```
### Plugin Manager
```python
# src/plugin_system/plugin_manager.py
import os
import json
import importlib
import sys
from pathlib import Path
from typing import Dict, List, Optional, Any
import logging
class PluginManager:
"""
Manages plugin discovery, loading, and lifecycle.
"""
def __init__(self, plugins_dir: str = "plugins",
config_manager=None, display_manager=None, cache_manager=None):
self.plugins_dir = Path(plugins_dir)
self.config_manager = config_manager
self.display_manager = display_manager
self.cache_manager = cache_manager
self.logger = logging.getLogger(__name__)
# Active plugins
self.plugins: Dict[str, Any] = {}
self.plugin_manifests: Dict[str, Dict] = {}
# Ensure plugins directory exists
self.plugins_dir.mkdir(exist_ok=True)
def discover_plugins(self) -> List[str]:
"""
Scan plugins directory for installed plugins.
Returns:
List of plugin IDs
"""
discovered = []
if not self.plugins_dir.exists():
self.logger.warning(f"Plugins directory not found: {self.plugins_dir}")
return discovered
for item in self.plugins_dir.iterdir():
if not item.is_dir():
continue
manifest_path = item / "manifest.json"
if manifest_path.exists():
try:
with open(manifest_path, 'r') as f:
manifest = json.load(f)
plugin_id = manifest.get('id')
if plugin_id:
discovered.append(plugin_id)
self.plugin_manifests[plugin_id] = manifest
self.logger.info(f"Discovered plugin: {plugin_id}")
except Exception as e:
self.logger.error(f"Error reading manifest in {item}: {e}")
return discovered
def load_plugin(self, plugin_id: str) -> bool:
"""
Load a plugin by ID.
Args:
plugin_id: Plugin identifier
Returns:
True if loaded successfully
"""
if plugin_id in self.plugins:
self.logger.warning(f"Plugin {plugin_id} already loaded")
return True
manifest = self.plugin_manifests.get(plugin_id)
if not manifest:
self.logger.error(f"No manifest found for plugin: {plugin_id}")
return False
try:
# Add plugin directory to Python path
plugin_dir = self.plugins_dir / plugin_id
sys.path.insert(0, str(plugin_dir))
# Import the plugin module
entry_point = manifest.get('entry_point', 'manager.py')
module_name = entry_point.replace('.py', '')
module = importlib.import_module(module_name)
# Get the plugin class
class_name = manifest.get('class_name')
if not class_name:
self.logger.error(f"No class_name in manifest for {plugin_id}")
return False
plugin_class = getattr(module, class_name)
# Get plugin config
plugin_config = self.config_manager.load_config().get(plugin_id, {})
# Instantiate the plugin
plugin_instance = plugin_class(
plugin_id=plugin_id,
config=plugin_config,
display_manager=self.display_manager,
cache_manager=self.cache_manager,
plugin_manager=self
)
# Validate configuration
if not plugin_instance.validate_config():
self.logger.error(f"Config validation failed for {plugin_id}")
return False
self.plugins[plugin_id] = plugin_instance
self.logger.info(f"Loaded plugin: {plugin_id} v{manifest.get('version')}")
return True
except Exception as e:
self.logger.error(f"Error loading plugin {plugin_id}: {e}", exc_info=True)
return False
finally:
# Clean up Python path
if str(plugin_dir) in sys.path:
sys.path.remove(str(plugin_dir))
def unload_plugin(self, plugin_id: str) -> bool:
"""
Unload a plugin by ID.
Args:
plugin_id: Plugin identifier
Returns:
True if unloaded successfully
"""
if plugin_id not in self.plugins:
self.logger.warning(f"Plugin {plugin_id} not loaded")
return False
try:
plugin = self.plugins[plugin_id]
plugin.cleanup()
del self.plugins[plugin_id]
self.logger.info(f"Unloaded plugin: {plugin_id}")
return True
except Exception as e:
self.logger.error(f"Error unloading plugin {plugin_id}: {e}")
return False
def reload_plugin(self, plugin_id: str) -> bool:
"""
Reload a plugin (unload and load).
Args:
plugin_id: Plugin identifier
Returns:
True if reloaded successfully
"""
if plugin_id in self.plugins:
if not self.unload_plugin(plugin_id):
return False
return self.load_plugin(plugin_id)
def get_plugin(self, plugin_id: str) -> Optional[Any]:
"""
Get a loaded plugin instance.
Args:
plugin_id: Plugin identifier
Returns:
Plugin instance or None
"""
return self.plugins.get(plugin_id)
def get_all_plugins(self) -> Dict[str, Any]:
"""
Get all loaded plugins.
Returns:
Dict of plugin_id: plugin_instance
"""
return self.plugins
def get_enabled_plugins(self) -> List[str]:
"""
Get list of enabled plugin IDs.
Returns:
List of plugin IDs
"""
return [pid for pid, plugin in self.plugins.items() if plugin.enabled]
```
### Display Controller Integration
```python
# Modified src/display_controller.py
class DisplayController:
def __init__(self):
# ... existing initialization ...
# Initialize plugin system
self.plugin_manager = PluginManager(
plugins_dir="plugins",
config_manager=self.config_manager,
display_manager=self.display_manager,
cache_manager=self.cache_manager
)
# Discover and load plugins
discovered = self.plugin_manager.discover_plugins()
logger.info(f"Discovered {len(discovered)} plugins")
for plugin_id in discovered:
if self.config.get(plugin_id, {}).get('enabled', False):
self.plugin_manager.load_plugin(plugin_id)
# Build available modes from plugins + legacy managers
self.available_modes = []
# Add legacy managers (existing code)
if self.clock: self.available_modes.append('clock')
# ... etc ...
# Add plugin modes
for plugin_id, plugin in self.plugin_manager.get_all_plugins().items():
if plugin.enabled:
manifest = self.plugin_manager.plugin_manifests.get(plugin_id, {})
display_modes = manifest.get('display_modes', [plugin_id])
self.available_modes.extend(display_modes)
def display_mode(self, mode: str, force_clear: bool = False):
"""
Render a specific mode (legacy or plugin).
"""
# Check if it's a plugin mode
for plugin_id, plugin in self.plugin_manager.get_all_plugins().items():
manifest = self.plugin_manager.plugin_manifests.get(plugin_id, {})
if mode in manifest.get('display_modes', []):
plugin.display(force_clear=force_clear)
return
# Fall back to legacy manager handling
if mode == 'clock' and self.clock:
self.clock.display_time(force_clear=force_clear)
# ... etc ...
```
### Base Classes and Code Reuse
#### Philosophy: Core Provides Stable Plugin API
The core LEDMatrix provides stable base classes and utilities for common plugin types. This approach balances code reuse with plugin independence.
#### Plugin API Base Classes
```
src/
├── plugin_system/
│ ├── base_plugin.py # Core plugin interface (required)
│ └── base_classes/ # Optional base classes for common use cases
│ ├── __init__.py
│ ├── sports_plugin.py # Generic sports displays
│ ├── hockey_plugin.py # Hockey-specific features
│ ├── basketball_plugin.py # Basketball-specific features
│ ├── baseball_plugin.py # Baseball-specific features
│ ├── football_plugin.py # Football-specific features
│ └── display_helpers.py # Common rendering utilities
```
#### Sports Plugin Base Class
```python
# src/plugin_system/base_classes/sports_plugin.py
from src.plugin_system.base_plugin import BasePlugin
from typing import List, Dict, Any, Optional
import requests
class SportsPlugin(BasePlugin):
"""
Base class for sports-related plugins.
API Version: 1.0.0
Stability: Stable - maintains backward compatibility
Provides common functionality:
- Favorite team filtering
- ESPN API integration
- Standard game data structures
- Common rendering methods
"""
API_VERSION = "1.0.0"
def __init__(self, plugin_id, config, display_manager, cache_manager, plugin_manager):
super().__init__(plugin_id, config, display_manager, cache_manager, plugin_manager)
# Standard sports plugin configuration
self.favorite_teams = config.get('favorite_teams', [])
self.show_favorite_only = config.get('show_favorite_teams_only', True)
self.show_odds = config.get('show_odds', True)
self.show_records = config.get('show_records', True)
self.logo_dir = config.get('logo_dir', 'assets/sports/logos')
def filter_by_favorites(self, games: List[Dict]) -> List[Dict]:
"""
Filter games to show only favorite teams.
Args:
games: List of game dictionaries
Returns:
Filtered list of games
"""
if not self.show_favorite_only or not self.favorite_teams:
return games
return [g for g in games if self._is_favorite_game(g)]
def _is_favorite_game(self, game: Dict) -> bool:
"""Check if game involves a favorite team."""
home_team = game.get('home_team', '')
away_team = game.get('away_team', '')
return home_team in self.favorite_teams or away_team in self.favorite_teams
def fetch_espn_data(self, sport: str, endpoint: str = "scoreboard",
params: Dict = None) -> Optional[Dict]:
"""
Fetch data from ESPN API.
Args:
sport: Sport identifier (e.g., 'hockey/nhl', 'basketball/nba')
endpoint: API endpoint (default: 'scoreboard')
params: Query parameters
Returns:
API response data or None on error
"""
url = f"https://site.api.espn.com/apis/site/v2/sports/{sport}/{endpoint}"
cache_key = f"espn_{sport}_{endpoint}"
# Try cache first
cached = self.cache_manager.get(cache_key, max_age=60)
if cached:
return cached
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
# Cache the response
self.cache_manager.set(cache_key, data)
return data
except Exception as e:
self.logger.error(f"Error fetching ESPN data: {e}")
return None
def render_team_logo(self, team_abbr: str, x: int, y: int, size: int = 16):
"""
Render a team logo at specified position.
Args:
team_abbr: Team abbreviation
x, y: Position on display
size: Logo size in pixels
"""
from pathlib import Path
from PIL import Image
# Try plugin assets first
logo_path = Path(self.plugin_id) / "assets" / "logos" / f"{team_abbr}.png"
# Fall back to core assets
if not logo_path.exists():
logo_path = Path(self.logo_dir) / f"{team_abbr}.png"
if logo_path.exists():
try:
logo = Image.open(logo_path)
logo = logo.resize((size, size), Image.LANCZOS)
self.display_manager.image.paste(logo, (x, y))
except Exception as e:
self.logger.error(f"Error rendering logo for {team_abbr}: {e}")
def render_score(self, away_team: str, away_score: int,
home_team: str, home_score: int,
x: int, y: int):
"""
Render a game score in standard format.
Args:
away_team, away_score: Away team info
home_team, home_score: Home team info
x, y: Position on display
"""
# Render away team
self.render_team_logo(away_team, x, y)
self.display_manager.draw_text(
f"{away_score}",
x=x + 20, y=y + 4,
color=(255, 255, 255)
)
# Render home team
self.render_team_logo(home_team, x + 40, y)
self.display_manager.draw_text(
f"{home_score}",
x=x + 60, y=y + 4,
color=(255, 255, 255)
)
```
#### Hockey Plugin Base Class
```python
# src/plugin_system/base_classes/hockey_plugin.py
from src.plugin_system.base_classes.sports_plugin import SportsPlugin
from typing import Dict, List, Optional
class HockeyPlugin(SportsPlugin):
"""
Base class for hockey plugins (NHL, NCAA Hockey, etc).
API Version: 1.0.0
Provides hockey-specific features:
- Period handling
- Power play indicators
- Shots on goal display
"""
def __init__(self, plugin_id, config, display_manager, cache_manager, plugin_manager):
super().__init__(plugin_id, config, display_manager, cache_manager, plugin_manager)
# Hockey-specific config
self.show_shots = config.get('show_shots_on_goal', True)
self.show_power_play = config.get('show_power_play', True)
def fetch_hockey_games(self, league: str = "nhl") -> List[Dict]:
"""
Fetch hockey games from ESPN.
Args:
league: League identifier (nhl, college-hockey)
Returns:
List of standardized game dictionaries
"""
sport = f"hockey/{league}"
data = self.fetch_espn_data(sport)
if not data:
return []
return self._parse_hockey_games(data.get('events', []))
def _parse_hockey_games(self, events: List[Dict]) -> List[Dict]:
"""
Parse ESPN hockey events into standardized format.
Returns:
List of dicts with keys: id, home_team, away_team, home_score,
away_score, period, clock, status, power_play, shots
"""
games = []
for event in events:
try:
competition = event['competitions'][0]
game = {
'id': event['id'],
'home_team': competition['competitors'][0]['team']['abbreviation'],
'away_team': competition['competitors'][1]['team']['abbreviation'],
'home_score': int(competition['competitors'][0]['score']),
'away_score': int(competition['competitors'][1]['score']),
'status': competition['status']['type']['state'],
'period': competition.get('period', 0),
'clock': competition.get('displayClock', ''),
'power_play': self._extract_power_play(competition),
'shots': self._extract_shots(competition)
}
games.append(game)
except (KeyError, IndexError, ValueError) as e:
self.logger.error(f"Error parsing hockey game: {e}")
continue
return games
def render_hockey_game(self, game: Dict, x: int = 0, y: int = 0):
"""
Render a hockey game in standard format.
Args:
game: Game dictionary (from _parse_hockey_games)
x, y: Position on display
"""
# Render score
self.render_score(
game['away_team'], game['away_score'],
game['home_team'], game['home_score'],
x, y
)
# Render period and clock
if game['status'] == 'in':
period_text = f"P{game['period']} {game['clock']}"
self.display_manager.draw_text(
period_text,
x=x, y=y + 20,
color=(255, 255, 0)
)
# Render power play indicator
if self.show_power_play and game.get('power_play'):
self.display_manager.draw_text(
"PP",
x=x + 80, y=y + 20,
color=(255, 0, 0)
)
# Render shots
if self.show_shots and game.get('shots'):
shots_text = f"SOG: {game['shots']['away']}-{game['shots']['home']}"
self.display_manager.draw_text(
shots_text,
x=x, y=y + 28,
color=(200, 200, 200),
small_font=True
)
def _extract_power_play(self, competition: Dict) -> Optional[str]:
"""Extract power play information from competition data."""
# Implementation details...
return None
def _extract_shots(self, competition: Dict) -> Optional[Dict]:
"""Extract shots on goal from competition data."""
# Implementation details...
return None
```
#### Using Base Classes in Plugins
**Example: NHL Scores Plugin**
```python
# plugins/nhl-scores/manager.py
from src.plugin_system.base_classes.hockey_plugin import HockeyPlugin
class NHLScoresPlugin(HockeyPlugin):
"""
NHL Scores plugin using stable hockey base class.
Inherits all hockey functionality, just needs to implement
update() and display() for NHL-specific behavior.
"""
def update(self):
"""Fetch NHL games using inherited method."""
self.games = self.fetch_hockey_games(league="nhl")
# Filter to favorites
if self.show_favorite_only:
self.games = self.filter_by_favorites(self.games)
self.logger.info(f"Fetched {len(self.games)} NHL games")
def display(self, force_clear=False):
"""Display NHL games using inherited rendering."""
if force_clear:
self.display_manager.clear()
if not self.games:
self._show_no_games()
return
# Show first game using inherited method
self.render_hockey_game(self.games[0], x=0, y=5)
self.display_manager.update_display()
def _show_no_games(self):
"""Show no games message."""
self.display_manager.draw_text(
"No NHL games",
x=5, y=15,
color=(255, 255, 255)
)
```
**Example: Custom Hockey Plugin (NCAA Hockey)**
```python
# plugins/ncaa-hockey/manager.py
from src.plugin_system.base_classes.hockey_plugin import HockeyPlugin
class NCAAHockeyPlugin(HockeyPlugin):
"""
NCAA Hockey plugin - different league, same base class.
"""
def update(self):
"""Fetch NCAA hockey games."""
self.games = self.fetch_hockey_games(league="college-hockey")
self.games = self.filter_by_favorites(self.games)
def display(self, force_clear=False):
"""Display using inherited hockey rendering."""
if force_clear:
self.display_manager.clear()
if self.games:
# Use inherited rendering method
self.render_hockey_game(self.games[0], x=0, y=5)
self.display_manager.update_display()
```
#### API Versioning and Compatibility
**Manifest declares required API version:**
```json
{
"id": "nhl-scores",
"plugin_api_version": "1.0.0",
"compatible_versions": [">=2.0.0"]
}
```
**Plugin Manager checks compatibility:**
```python
# In plugin_manager.py
def load_plugin(self, plugin_id: str) -> bool:
manifest = self.plugin_manifests.get(plugin_id)
# Check API compatibility
required_api = manifest.get('plugin_api_version', '1.0.0')
from src.plugin_system.base_classes.sports_plugin import SportsPlugin
current_api = SportsPlugin.API_VERSION
if not self._is_api_compatible(required_api, current_api):
self.logger.error(
f"Plugin {plugin_id} requires API {required_api}, "
f"but {current_api} is available. Please update plugin or core."
)
return False
# Continue loading...
return True
def _is_api_compatible(self, required: str, current: str) -> bool:
"""
Check if required API version is compatible with current.
Uses semantic versioning: MAJOR.MINOR.PATCH
- Same major version = compatible
- Different major version = incompatible (breaking changes)
"""
req_major = int(required.split('.')[0])
cur_major = int(current.split('.')[0])
return req_major == cur_major
```
#### Handling API Changes
**Non-Breaking Changes (Minor/Patch versions):**
```python
# v1.0.0 -> v1.1.0 (new optional parameter)
class HockeyPlugin:
def render_hockey_game(self, game, x=0, y=0, show_penalties=False):
# Added optional parameter, old code still works
pass
```
**Breaking Changes (Major version):**
```python
# v1.x.x
class HockeyPlugin:
def render_hockey_game(self, game, x=0, y=0):
pass
# v2.0.0 (breaking change)
class HockeyPlugin:
API_VERSION = "2.0.0"
def render_hockey_game(self, game, position=(0, 0), style="default"):
# Changed signature - plugins need updates
pass
```
Plugins requiring v1.x would fail to load with v2.0.0 core, prompting user to update.
#### Benefits of This Approach
1. **No Code Duplication**: Plugins import from core
2. **Consistent Behavior**: All hockey plugins render the same way
3. **Easy Updates**: Bug fixes in base classes benefit all plugins
4. **Smaller Plugins**: No need to bundle common code
5. **Clear API Contract**: Versioned, stable interface
6. **Flexibility**: Plugins can override any method
#### When NOT to Use Base Classes
Plugins should implement BasePlugin directly when:
- Creating completely custom displays (no common patterns)
- Needing full control over every aspect
- Prototyping new display types
- External data sources (not ESPN)
Example:
```python
# plugins/custom-animation/manager.py
from src.plugin_system.base_plugin import BasePlugin
class CustomAnimationPlugin(BasePlugin):
"""Fully custom plugin - doesn't need sports base classes."""
def update(self):
# Custom data fetching
pass
def display(self, force_clear=False):
# Custom rendering
pass
```
#### Migration Strategy for Existing Base Classes
**Current base classes** (`src/base_classes/`):
- `sports.py`
- `hockey.py`
- `basketball.py`
- etc.
**Phase 1**: Create new plugin-specific base classes
- Keep old ones for backward compatibility
- New base classes in `src/plugin_system/base_classes/`
**Phase 2**: Migrate existing managers
- Legacy managers still use old base classes
- New plugins use new base classes
**Phase 3**: Deprecate old base classes (v3.0)
- Remove old `src/base_classes/`
- All code uses plugin system base classes
---
## 3. Plugin Store & Discovery
### Store Architecture (HACS-inspired)
The plugin store will be a simple GitHub-based discovery system where:
1. **Central Registry**: A GitHub repo (`ChuckBuilds/ledmatrix-plugin-registry`) contains a JSON file listing approved plugins
2. **Plugin Repos**: Individual GitHub repos contain plugin code
3. **Installation**: Clone/download plugin repos directly to `./plugins/` directory
4. **Updates**: Git pull or re-download from GitHub
### Registry Structure
```json
// ledmatrix-plugin-registry/plugins.json
{
"version": "1.0.0",
"plugins": [
{
"id": "clock-simple",
"name": "Simple Clock",
"description": "A simple clock display with date",
"author": "ChuckBuilds",
"category": "time",
"tags": ["clock", "time", "date"],
"repo": "https://github.com/ChuckBuilds/ledmatrix-clock-simple",
"branch": "main",
"versions": [
{
"version": "1.0.0",
"ledmatrix_min_version": "2.0.0",
"released": "2025-01-15",
"download_url": "https://github.com/ChuckBuilds/ledmatrix-clock-simple/archive/refs/tags/v1.0.0.zip"
}
],
"stars": 45,
"downloads": 1234,
"last_updated": "2025-01-15",
"verified": true
},
{
"id": "weather-animated",
"name": "Animated Weather",
"description": "Weather display with animated icons",
"author": "SomeUser",
"category": "weather",
"tags": ["weather", "animated", "forecast"],
"repo": "https://github.com/SomeUser/ledmatrix-weather-animated",
"branch": "main",
"versions": [
{
"version": "2.1.0",
"ledmatrix_min_version": "2.0.0",
"released": "2025-01-10",
"download_url": "https://github.com/SomeUser/ledmatrix-weather-animated/archive/refs/tags/v2.1.0.zip"
}
],
"stars": 89,
"downloads": 2341,
"last_updated": "2025-01-10",
"verified": true
}
]
}
```
### Plugin Store Manager
```python
# src/plugin_system/store_manager.py
import requests
import subprocess
import shutil
from pathlib import Path
from typing import List, Dict, Optional
import logging
class PluginStoreManager:
"""
Manages plugin discovery, installation, and updates from GitHub.
"""
REGISTRY_URL = "https://raw.githubusercontent.com/ChuckBuilds/ledmatrix-plugin-registry/main/plugins.json"
def __init__(self, plugins_dir: str = "plugins"):
self.plugins_dir = Path(plugins_dir)
self.logger = logging.getLogger(__name__)
self.registry_cache = None
def fetch_registry(self, force_refresh: bool = False) -> Dict:
"""
Fetch the plugin registry from GitHub.
Args:
force_refresh: Force refresh even if cached
Returns:
Registry data
"""
if self.registry_cache and not force_refresh:
return self.registry_cache
try:
response = requests.get(self.REGISTRY_URL, timeout=10)
response.raise_for_status()
self.registry_cache = response.json()
self.logger.info(f"Fetched registry with {len(self.registry_cache['plugins'])} plugins")
return self.registry_cache
except Exception as e:
self.logger.error(f"Error fetching registry: {e}")
return {"plugins": []}
def search_plugins(self, query: str = "", category: str = "", tags: List[str] = []) -> List[Dict]:
"""
Search for plugins in the registry.
Args:
query: Search query string
category: Filter by category
tags: Filter by tags
Returns:
List of matching plugins
"""
registry = self.fetch_registry()
plugins = registry.get('plugins', [])
results = []
for plugin in plugins:
# Category filter
if category and plugin.get('category') != category:
continue
# Tags filter
if tags and not any(tag in plugin.get('tags', []) for tag in tags):
continue
# Query search
if query:
query_lower = query.lower()
if not any([
query_lower in plugin.get('name', '').lower(),
query_lower in plugin.get('description', '').lower(),
query_lower in plugin.get('id', '').lower()
]):
continue
results.append(plugin)
return results
def install_plugin(self, plugin_id: str) -> bool:
"""
Install a plugin from GitHub.
Always clones or downloads the latest commit from the repository's default branch.
Args:
plugin_id: Plugin identifier
Returns:
True if installed successfully
"""
registry = self.fetch_registry()
plugin_info = next((p for p in registry['plugins'] if p['id'] == plugin_id), None)
if not plugin_info:
self.logger.error(f"Plugin not found in registry: {plugin_id}")
return False
try:
# Get version info
if version == "latest":
version_info = plugin_info['versions'][0] # First is latest
else:
version_info = next((v for v in plugin_info['versions'] if v['version'] == version), None)
if not version_info:
self.logger.error(f"Version not found: {version}")
return False
# Get repo URL
repo_url = plugin_info['repo']
# Clone or download
plugin_path = self.plugins_dir / plugin_id
if plugin_path.exists():
self.logger.warning(f"Plugin directory already exists: {plugin_id}")
shutil.rmtree(plugin_path)
# Try git clone first
try:
subprocess.run(
['git', 'clone', '--depth', '1', '--branch', version_info['version'],
repo_url, str(plugin_path)],
check=True,
capture_output=True
)
self.logger.info(f"Cloned plugin {plugin_id} v{version_info['version']}")
except (subprocess.CalledProcessError, FileNotFoundError):
# Fall back to download
self.logger.info("Git not available, downloading zip...")
download_url = version_info['download_url']
response = requests.get(download_url, timeout=30)
response.raise_for_status()
# Extract zip (implementation needed)
# ...
# Install Python dependencies
requirements_file = plugin_path / "requirements.txt"
if requirements_file.exists():
subprocess.run(
['pip3', 'install', '--break-system-packages', '-r', str(requirements_file)],
check=True
)
self.logger.info(f"Installed dependencies for {plugin_id}")
self.logger.info(f"Successfully installed plugin: {plugin_id}")
return True
except Exception as e:
self.logger.error(f"Error installing plugin {plugin_id}: {e}")
return False
def uninstall_plugin(self, plugin_id: str) -> bool:
"""
Uninstall a plugin.
Args:
plugin_id: Plugin identifier
Returns:
True if uninstalled successfully
"""
plugin_path = self.plugins_dir / plugin_id
if not plugin_path.exists():
self.logger.warning(f"Plugin not found: {plugin_id}")
return False
try:
shutil.rmtree(plugin_path)
self.logger.info(f"Uninstalled plugin: {plugin_id}")
return True
except Exception as e:
self.logger.error(f"Error uninstalling plugin {plugin_id}: {e}")
return False
def update_plugin(self, plugin_id: str) -> bool:
"""
Update a plugin to the latest version.
Args:
plugin_id: Plugin identifier
Returns:
True if updated successfully
"""
plugin_path = self.plugins_dir / plugin_id
if not plugin_path.exists():
self.logger.error(f"Plugin not installed: {plugin_id}")
return False
try:
# Try git pull first
git_dir = plugin_path / ".git"
if git_dir.exists():
result = subprocess.run(
['git', '-C', str(plugin_path), 'pull'],
capture_output=True,
text=True
)
if result.returncode == 0:
self.logger.info(f"Updated plugin {plugin_id} via git pull")
return True
# Fall back to re-download
self.logger.info(f"Re-downloading plugin {plugin_id}")
return self.install_plugin(plugin_id)
except Exception as e:
self.logger.error(f"Error updating plugin {plugin_id}: {e}")
return False
def install_from_url(self, repo_url: str, plugin_id: str = None) -> bool:
"""
Install a plugin directly from a GitHub URL (for custom/unlisted plugins).
Args:
repo_url: GitHub repository URL
plugin_id: Optional custom plugin ID (extracted from manifest if not provided)
Returns:
True if installed successfully
"""
try:
# Clone to temporary location
temp_dir = self.plugins_dir / ".temp_install"
if temp_dir.exists():
shutil.rmtree(temp_dir)
subprocess.run(
['git', 'clone', '--depth', '1', repo_url, str(temp_dir)],
check=True,
capture_output=True
)
# Read manifest to get plugin ID
manifest_path = temp_dir / "manifest.json"
if not manifest_path.exists():
self.logger.error("No manifest.json found in repository")
shutil.rmtree(temp_dir)
return False
with open(manifest_path, 'r') as f:
manifest = json.load(f)
plugin_id = plugin_id or manifest.get('id')
if not plugin_id:
self.logger.error("No plugin ID found in manifest")
shutil.rmtree(temp_dir)
return False
# Move to plugins directory
final_path = self.plugins_dir / plugin_id
if final_path.exists():
shutil.rmtree(final_path)
shutil.move(str(temp_dir), str(final_path))
# Install dependencies
requirements_file = final_path / "requirements.txt"
if requirements_file.exists():
subprocess.run(
['pip3', 'install', '--break-system-packages', '-r', str(requirements_file)],
check=True
)
self.logger.info(f"Installed plugin from URL: {plugin_id}")
return True
except Exception as e:
self.logger.error(f"Error installing from URL: {e}")
if temp_dir.exists():
shutil.rmtree(temp_dir)
return False
```
---
## 4. Web UI Transformation
### New Web UI Structure
The web UI needs significant updates to support dynamic plugin management:
**New Sections:**
1. **Plugin Store** - Browse, search, install plugins
2. **Plugin Manager** - View installed, enable/disable, configure
3. **Display Rotation** - Drag-and-drop ordering of active displays
4. **Plugin Settings** - Dynamic configuration UI generated from schemas
### Plugin Store UI (React Component Structure)
```javascript
// New: templates/src/components/PluginStore.jsx
import React, { useState, useEffect } from 'react';
export default function PluginStore() {
const [plugins, setPlugins] = useState([]);
const [search, setSearch] = useState('');
const [category, setCategory] = useState('all');
const [loading, setLoading] = useState(false);
useEffect(() => {
fetchPlugins();
}, []);
const fetchPlugins = async () => {
setLoading(true);
try {
const response = await fetch('/api/plugins/store/list');
const data = await response.json();
setPlugins(data.plugins);
} catch (error) {
console.error('Error fetching plugins:', error);
} finally {
setLoading(false);
}
};
const installPlugin = async (pluginId) => {
try {
const response = await fetch('/api/plugins/install', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: pluginId })
});
if (response.ok) {
alert('Plugin installed successfully!');
// Refresh plugin list
fetchPlugins();
}
} catch (error) {
console.error('Error installing plugin:', error);
}
};
const filteredPlugins = plugins.filter(plugin => {
const matchesSearch = search === '' ||
plugin.name.toLowerCase().includes(search.toLowerCase()) ||
plugin.description.toLowerCase().includes(search.toLowerCase());
const matchesCategory = category === 'all' || plugin.category === category;
return matchesSearch && matchesCategory;
});
return (
<div className="plugin-store">
<div className="store-header">
<h1>Plugin Store</h1>
<div className="store-controls">
<input
type="text"
placeholder="Search plugins..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="search-input"
/>
<select
value={category}
onChange={(e) => setCategory(e.target.value)}
className="category-select"
>
<option value="all">All Categories</option>
<option value="time">Time</option>
<option value="weather">Weather</option>
<option value="sports">Sports</option>
<option value="finance">Finance</option>
<option value="entertainment">Entertainment</option>
</select>
</div>
</div>
{loading ? (
<div className="loading">Loading plugins...</div>
) : (
<div className="plugin-grid">
{filteredPlugins.map(plugin => (
<PluginCard
key={plugin.id}
plugin={plugin}
onInstall={installPlugin}
/>
))}
</div>
)}
</div>
);
}
function PluginCard({ plugin, onInstall }) {
return (
<div className="plugin-card">
<div className="plugin-header">
<h3>{plugin.name}</h3>
{plugin.verified && <span className="verified-badge"> Verified</span>}
</div>
<p className="plugin-author">by {plugin.author}</p>
<p className="plugin-description">{plugin.description}</p>
<div className="plugin-meta">
<span className="meta-item"> {plugin.stars}</span>
<span className="meta-item">📥 {plugin.downloads}</span>
<span className="meta-item">{plugin.category}</span>
</div>
<div className="plugin-tags">
{plugin.tags.map(tag => (
<span key={tag} className="tag">{tag}</span>
))}
</div>
<div className="plugin-actions">
<button
className="btn-primary"
onClick={() => onInstall(plugin.id)}
>
Install
</button>
<a
href={plugin.repo}
target="_blank"
rel="noopener noreferrer"
className="btn-secondary"
>
View on GitHub
</a>
</div>
</div>
);
}
```
### Plugin Manager UI
```javascript
// New: templates/src/components/PluginManager.jsx
import React, { useState, useEffect } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
export default function PluginManager() {
const [installedPlugins, setInstalledPlugins] = useState([]);
const [rotationOrder, setRotationOrder] = useState([]);
useEffect(() => {
fetchInstalledPlugins();
}, []);
const fetchInstalledPlugins = async () => {
try {
const response = await fetch('/api/plugins/installed');
const data = await response.json();
setInstalledPlugins(data.plugins);
setRotationOrder(data.rotation_order || []);
} catch (error) {
console.error('Error fetching installed plugins:', error);
}
};
const togglePlugin = async (pluginId, enabled) => {
try {
await fetch('/api/plugins/toggle', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: pluginId, enabled })
});
fetchInstalledPlugins();
} catch (error) {
console.error('Error toggling plugin:', error);
}
};
const uninstallPlugin = async (pluginId) => {
if (!confirm(`Are you sure you want to uninstall ${pluginId}?`)) {
return;
}
try {
await fetch('/api/plugins/uninstall', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: pluginId })
});
fetchInstalledPlugins();
} catch (error) {
console.error('Error uninstalling plugin:', error);
}
};
const handleDragEnd = async (result) => {
if (!result.destination) return;
const newOrder = Array.from(rotationOrder);
const [removed] = newOrder.splice(result.source.index, 1);
newOrder.splice(result.destination.index, 0, removed);
setRotationOrder(newOrder);
try {
await fetch('/api/plugins/rotation-order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ order: newOrder })
});
} catch (error) {
console.error('Error saving rotation order:', error);
}
};
return (
<div className="plugin-manager">
<h1>Installed Plugins</h1>
<div className="plugins-list">
{installedPlugins.map(plugin => (
<div key={plugin.id} className="plugin-item">
<div className="plugin-info">
<h3>{plugin.name}</h3>
<p>{plugin.description}</p>
<span className="version">v{plugin.version}</span>
</div>
<div className="plugin-controls">
<label className="toggle-switch">
<input
type="checkbox"
checked={plugin.enabled}
onChange={(e) => togglePlugin(plugin.id, e.target.checked)}
/>
<span className="slider"></span>
</label>
<button
className="btn-config"
onClick={() => openPluginConfig(plugin.id)}
>
Configure
</button>
<button
className="btn-danger"
onClick={() => uninstallPlugin(plugin.id)}
>
🗑 Uninstall
</button>
</div>
</div>
))}
</div>
<h2>Display Rotation Order</h2>
<DragDropContext onDragEnd={handleDragEnd}>
<Droppable droppableId="rotation">
{(provided) => (
<div
{...provided.droppableProps}
ref={provided.innerRef}
className="rotation-list"
>
{rotationOrder.map((pluginId, index) => {
const plugin = installedPlugins.find(p => p.id === pluginId);
if (!plugin || !plugin.enabled) return null;
return (
<Draggable
key={pluginId}
draggableId={pluginId}
index={index}
>
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
className="rotation-item"
>
<span className="drag-handle"></span>
<span>{plugin.name}</span>
<span className="duration">{plugin.display_duration}s</span>
</div>
)}
</Draggable>
);
})}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
</div>
);
}
```
### API Endpoints for Web UI
```python
# New endpoints in web_interface_v2.py
@app.route('/api/plugins/store/list', methods=['GET'])
def api_plugin_store_list():
"""Get list of available plugins from store."""
try:
store_manager = PluginStoreManager()
registry = store_manager.fetch_registry()
return jsonify({
'status': 'success',
'plugins': registry.get('plugins', [])
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/plugins/install', methods=['POST'])
def api_plugin_install():
"""Install a plugin from the store."""
try:
data = request.get_json()
plugin_id = data.get('plugin_id')
version = data.get('version', 'latest')
store_manager = PluginStoreManager()
success = store_manager.install_plugin(plugin_id)
if success:
# Reload plugin manager to discover new plugin
global plugin_manager
plugin_manager.discover_plugins()
return jsonify({
'status': 'success',
'message': f'Plugin {plugin_id} installed successfully'
})
else:
return jsonify({
'status': 'error',
'message': f'Failed to install plugin {plugin_id}'
}), 500
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/plugins/installed', methods=['GET'])
def api_plugins_installed():
"""Get list of installed plugins."""
try:
global plugin_manager
plugins = []
for plugin_id, plugin in plugin_manager.get_all_plugins().items():
manifest = plugin_manager.plugin_manifests.get(plugin_id, {})
plugins.append({
'id': plugin_id,
'name': manifest.get('name', plugin_id),
'version': manifest.get('version', ''),
'description': manifest.get('description', ''),
'author': manifest.get('author', ''),
'enabled': plugin.enabled,
'display_duration': plugin.get_display_duration()
})
# Get rotation order from config
config = config_manager.load_config()
rotation_order = config.get('display', {}).get('plugin_rotation_order', [])
return jsonify({
'status': 'success',
'plugins': plugins,
'rotation_order': rotation_order
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/plugins/toggle', methods=['POST'])
def api_plugin_toggle():
"""Enable or disable a plugin."""
try:
data = request.get_json()
plugin_id = data.get('plugin_id')
enabled = data.get('enabled', True)
# Update config
config = config_manager.load_config()
if plugin_id not in config:
config[plugin_id] = {}
config[plugin_id]['enabled'] = enabled
config_manager.save_config(config)
# Reload plugin
global plugin_manager
if enabled:
plugin_manager.load_plugin(plugin_id)
else:
plugin_manager.unload_plugin(plugin_id)
return jsonify({
'status': 'success',
'message': f'Plugin {plugin_id} {"enabled" if enabled else "disabled"}'
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/plugins/uninstall', methods=['POST'])
def api_plugin_uninstall():
"""Uninstall a plugin."""
try:
data = request.get_json()
plugin_id = data.get('plugin_id')
# Unload first
global plugin_manager
plugin_manager.unload_plugin(plugin_id)
# Uninstall
store_manager = PluginStoreManager()
success = store_manager.uninstall_plugin(plugin_id)
if success:
return jsonify({
'status': 'success',
'message': f'Plugin {plugin_id} uninstalled successfully'
})
else:
return jsonify({
'status': 'error',
'message': f'Failed to uninstall plugin {plugin_id}'
}), 500
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/plugins/rotation-order', methods=['POST'])
def api_plugin_rotation_order():
"""Update plugin rotation order."""
try:
data = request.get_json()
order = data.get('order', [])
# Update config
config = config_manager.load_config()
if 'display' not in config:
config['display'] = {}
config['display']['plugin_rotation_order'] = order
config_manager.save_config(config)
return jsonify({
'status': 'success',
'message': 'Rotation order updated'
})
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
@app.route('/api/plugins/install-from-url', methods=['POST'])
def api_plugin_install_from_url():
"""Install a plugin from a custom GitHub URL."""
try:
data = request.get_json()
repo_url = data.get('repo_url')
if not repo_url:
return jsonify({
'status': 'error',
'message': 'repo_url is required'
}), 400
store_manager = PluginStoreManager()
success = store_manager.install_from_url(repo_url)
if success:
# Reload plugin manager
global plugin_manager
plugin_manager.discover_plugins()
return jsonify({
'status': 'success',
'message': 'Plugin installed from URL successfully'
})
else:
return jsonify({
'status': 'error',
'message': 'Failed to install plugin from URL'
}), 500
except Exception as e:
return jsonify({
'status': 'error',
'message': str(e)
}), 500
```
---
## 5. Migration Strategy
### Phase 1: Core Plugin Infrastructure (v2.0.0)
**Goal**: Build plugin system alongside existing managers
**Changes**:
1. Create `src/plugin_system/` module
2. Implement `BasePlugin`, `PluginManager`, `PluginStoreManager`
3. Add `plugins/` directory support
4. Modify `display_controller.py` to load both legacy and plugins
5. Update web UI to show plugin store tab
**Backward Compatibility**: 100% - all existing managers still work
### Phase 2: Example Plugins (v2.1.0)
**Goal**: Create reference plugins and migration examples
**Create Official Plugins**:
1. `ledmatrix-clock-simple` - Simple clock (migrated from existing)
2. `ledmatrix-weather-basic` - Basic weather display
3. `ledmatrix-stocks-ticker` - Stock ticker
4. `ledmatrix-nhl-scores` - NHL scoreboard
**Changes**:
- Document plugin creation process
- Create plugin templates
- Update wiki with plugin development guide
**Backward Compatibility**: 100% - plugins are additive
### Phase 3: Migration Tools (v2.2.0)
**Goal**: Provide tools to migrate existing setups
**Migration Script**:
```python
# scripts/migrate_to_plugins.py
import json
from pathlib import Path
def migrate_config():
"""
Migrate existing config.json to plugin-based format.
"""
config_path = Path("config/config.json")
with open(config_path, 'r') as f:
config = json.load(f)
# Create migration plan
migration_map = {
'clock': 'clock-simple',
'weather': 'weather-basic',
'stocks': 'stocks-ticker',
'nhl_scoreboard': 'nhl-scores',
# ... etc
}
# Install recommended plugins
from src.plugin_system.store_manager import PluginStoreManager
store = PluginStoreManager()
for legacy_key, plugin_id in migration_map.items():
if config.get(legacy_key, {}).get('enabled', False):
print(f"Migrating {legacy_key} to plugin {plugin_id}")
store.install_plugin(plugin_id)
# Migrate config section
if legacy_key in config:
config[plugin_id] = config[legacy_key]
# Save migrated config
with open("config/config.json.migrated", 'w') as f:
json.dump(config, f, indent=2)
print("Migration complete! Review config.json.migrated")
if __name__ == "__main__":
migrate_config()
```
**User Instructions**:
```bash
# 1. Backup existing config
cp config/config.json config/config.json.backup
# 2. Run migration script
python3 scripts/migrate_to_plugins.py
# 3. Review migrated config
cat config/config.json.migrated
# 4. Apply migration
mv config/config.json.migrated config/config.json
# 5. Restart service
sudo systemctl restart ledmatrix
```
### Phase 4: Deprecation (v2.5.0)
**Goal**: Mark legacy managers as deprecated
**Changes**:
- Add deprecation warnings to legacy managers
- Update documentation to recommend plugins
- Create migration guide in wiki
**Backward Compatibility**: 95% - legacy still works but shows warnings
### Phase 5: Plugin-Only (v3.0.0)
**Goal**: Remove legacy managers from core
**Breaking Changes**:
- Remove hardcoded manager imports from `display_controller.py`
- Remove legacy manager files from `src/`
- Package legacy managers as official plugins
- Update config template to plugin-based format
**Migration Required**: Users must run migration script
---
## 6. Plugin Developer Guidelines
### Creating a New Plugin
#### Step 1: Plugin Structure
```bash
# Create plugin directory
mkdir -p plugins/my-plugin
cd plugins/my-plugin
# Create required files
touch manifest.json
touch manager.py
touch requirements.txt
touch config_schema.json
touch README.md
```
#### Step 2: Manifest
```json
{
"id": "my-plugin",
"name": "My Custom Display",
"version": "1.0.0",
"author": "YourName",
"description": "A custom display for LEDMatrix",
"homepage": "https://github.com/YourName/ledmatrix-my-plugin",
"entry_point": "manager.py",
"class_name": "MyPluginManager",
"category": "custom",
"tags": ["custom", "example"],
"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": {},
"update_interval": 60,
"default_duration": 15,
"display_modes": ["my-plugin"],
"api_requirements": []
}
```
#### Step 3: Manager Implementation
```python
# manager.py
from src.plugin_system.base_plugin import BasePlugin
import time
class MyPluginManager(BasePlugin):
"""
Example plugin that displays custom content.
"""
def __init__(self, plugin_id, config, display_manager, cache_manager, plugin_manager):
super().__init__(plugin_id, config, display_manager, cache_manager, plugin_manager)
# Plugin-specific initialization
self.message = config.get('message', 'Hello, World!')
self.color = tuple(config.get('color', [255, 255, 255]))
self.last_update = 0
def update(self):
"""
Update plugin data.
Called based on update_interval in manifest.
"""
# Fetch or update data here
self.last_update = time.time()
self.logger.info(f"Updated {self.plugin_id}")
def display(self, force_clear=False):
"""
Render the plugin display.
"""
if force_clear:
self.display_manager.clear()
# Get display dimensions
width = self.display_manager.width
height = self.display_manager.height
# Draw custom content
self.display_manager.draw_text(
self.message,
x=width // 2,
y=height // 2,
color=self.color,
centered=True
)
# Update the physical display
self.display_manager.update_display()
self.logger.debug(f"Displayed {self.plugin_id}")
```
#### Step 4: Configuration Schema
```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"enabled": {
"type": "boolean",
"default": true,
"description": "Enable or disable this plugin"
},
"message": {
"type": "string",
"default": "Hello, World!",
"description": "Message to display"
},
"color": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0,
"maximum": 255
},
"minItems": 3,
"maxItems": 3,
"default": [255, 255, 255],
"description": "RGB color for text"
},
"display_duration": {
"type": "number",
"default": 15,
"minimum": 1,
"description": "How long to display in seconds"
}
},
"required": ["enabled"]
}
```
#### Step 5: README
```markdown
# My Custom Display Plugin
A custom display plugin for LEDMatrix.
## Installation
From the LEDMatrix web UI:
1. Go to Plugin Store
2. Search for "My Custom Display"
3. Click Install
Or install from command line:
```bash
cd /path/to/LEDMatrix
python3 -c "from src.plugin_system.store_manager import PluginStoreManager; PluginStoreManager().install_plugin('my-plugin')"
```
## Configuration
Add to `config/config.json`:
```json
{
"my-plugin": {
"enabled": true,
"message": "Hello, World!",
"color": [255, 255, 255],
"display_duration": 15
}
}
```
## Options
- `message` (string): Text to display
- `color` (array): RGB color [R, G, B]
- `display_duration` (number): Display time in seconds
## License
MIT
```
### Publishing a Plugin
#### Step 1: Create GitHub Repository
```bash
# Initialize git
git init
git add .
git commit -m "Initial commit"
# Create on GitHub and push
git remote add origin https://github.com/YourName/ledmatrix-my-plugin.git
git push -u origin main
```
#### Step 2: Create Release
```bash
# Tag version
git tag -a v1.0.0 -m "Version 1.0.0"
git push origin v1.0.0
```
Create release on GitHub with:
- Release notes
- Installation instructions
- Screenshots/GIFs
#### Step 3: Submit to Registry
Create pull request to `ChuckBuilds/ledmatrix-plugin-registry` adding your plugin:
```json
{
"id": "my-plugin",
"name": "My Custom Display",
"description": "A custom display for LEDMatrix",
"author": "YourName",
"category": "custom",
"tags": ["custom", "example"],
"repo": "https://github.com/YourName/ledmatrix-my-plugin",
"branch": "main",
"versions": [
{
"version": "1.0.0",
"ledmatrix_min_version": "2.0.0",
"released": "2025-01-15",
"download_url": "https://github.com/YourName/ledmatrix-my-plugin/archive/refs/tags/v1.0.0.zip"
}
],
"verified": false
}
```
---
## 7. Technical Implementation Details
### Configuration Management
**Old Way** (monolithic):
```json
{
"clock": { "enabled": true },
"weather": { "enabled": true },
"nhl_scoreboard": { "enabled": true }
}
```
**New Way** (plugin-based):
```json
{
"plugins": {
"clock-simple": { "enabled": true },
"weather-basic": { "enabled": true },
"nhl-scores": { "enabled": true }
},
"display": {
"plugin_rotation_order": [
"clock-simple",
"weather-basic",
"nhl-scores"
]
}
}
```
### Dependency Management
Each plugin manages its own dependencies via `requirements.txt`:
```txt
# plugins/nhl-scores/requirements.txt
requests>=2.28.0
pytz>=2022.1
```
During installation:
```python
subprocess.run([
'pip3', 'install',
'--break-system-packages',
'-r', 'plugins/nhl-scores/requirements.txt'
])
```
### Asset Management
Plugins can include their own assets:
```
plugins/nhl-scores/
├── assets/
│ ├── logos/
│ │ ├── TB.png
│ │ └── DAL.png
│ └── fonts/
│ └── sports.bdf
```
Access in plugin:
```python
def get_asset_path(self, relative_path):
"""Get absolute path to plugin asset."""
plugin_dir = Path(__file__).parent
return plugin_dir / "assets" / relative_path
# Usage
logo_path = self.get_asset_path("logos/TB.png")
```
### Caching Integration
Plugins use the shared cache manager:
```python
def update(self):
cache_key = f"{self.plugin_id}_data"
# Try to get cached data
cached = self.cache_manager.get(cache_key, max_age=3600)
if cached:
self.data = cached
return
# Fetch fresh data
self.data = self._fetch_from_api()
# Cache it
self.cache_manager.set(cache_key, self.data)
```
### Inter-Plugin Communication
Plugins can communicate through the plugin manager:
```python
# In plugin A
other_plugin = self.plugin_manager.get_plugin('plugin-b')
if other_plugin:
data = other_plugin.get_shared_data()
# In plugin B
def get_shared_data(self):
return {'temperature': 72, 'conditions': 'sunny'}
```
### Error Handling
Plugins should handle errors gracefully:
```python
def display(self, force_clear=False):
try:
# Plugin logic
self._render_content()
except Exception as e:
self.logger.error(f"Error in display: {e}", exc_info=True)
# Show error message on display
self.display_manager.clear()
self.display_manager.draw_text(
f"Error: {self.plugin_id}",
x=5, y=15,
color=(255, 0, 0)
)
self.display_manager.update_display()
```
---
## 8. Best Practices & Standards
### Plugin Best Practices
1. **Follow BasePlugin Interface**: Always extend `BasePlugin` and implement required methods
2. **Validate Configuration**: Use config schemas to validate user settings
3. **Handle Errors Gracefully**: Never crash the entire system
4. **Use Logging**: Log important events and errors
5. **Cache Appropriately**: Use cache manager for API responses
6. **Clean Up Resources**: Implement `cleanup()` for resource disposal
7. **Document Everything**: Provide clear README and code comments
8. **Test on Hardware**: Test on actual Raspberry Pi with LED matrix
9. **Version Properly**: Use semantic versioning
10. **Respect Resources**: Be mindful of CPU, memory, and API quotas
### Coding Standards
```python
# Good: Clear, documented, error-handled
class MyPlugin(BasePlugin):
"""
Custom plugin that displays messages.
Configuration:
message (str): Message to display
color (tuple): RGB color tuple
"""
def __init__(self, plugin_id, config, display_manager, cache_manager, plugin_manager):
super().__init__(plugin_id, config, display_manager, cache_manager, plugin_manager)
self.message = config.get('message', 'Default')
self.validate_color(config.get('color', (255, 255, 255)))
def validate_color(self, color):
"""Validate color is proper RGB tuple."""
if not isinstance(color, (list, tuple)) or len(color) != 3:
raise ValueError("Color must be RGB tuple")
if not all(0 <= c <= 255 for c in color):
raise ValueError("Color values must be 0-255")
self.color = tuple(color)
def update(self):
"""Update plugin data."""
try:
# Update logic
pass
except Exception as e:
self.logger.error(f"Update failed: {e}")
def display(self, force_clear=False):
"""Display plugin content."""
try:
if force_clear:
self.display_manager.clear()
self.display_manager.draw_text(
self.message,
x=5, y=15,
color=self.color
)
self.display_manager.update_display()
except Exception as e:
self.logger.error(f"Display failed: {e}")
```
### Testing Guidelines
```python
# test/test_my_plugin.py
import unittest
from unittest.mock import Mock, MagicMock
import sys
sys.path.insert(0, 'plugins/my-plugin')
from manager import MyPluginManager
class TestMyPlugin(unittest.TestCase):
def setUp(self):
"""Set up test fixtures."""
self.config = {
'enabled': True,
'message': 'Test',
'color': [255, 0, 0]
}
self.display_manager = Mock()
self.cache_manager = Mock()
self.plugin_manager = Mock()
self.plugin = MyPluginManager(
plugin_id='my-plugin',
config=self.config,
display_manager=self.display_manager,
cache_manager=self.cache_manager,
plugin_manager=self.plugin_manager
)
def test_initialization(self):
"""Test plugin initializes correctly."""
self.assertEqual(self.plugin.message, 'Test')
self.assertEqual(self.plugin.color, (255, 0, 0))
def test_display_calls_manager(self):
"""Test display method calls display manager."""
self.plugin.display()
self.display_manager.draw_text.assert_called_once()
self.display_manager.update_display.assert_called_once()
def test_invalid_color_raises_error(self):
"""Test invalid color configuration raises error."""
bad_config = {'color': [300, 0, 0]}
with self.assertRaises(ValueError):
MyPluginManager(
'test', bad_config,
self.display_manager,
self.cache_manager,
self.plugin_manager
)
if __name__ == '__main__':
unittest.main()
```
---
## 9. Security Considerations
### Plugin Verification
**Verified Plugins**:
- Reviewed by maintainers
- Follow best practices
- No known security issues
- Marked with ✓ badge in store
**Unverified Plugins**:
- User-contributed
- Not reviewed
- Install at own risk
- Show warning before installation
### Code Review Process
Before marking a plugin as verified:
1. **Code Review**: Manual inspection of code
2. **Dependency Audit**: Check all requirements
3. **Permission Check**: Verify minimal permissions
4. **API Key Safety**: Ensure no hardcoded secrets
5. **Resource Usage**: Check for excessive CPU/memory use
6. **Testing**: Test on actual hardware
### Sandboxing Considerations
Current implementation has NO sandboxing. Plugins run with same permissions as main process.
**Future Enhancement** (v3.x):
- Run plugins in separate processes
- Limit file system access
- Rate limit API calls
- Monitor resource usage
- Kill misbehaving plugins
### User Guidelines
**For Users**:
1. Only install plugins from trusted sources
2. Review plugin permissions before installing
3. Check plugin ratings and reviews
4. Keep plugins updated
5. Report suspicious plugins
**For Developers**:
1. Never include hardcoded API keys
2. Minimize required permissions
3. Use secure API practices
4. Validate all user inputs
5. Handle errors gracefully
---
## 10. Implementation Roadmap
### Timeline
**Phase 1: Foundation (Weeks 1-3)**
- Create plugin system infrastructure
- Implement BasePlugin, PluginManager, StoreManager
- Update display_controller for plugin support
- Basic web UI for plugin management
**Phase 2: Example Plugins (Weeks 4-5)**
- Create 4-5 reference plugins
- Migrate existing managers as examples
- Write developer documentation
- Create plugin templates
**Phase 3: Store Integration (Weeks 6-7)**
- Set up plugin registry repo
- Implement store API
- Build web UI for store
- Add search and filtering
**Phase 4: Migration Tools (Weeks 8-9)**
- Create migration script
- Test with existing installations
- Write migration guide
- Update documentation
**Phase 5: Testing & Polish (Weeks 10-12)**
- Comprehensive testing on Pi hardware
- Bug fixes
- Performance optimization
- Documentation improvements
**Phase 6: Release v2.0.0 (Week 13)**
- Tag release
- Publish documentation
- Announce to community
- Gather feedback
### Success Metrics
**Technical**:
- 100% backward compatibility in v2.0
- <100ms plugin load time
- <5% performance overhead
- Zero critical bugs in first month
**User Adoption**:
- 10+ community-created plugins in 3 months
- 50%+ of users install at least one plugin
- Positive feedback on ease of use
**Developer Experience**:
- Clear documentation
- Responsive to plugin dev questions
- Regular updates to plugin system
---
## Appendix A: File Structure Comparison
### Before (v1.x)
```
LEDMatrix/
├── src/
│ ├── clock.py
│ ├── weather_manager.py
│ ├── stock_manager.py
│ ├── nhl_managers.py
│ ├── nba_managers.py
│ ├── mlb_manager.py
│ └── ... (40+ manager files)
├── config/
│ ├── config.json (650+ lines)
│ └── config.template.json
└── web_interface_v2.py (hardcoded imports)
```
### After (v2.0+)
```
LEDMatrix/
├── src/
│ ├── plugin_system/
│ │ ├── __init__.py
│ │ ├── base_plugin.py
│ │ ├── plugin_manager.py
│ │ └── store_manager.py
│ ├── display_controller.py (plugin-aware)
│ └── ... (core components only)
├── plugins/
│ ├── clock-simple/
│ ├── weather-basic/
│ ├── nhl-scores/
│ └── ... (user-installed plugins)
├── config/
│ └── config.json (minimal core config)
└── web_interface_v2.py (dynamic plugin loading)
```
---
## Appendix B: Example Plugin: NHL Scoreboard
Complete example of migrating NHL scoreboard to plugin:
**Directory Structure**:
```
plugins/nhl-scores/
├── manifest.json
├── manager.py
├── requirements.txt
├── config_schema.json
├── assets/
│ └── logos/
│ ├── TB.png
│ └── ... (NHL team logos)
└── README.md
```
**manifest.json**:
```json
{
"id": "nhl-scores",
"name": "NHL Scoreboard",
"version": "1.0.0",
"author": "ChuckBuilds",
"description": "Display NHL game scores and schedules",
"homepage": "https://github.com/ChuckBuilds/ledmatrix-nhl-scores",
"entry_point": "manager.py",
"class_name": "NHLScoresPlugin",
"category": "sports",
"tags": ["nhl", "hockey", "sports", "scores"],
"compatible_versions": [">=2.0.0"],
"requires": {
"python": ">=3.9",
"display_size": {
"min_width": 64,
"min_height": 32
}
},
"config_schema": "config_schema.json",
"assets": {
"logos": "assets/logos/"
},
"update_interval": 60,
"default_duration": 30,
"display_modes": ["nhl_live", "nhl_recent", "nhl_upcoming"],
"api_requirements": ["ESPN API"]
}
```
**requirements.txt**:
```txt
requests>=2.28.0
pytz>=2022.1
```
**manager.py** (abbreviated):
```python
from src.plugin_system.base_plugin import BasePlugin
import requests
from datetime import datetime
from pathlib import Path
class NHLScoresPlugin(BasePlugin):
"""NHL Scoreboard plugin for LEDMatrix."""
ESPN_NHL_URL = "https://site.api.espn.com/apis/site/v2/sports/hockey/nhl/scoreboard"
def __init__(self, plugin_id, config, display_manager, cache_manager, plugin_manager):
super().__init__(plugin_id, config, display_manager, cache_manager, plugin_manager)
self.favorite_teams = config.get('favorite_teams', [])
self.show_favorite_only = config.get('show_favorite_teams_only', True)
self.games = []
def update(self):
"""Fetch NHL games from ESPN API."""
cache_key = f"{self.plugin_id}_games"
# Try cache first
cached = self.cache_manager.get(cache_key, max_age=60)
if cached:
self.games = cached
self.logger.debug("Using cached NHL data")
return
try:
response = requests.get(self.ESPN_NHL_URL, timeout=10)
response.raise_for_status()
data = response.json()
self.games = self._process_games(data.get('events', []))
# Cache the results
self.cache_manager.set(cache_key, self.games)
self.logger.info(f"Fetched {len(self.games)} NHL games")
except Exception as e:
self.logger.error(f"Error fetching NHL data: {e}")
def _process_games(self, events):
"""Process raw ESPN data into game objects."""
games = []
for event in events:
# Extract game info
# ... (implementation)
pass
return games
def display(self, force_clear=False):
"""Display NHL scores."""
if force_clear:
self.display_manager.clear()
if not self.games:
self._show_no_games()
return
# Show first game (or cycle through)
game = self.games[0]
self._display_game(game)
self.display_manager.update_display()
def _display_game(self, game):
"""Render a single game."""
# Load team logos
away_logo = self._get_logo(game['away_team'])
home_logo = self._get_logo(game['home_team'])
# Draw logos and scores
# ... (implementation)
def _get_logo(self, team_abbr):
"""Get team logo from assets."""
logo_path = Path(__file__).parent / "assets" / "logos" / f"{team_abbr}.png"
if logo_path.exists():
return logo_path
return None
def _show_no_games(self):
"""Show 'no games' message."""
self.display_manager.draw_text(
"No NHL games",
x=5, y=15,
color=(255, 255, 255)
)
```
---
## Conclusion
This specification outlines a comprehensive transformation of the LEDMatrix project into a modular, extensible platform. The plugin architecture enables:
- **User Extensibility**: Anyone can create custom displays
- **Easy Distribution**: GitHub-based store for discovery and installation
- **Backward Compatibility**: Gradual migration path for existing users
- **Community Growth**: Lower barrier to contribution
- **Better Maintenance**: Smaller core, cleaner codebase
The gradual migration approach ensures existing users aren't disrupted while new users benefit from the improved architecture.
**Next Steps**:
1. Review and refine this specification
2. Begin Phase 1 implementation
3. Create prototype plugins for testing
4. Gather community feedback
5. Iterate and improve
---
**Document Version**: 1.0.0
**Last Updated**: 2025-01-09
**Author**: AI Assistant (Claude)
**Status**: Draft for Review