72 Commits

Author SHA1 Message Date
ca8d4a3d36 feat: upgrade to version 2.0.0-alpha with mainstream dependencies
- Update application version to 2.0.0-alpha
- Update application name to 'Ambient Light Control'
- Upgrade Node.js requirement to >=22.0.0 (current LTS)
- Upgrade pnpm requirement to >=10.0.0 (current stable)
- Update all GitHub Actions workflows to use Node.js 22 and pnpm 10
- Update README.md with current version requirements
- Add comprehensive project metadata to package.json
- Remove obsolete src-tauri/src-tauri directory structure
- Update Cargo.toml with proper project information
2025-07-09 20:05:38 +08:00
a49306517e style: optimize LED strip component styling with proper margins and padding 2025-07-09 16:59:07 +08:00
142332730f fix: update 0x02 protocol to use byte offset instead of LED position offset 2025-07-09 16:59:07 +08:00
5f5824721e docs: add MIT license and update README with license information 2025-07-09 16:59:07 +08:00
7e70fb9d8d fix: resolve input field clearing issue in LED strip test page 2025-07-09 16:59:07 +08:00
93de5dd39a fix: resolve dropdown menu gap issue 2025-07-09 16:59:07 +08:00
953cb24a3b fix: resolve i18n implementation issues 2025-07-09 16:59:07 +08:00
a8f2b93de0 refactor: complete LED type system simplification 2025-07-09 16:59:07 +08:00
2d502fcd6c refactor: simplify LED type system to support only WS2812B and SK6812 chips 2025-07-09 16:59:07 +08:00
2c6b777fa6 feat: implement comprehensive i18n internationalization support
- Add custom i18n infrastructure with TypeScript support
- Support Chinese (zh-CN) and English (en-US) languages
- Implement language switching with localStorage persistence
- Update all components with translation keys:
  * System info components (board-info-panel, board-index)
  * Display management components (display-state-index, display-state-card)
  * LED strip configuration components (led-strip-configuration, led-count-control-panel)
  * White balance component with detailed usage instructions
  * LED test component with test pattern descriptions
- Add comprehensive translation coverage for:
  * Navigation menus and page titles
  * Common UI elements (buttons, status, actions)
  * Hardware information and connection status
  * Display configuration options
  * LED strip settings and controls
  * White balance adjustment instructions and tips
  * LED test modes and descriptions
  * Error messages and status indicators
- Features:
  * Dynamic language switching without app restart
  * Type-safe translation keys with full TypeScript support
  * Modular design for easy language extension
  * Responsive UI updates using SolidJS reactivity
2025-07-08 16:55:12 +08:00
4a3d7681d6 Fix layout spacing issues in LED strip configuration
- Remove forced height expansion from display configuration panel
- Change layout from flex-based to space-based for natural content sizing
- Eliminate large empty spaces between configuration sections
- Improve overall UI compactness and visual flow
2025-07-08 03:19:06 +08:00
2834b7fe57 Optimize responsive layout for LED count control interface
- Improve grid layout responsiveness from md:grid-cols-2 to lg:grid-cols-2
- Add responsive LED control items with grid-cols-2 sm:grid-cols-4
- Reduce padding and spacing for better small window display
- Optimize button and input sizes with compact styling
- Add custom CSS for small screen handling (<640px and <600px)
- Implement auto-fit grid layout with minmax(280px, 1fr)
- Enhance main container with overflow-x-auto and responsive padding
- Reduce overall page spacing and card body padding for compact display
2025-07-08 03:02:24 +08:00
c57f52ea74 Improve white balance panel drag functionality
- Fix drag event handling to only trigger on title bar area
- Prevent color slider interactions from triggering panel drag
- Add event propagation control for better user experience
- Improve cursor styling for interactive elements
2025-07-08 02:46:44 +08:00
9f37b4043c Fix device selection reset issue in LED Strip Testing
- Fix frontend device selection state management to properly update selected board when boards_changed event is triggered
- Optimize backend board status checking to only emit boards_changed events when there are actual changes
- Prevent unnecessary UI updates and improve performance

Fixes issue where device selection would reset to unselected state shortly after selection
2025-07-08 02:46:24 +08:00
92349eebb6 Fix hamburger menu button click issue
- Add dropdown-hover class for better interaction
- Add onClick handler to ensure proper focus management
- Increase z-index from z-[1] to z-[100] to prevent overlay issues
- Remove conflicting tabindex from menu items
- Add border and hover effects for better visual feedback
2025-07-07 19:20:05 +08:00
d1fc5713a1 Fix top navigation bar to prevent scrolling
- Add fixed positioning to navbar with top-0, left-0, right-0, z-50 classes
- Increase main content top padding to pt-20 to account for fixed navbar height
- Ensure navbar stays visible at top of screen during page scrolling
2025-07-07 14:59:42 +08:00
d1a614fbbb docs: enhance hardware protocol documentation and reorganize project docs
- Complete hardware communication protocol documentation with:
  * Add ping/pong health check protocol (0x01)
  * Add hardware control protocols (0x03 brightness, 0x04 volume)
  * Add mDNS service discovery specifications
  * Add connection state management and retry logic
  * Add comprehensive troubleshooting guide
  * Update hardware implementation examples

- Reorganize project documentation:
  * Move device auto-refresh docs from root to docs/ directory
  * Rename files to follow kebab-case convention
  * Maintain complete technical implementation details

- Fix markdown formatting issues:
  * Add proper language tags to code blocks
  * Ensure consistent documentation structure
2025-07-07 13:50:05 +08:00
2a49b081cb feat: Add GitHub Actions workflows for CI/CD
- Add cross-platform build workflow for macOS, Windows, Linux
- Add CI workflow with Rust code quality checks
- Add manual release workflow with automatic asset publishing
- Add dependency management workflow with security monitoring
- Update README with build status badges
- Remove unused Prettier/ESLint configurations
- Focus on Rust code quality and build verification
2025-07-06 03:45:55 +08:00
7e2dafa3d2 Implement LED test effects with proper cleanup
- Add LED test effects page with multiple test patterns (solid colors, rainbow, breathing, flowing)
- Implement Rust backend for LED test effects with proper task management
- Add automatic cleanup when navigating away from test page using onCleanup hook
- Ensure test mode is properly disabled to resume normal ambient lighting
- Clean up debug logging for production readiness
- Fix menu navigation issues by using SolidJS router components

Features:
- Multiple test patterns: solid colors, rainbow cycle, breathing effect, flowing lights
- Configurable animation speed
- Automatic cleanup prevents LED conflicts with ambient lighting
- Responsive UI with proper error handling
2025-07-06 02:37:15 +08:00
90cace679b Implement synchronized LED strip highlighting with theme colors and clean up debug logs
- Add three-way synchronized highlighting between LED strip components
- Implement hover and selection state synchronization across display borders, sorter, and control panels
- Replace hardcoded colors with DaisyUI theme colors (primary, warning, base-content)
- Use background highlighting for sorter to prevent interface jittering
- Reduce LED strip width from 24px to 20px for better visual appearance
- Clean up console.log statements and debug output for production readiness
- Maintain layout stability by avoiding size changes in highlighting effects
2025-07-05 14:32:31 +08:00
99cbaf3b9f feat: Add RGBW LED support and hardware communication protocol
- Add RGBW LED type support alongside existing RGB LEDs
- Implement 4-channel RGBW data transmission (R,G,B,W bytes)
- Add RGBW visual preview with half-color, half-white gradient display
- Fix RGB color calibration bug in publisher (was not being applied)
- Create comprehensive hardware communication protocol documentation
- Support mixed RGB/RGBW LED strips on same display
- Add W channel color temperature adjustment in white balance page
- Hardware acts as simple UDP-to-WS2812 bridge without type distinction
2025-07-05 02:46:31 +08:00
5de105960b Merge pull request 'feat: Replace screen capture with ScreenCaptureKit and fix performance issues' (#6) from replace-rust-swift-screencapture-with-screencapturekit into develop
Reviewed-on: #6
2025-07-04 22:03:41 +08:00
3a44b96621 Update README.md with comprehensive project documentation
- Replace default Tauri template content with detailed project description
- Add comprehensive feature list and tech stack information
- Include complete installation and development setup guide
- Document application interface and configuration details
- Add development workflow and debugging tips
- Provide contributing guidelines and support information
- Write documentation in English for international accessibility
2025-07-04 21:57:36 +08:00
5da81e5f93 Fix resource leak and CPU performance issues
- Fix integer underflow panic in LED color publisher by adding bounds checking
- Reduce screenshot capture frequency from 15 FPS to 5 FPS for better CPU performance
- Reduce WebSocket force-send frequency from 200ms to 500ms
- Fix WebSocket resource leak by properly cleaning up streams when connections end
- Add proper stream lifecycle management with is_running flag checks
- Ensure background tasks exit when streams are stopped

This resolves the issue where CPU usage remained above 100% after visiting
the LED strip configuration page, even when navigating to other pages.
2025-07-04 21:49:05 +08:00
a10fae75d2 Refactor LED strip configuration interface layout
- Separate LED control panels from display preview areas
- Add dedicated LED count control section at bottom of page
- Create new LedCountControlPanel component with 4-column grid layout
- Fix display container height to prevent layout overflow
- Remove embedded LED controls from DisplayView component
- Improve text color for display info panel title
- Hide spinner buttons on number inputs for cleaner UI
- Enhance input field styling with centered text and larger font
2025-07-04 19:13:35 +08:00
5f12b8312a feat: enhance white balance interface with expandable help content
- Add comprehensive expandable help section in normal mode with detailed instructions
- Include usage recommendations, adjustment tips, and comparison methods
- Add simplified tooltip in fullscreen mode for quick reference
- Improve user guidance for LED strip color calibration process
- Maintain dual-mode functionality (normal/fullscreen) with appropriate help content
2025-07-04 18:31:44 +08:00
1944c88b55 Optimize screen streaming performance and clean up debug logs
- Reduced image processing time from 7-8 seconds to 340-420ms (15-20x improvement)
- Optimized BGRA->RGBA conversion with unsafe pointer operations and batch processing
- Changed image resize filter from Lanczos3 to Nearest for maximum speed
- Reduced target resolution from 400x225 to 320x180 for better performance
- Reduced JPEG quality from 75 to 50 for faster compression
- Fixed force-send mechanism timing from 500ms to 200ms intervals
- Improved frame rate from 0 FPS to ~2.5 FPS
- Cleaned up extensive debug logging and performance instrumentation
- Removed unused imports and variables to reduce compiler warnings
2025-07-04 14:45:50 +08:00
c8db28168c feat: Add Daisy-UI and optimize LED strip configuration UI
- Install and configure Tailwind CSS 4.1 with Daisy-UI plugin
- Redesign main navigation with responsive navbar and dark theme
- Optimize LED strip configuration layout with modern card components
- Improve screen preview performance with frame-based rendering
- Reduce LED pixel size for better visual appearance
- Remove excessive debug logging for better performance
- Fix Tailwind CSS ESM compatibility issues with dynamic imports
2025-07-03 13:28:19 +08:00
93ad9ae46c feat: implement real-time LED strip preview
- Add LED strip visualization around display previews
- Show real-time color status for each LED pixel
- Support multi-display LED strip configurations
- Use elegant 16px thin LED strip design
- Real-time LED color sync via WebSocket
- Responsive layout with display scaling support
2025-07-03 02:09:19 +08:00
6c30a824b0 feat: upgrade Tailwind CSS to v4.1.11
- Upgrade Tailwind CSS from 3.x to 4.x for latest features and performance
- Install @tailwindcss/postcss plugin for Tailwind CSS 4.0 compatibility
- Update CSS configuration to use new @import and @config syntax
- Update PostCSS configuration to use new plugin format
- Build working correctly with new Tailwind CSS engine
2025-06-30 18:01:26 +08:00
515b3a4ccb feat: upgrade Vite to v6.3.5
- Upgrade Vite from 4.x to 6.x for better performance and features
- Update @types/node to v24.0.7 for compatibility
- Maintain compatibility with vite-plugin-solid 2.11.7
- Build and development server working correctly
2025-06-30 17:51:53 +08:00
ddf61c861d feat: update dependencies to latest compatible versions
- Update frontend dependencies (SolidJS, Vite, Tailwind, etc.)
- Update backend dependencies (Tauri 1.8.3, Tokio, Serde, etc.)
- Fix thread safety issues with SafeDisplay wrapper for ddc-hi::Display
- Resolve display-info API compatibility issues
- All dependencies updated within major version constraints
2025-06-30 17:35:03 +08:00
b1fd751090 Fix LED color events and improve screenshot capture
- Fix LED color publisher: uncomment display_colors_tx.send() to enable LED color events
- Replace rust_swift_screencapture with screen-capture-kit for better macOS compatibility
- Add bounds checking in LED color processing to prevent array index errors
- Update screenshot manager to use CGDisplay as fallback implementation
- Fix frontend screenshot URL protocol to use ambient-light://
- Add debug logging for LED color events in frontend
- Remove debug logs that were added for troubleshooting
- Update dependencies and remove CMake-dependent paho-mqtt temporarily

This resolves the issue where LED color events were not being sent to the frontend,
enabling real-time LED color visualization in the UI.
2025-06-30 14:35:03 +08:00
91983e6728 feat: 电脑睡眠后唤醒,支持重新开始捕捉屏幕内容。 2023-06-17 17:36:32 +08:00
bab3b8941e fix: 临时避免 CPU 占用率高的问题。 2023-06-10 21:09:36 +08:00
268ec1df81 feat: 使用 ScreenCaptureKit 获取屏幕帧数据。 2023-06-05 22:34:32 +08:00
ed72bdfdb1 feat: 改用 udp 向板子发送颜色校准信息。 2023-05-12 20:38:24 +08:00
98d2f7891a feat: 支持定期向板子发送显示器亮度信息。 2023-05-11 21:52:50 +08:00
3a23e1760b feat: 支持记住显示器配置。 2023-05-11 14:13:14 +08:00
8b124f8182 feat: 当新板子上线或音量变化时,推送当前音量给板子。 2023-05-10 21:50:51 +08:00
878180ed5b fix: 亮度调节指令频繁时通道被关闭。 2023-05-10 21:18:55 +08:00
5ddd704c9d chore: 完善。 2023-05-09 21:57:52 +08:00
2c5ac11579 feat: 支持设置音量。 2023-05-07 18:18:34 +08:00
9109518822 chore: 清理代码。 2023-05-07 15:21:27 +08:00
d9d73f01d7 feat: 支持控制显示器参数。 2023-05-07 14:48:06 +08:00
239144a446 feat: 支持调整程序内存中暂存的显示器配置。 2023-05-07 14:32:31 +08:00
3a430716d6 feat: 支持读取显示器配置。 2023-05-07 09:56:00 +08:00
800c0d3fc4 feat: 支持列出显示器。 2023-05-07 01:18:48 +08:00
091bcf33da feat: 支持收取来自板子要求的显示器亮度和电脑音量。 2023-05-06 20:14:31 +08:00
9b863508e4 build: update deps. 2023-05-04 23:31:39 +08:00
174840403f pref: 调整发送数据的逻辑,改善丢包问题。 2023-05-04 21:56:56 +08:00
ca9a2ba34d feat: skip send colors for disconnected board. 2023-04-30 22:48:25 +08:00
82d4adfe0f feat: 增强连接状态。 2023-04-30 22:30:24 +08:00
6c90a5e655 feat: 支持获取和查看板子连接的情况。 2023-04-30 18:44:26 +08:00
11045f27d8 feat: 通过新的 udp 逻辑发送灯带颜色。 2023-04-29 18:07:21 +08:00
f6e3257670 feat: 前端显示 mdns 搜索到的板子连接信息。 2023-04-29 15:09:45 +08:00
e5527ce3c3 feat: mdns search. 2023-04-29 12:40:34 +08:00
3deb14823d chore: 改为单独 task 推送灯条颜色。 2023-04-28 21:24:46 +08:00
7a87748cf1 feat: 使用 UDP 发送颜色。 2023-04-28 00:26:49 +08:00
9d11abfa6e chore: ignore .DS_Store. 2023-04-20 14:57:48 +08:00
d97eb0115f feat: 完善颜色校准 GUI。 2023-04-16 23:45:07 +08:00
effcb1e192 chore: 期望以 30 fps 捕获屏幕。 2023-04-16 23:15:26 +08:00
1c08c17fd4 feat: 支持将校准的色彩发送到 MQTT 中。 2023-04-16 21:55:24 +08:00
81d666557b chore: clean code. 2023-04-16 18:23:56 +08:00
6e6160fc0a feat: 支持将色彩校准的值写入本地配置文件。 2023-04-16 18:17:49 +08:00
fc8b3164d8 feat(GUI): 色彩调整界面。 2023-04-16 12:53:03 +08:00
932cc78bcf chore: GUI 增加路由。 2023-04-15 18:58:40 +08:00
782f3bf029 fix: wrong sample points on mac os 13. 2023-04-15 13:45:30 +08:00
09799cb2d5 fix: 修复灯带顺序控件不能很好地被控制。 2023-04-15 11:26:41 +08:00
a905c98823 fix: 更新配置时无法应用配置到灯带颜色获取逻辑。 2023-04-14 22:18:59 +08:00
9cbccedc72 fix: wrong sample points on mac os 13. 2023-04-14 21:27:14 +08:00
aa7430c54e build: update deps. 2023-04-12 23:43:41 +08:00
84 changed files with 19226 additions and 4013 deletions

158
.github/README.md vendored Normal file
View File

@ -0,0 +1,158 @@
# GitHub Actions Workflows
This directory contains GitHub Actions workflows for automated CI/CD processes.
## Workflows Overview
### 🔨 `build.yml` - Build Desktop App
**Triggers:** Push to main/develop, Pull Requests, Releases
**Purpose:** Builds the desktop application for all supported platforms (macOS, Windows, Linux)
**Features:**
- Cross-platform builds (macOS Universal, Windows x64, Linux x64)
- Automatic artifact uploads
- Release asset publishing
- Caching for faster builds
**Artifacts:**
- **macOS**: DMG installer and .app bundle
- **Windows**: MSI and NSIS installers
- **Linux**: DEB package and AppImage
### 🧪 `ci.yml` - Continuous Integration
**Triggers:** Push to main/develop, Pull Requests
**Purpose:** Code quality checks and testing
**Features:**
- Frontend build verification
- Rust formatting and linting (rustfmt, clippy)
- Rust unit tests
- Security audits for both frontend and backend dependencies
### 🚀 `release.yml` - Manual Release
**Triggers:** Manual workflow dispatch
**Purpose:** Create tagged releases with built applications
**Features:**
- Manual version input
- Pre-release option
- Automatic release notes generation
- Cross-platform builds and uploads
- Comprehensive installation instructions
**Usage:**
1. Go to Actions tab in GitHub
2. Select "Release" workflow
3. Click "Run workflow"
4. Enter version (e.g., v1.0.0)
5. Choose if it's a pre-release
6. Click "Run workflow"
### 🔄 `dependencies.yml` - Dependency Management
**Triggers:** Weekly schedule (Mondays 9 AM UTC), Manual dispatch
**Purpose:** Automated dependency updates and security monitoring
**Features:**
- Weekly dependency updates
- Automatic PR creation for updates
- Security vulnerability detection
- Automatic issue creation for security alerts
## Setup Requirements
### Repository Secrets
No additional secrets are required beyond the default `GITHUB_TOKEN`.
### Branch Protection (Recommended)
Configure branch protection rules for `main` branch:
- Require status checks to pass before merging
- Require branches to be up to date before merging
- Include status checks: `lint-and-test`, `security-audit`
### Release Process
#### Automated (Recommended)
1. Merge changes to `main` branch
2. Use the manual release workflow to create a new release
3. The workflow will automatically build and upload all platform binaries
#### Manual
1. Create a new tag: `git tag v1.0.0`
2. Push the tag: `git push origin v1.0.0`
3. Create a release on GitHub
4. The build workflow will automatically attach binaries
## Platform-Specific Notes
### macOS
- Builds universal binaries (Intel + Apple Silicon)
- Requires macOS 13.0 or later
- DMG installer includes code signing (if certificates are configured)
### Windows
- Builds for x64 architecture
- Provides both MSI and NSIS installers
- Compatible with Windows 10 and later
### Linux
- Builds for x64 architecture
- Provides DEB package for Debian/Ubuntu
- Provides AppImage for universal Linux compatibility
- Requires WebKit2GTK and other system dependencies
## Troubleshooting
### Build Failures
1. Check the specific platform logs in the Actions tab
2. Ensure all dependencies are properly declared
3. Verify Tauri configuration is correct
### Security Audit Failures
1. Review the security report in the workflow logs
2. Update vulnerable dependencies
3. Consider using `pnpm audit --fix` for frontend issues
4. Use `cargo update` for Rust dependency updates
### Cache Issues
If builds are failing due to cache corruption:
1. Go to Actions tab
2. Click on "Caches" in the sidebar
3. Delete relevant caches
4. Re-run the workflow
## Customization
### Adding New Platforms
To add support for additional platforms, modify the `matrix` section in `build.yml`:
```yaml
matrix:
include:
- platform: 'macos-latest'
args: '--target aarch64-apple-darwin'
target: 'aarch64-apple-darwin'
```
### Modifying Build Steps
Each workflow can be customized by:
1. Adding new steps
2. Modifying existing commands
3. Adding environment variables
4. Configuring different Node.js/Rust versions
### Adding Code Quality Tools (Optional)
If you want to add code quality tools in the future:
1. **ESLint**: Add ESLint configuration and dependencies for JavaScript/TypeScript linting
2. **Prettier**: Add Prettier for consistent code formatting
3. **TypeScript strict checking**: Enable stricter TypeScript rules and type checking
### Changing Schedule
Modify the `cron` expression in `dependencies.yml` to change the update frequency:
```yaml
schedule:
- cron: '0 9 * * 1' # Every Monday at 9 AM UTC
```

124
.github/workflows/build.yml vendored Normal file
View File

@ -0,0 +1,124 @@
name: Build Desktop App
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
release:
types: [ published ]
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
jobs:
build:
strategy:
fail-fast: false
matrix:
include:
- platform: 'macos-latest'
args: '--target universal-apple-darwin'
target: 'universal-apple-darwin'
- platform: 'ubuntu-22.04'
args: ''
target: 'x86_64-unknown-linux-gnu'
- platform: 'windows-latest'
args: ''
target: 'x86_64-pc-windows-msvc'
runs-on: ${{ matrix.platform }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies (Ubuntu only)
if: matrix.platform == 'ubuntu-22.04'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Rust cache
uses: swatinem/rust-cache@v2
with:
workspaces: './src-tauri -> target'
- name: Install frontend dependencies
run: pnpm install
- name: Build frontend
run: pnpm build
- name: Build Tauri app
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
args: ${{ matrix.args }}
- name: Upload artifacts (macOS)
if: matrix.platform == 'macos-latest'
uses: actions/upload-artifact@v4
with:
name: macos-app
path: |
src-tauri/target/universal-apple-darwin/release/bundle/dmg/*.dmg
src-tauri/target/universal-apple-darwin/release/bundle/macos/*.app
- name: Upload artifacts (Linux)
if: matrix.platform == 'ubuntu-22.04'
uses: actions/upload-artifact@v4
with:
name: linux-app
path: |
src-tauri/target/release/bundle/deb/*.deb
src-tauri/target/release/bundle/appimage/*.AppImage
- name: Upload artifacts (Windows)
if: matrix.platform == 'windows-latest'
uses: actions/upload-artifact@v4
with:
name: windows-app
path: |
src-tauri/target/release/bundle/msi/*.msi
src-tauri/target/release/bundle/nsis/*.exe
release:
if: github.event_name == 'release'
needs: build
runs-on: ubuntu-latest
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
- name: Display structure of downloaded files
run: ls -la
- name: Upload release assets
uses: softprops/action-gh-release@v1
with:
files: |
macos-app/**/*
linux-app/**/*
windows-app/**/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

99
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,99 @@
name: CI
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
env:
CARGO_TERM_COLOR: always
jobs:
lint-and-test:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Rust cache
uses: swatinem/rust-cache@v2
with:
workspaces: './src-tauri -> target'
- name: Install frontend dependencies
run: pnpm install
- name: Check Rust formatting
run: cargo fmt --all --check
working-directory: src-tauri
- name: Lint Rust code
run: cargo clippy --all-targets --all-features -- -D warnings
working-directory: src-tauri
- name: Run Rust tests
run: cargo test --all-features
working-directory: src-tauri
- name: Build frontend
run: pnpm build
- name: Check Tauri build
run: cargo check --all-targets --all-features
working-directory: src-tauri
security-audit:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Install cargo-audit
run: cargo install cargo-audit
- name: Run security audit
run: cargo audit
working-directory: src-tauri
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Install frontend dependencies
run: pnpm install
- name: Run npm audit
run: pnpm audit --audit-level moderate

126
.github/workflows/dependencies.yml vendored Normal file
View File

@ -0,0 +1,126 @@
name: Update Dependencies
on:
schedule:
# Run every Monday at 9:00 AM UTC
- cron: '0 9 * * 1'
workflow_dispatch:
jobs:
update-dependencies:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Install cargo-edit
run: cargo install cargo-edit
- name: Update frontend dependencies
run: |
pnpm update --latest
pnpm install
- name: Update Rust dependencies
run: |
cargo update
working-directory: src-tauri
- name: Check if build still works
run: |
pnpm build
cargo check --all-targets --all-features
working-directory: src-tauri
- name: Create Pull Request
uses: peter-evans/create-pull-request@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: 'chore: update dependencies'
title: 'chore: update dependencies'
body: |
## Automated Dependency Update
This PR updates all dependencies to their latest versions.
### Changes
- Updated frontend dependencies via `pnpm update --latest`
- Updated Rust dependencies via `cargo update`
### Testing
- ✅ Frontend build passes
- ✅ Rust compilation check passes
Please review the changes and run full tests before merging.
branch: chore/update-dependencies
delete-branch: true
security-updates:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Install cargo-audit
run: cargo install cargo-audit
- name: Check for security vulnerabilities
run: |
echo "## Frontend Security Audit" >> security-report.md
pnpm audit --audit-level moderate >> security-report.md || true
echo "## Rust Security Audit" >> security-report.md
cd src-tauri
cargo audit >> ../security-report.md || true
- name: Create security issue if vulnerabilities found
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const report = fs.readFileSync('security-report.md', 'utf8');
if (report.includes('vulnerabilities') || report.includes('RUSTSEC')) {
github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: '🔒 Security vulnerabilities detected',
body: `## Security Audit Report\n\n\`\`\`\n${report}\n\`\`\`\n\nPlease review and update the affected dependencies.`,
labels: ['security', 'dependencies']
});
}

140
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,140 @@
name: Release
on:
workflow_dispatch:
inputs:
version:
description: 'Release version (e.g., v1.0.0)'
required: true
type: string
prerelease:
description: 'Mark as pre-release'
required: false
type: boolean
default: false
env:
CARGO_TERM_COLOR: always
jobs:
create-release:
runs-on: ubuntu-latest
outputs:
release_id: ${{ steps.create_release.outputs.id }}
upload_url: ${{ steps.create_release.outputs.upload_url }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.event.inputs.version }}
release_name: Release ${{ github.event.inputs.version }}
draft: false
prerelease: ${{ github.event.inputs.prerelease }}
body: |
## Changes in this Release
- Auto-generated release for version ${{ github.event.inputs.version }}
## Downloads
Choose the appropriate installer for your operating system:
### macOS
- **DMG**: Universal binary for Intel and Apple Silicon Macs
### Windows
- **MSI**: Windows Installer package
- **EXE**: NSIS installer
### Linux
- **DEB**: Debian/Ubuntu package
- **AppImage**: Portable application
## Installation Notes
### macOS
1. Download the DMG file
2. Open the DMG and drag the app to Applications folder
3. On first launch, you may need to right-click and select "Open" due to Gatekeeper
### Windows
1. Download the MSI or EXE installer
2. Run the installer as administrator
3. Follow the installation wizard
### Linux
1. **DEB**: `sudo dpkg -i ambient-light-desktop_*.deb`
2. **AppImage**: Make executable and run directly
## System Requirements
- **macOS**: 13.0 or later
- **Windows**: Windows 10 or later
- **Linux**: Ubuntu 22.04 or equivalent
build-and-upload:
needs: create-release
strategy:
fail-fast: false
matrix:
include:
- platform: 'macos-latest'
args: '--target universal-apple-darwin'
target: 'universal-apple-darwin'
- platform: 'ubuntu-22.04'
args: ''
target: 'x86_64-unknown-linux-gnu'
- platform: 'windows-latest'
args: ''
target: 'x86_64-pc-windows-msvc'
runs-on: ${{ matrix.platform }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies (Ubuntu only)
if: matrix.platform == 'ubuntu-22.04'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Rust cache
uses: swatinem/rust-cache@v2
with:
workspaces: './src-tauri -> target'
- name: Install frontend dependencies
run: pnpm install
- name: Build and release
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
releaseId: ${{ needs.create-release.outputs.release_id }}
args: ${{ matrix.args }}

37
.gitignore vendored
View File

@ -1,2 +1,39 @@
node_modules
dist
.DS_Store
# IDE
.vscode/settings.json
.idea/
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# ESLint cache
.eslintcache
# Prettier cache
.prettiercache
# Build artifacts
src-tauri/target/
src-tauri/Cargo.lock
# OS generated files
Thumbs.db
ehthumbs.db
Desktop.ini

View File

@ -1,7 +0,0 @@
node_modules
.DS_Store
dist
dist-ssr
*.local
node_modules/*
src-tauri

View File

@ -1,8 +0,0 @@
module.exports = {
semi: true,
trailingComma: "all",
singleQuote: true,
printWidth: 90,
tabWidth: 2,
endOfLine: "auto",
};

View File

@ -2,6 +2,10 @@
"files.autoSave": "onWindowChange",
"cSpell.words": [
"Itertools",
"Leds"
]
"Leds",
"unlisten"
],
"idf.customExtraVars": {
"OPENOCD_SCRIPTS": "/Users/ivan/.espressif/tools/openocd-esp32/v0.11.0-esp32-20211220/openocd-esp32/share/openocd/scripts"
}
}

24
.vscode/tasks.json vendored
View File

@ -3,15 +3,26 @@
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "dev",
"type": "shell",
"isBackground": true,
"command": "pnpm",
"args": [
"tauri",
"dev"
],
"options": {
"env": {
"RUST_LOG": "info"
}
}
},
{
"label": "ui:dev",
"type": "shell",
// `dev` keeps running in the background
// ideally you should also configure a `problemMatcher`
// see https://code.visualstudio.com/docs/editor/tasks#_can-a-background-task-be-used-as-a-prelaunchtask-in-launchjson
"isBackground": true,
// change this to your `beforeDevCommand`:
"command": "yarn",
"command": "pnpm",
"args": [
"dev"
]
@ -19,8 +30,7 @@
{
"label": "ui:build",
"type": "shell",
// change this to your `beforeBuildCommand`:
"command": "yarn",
"command": "pnpm",
"args": [
"build"
]

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

194
README.md
View File

@ -1,7 +1,193 @@
# Tauri + Solid + Typescript
# Display Ambient Light Desktop App
This template should help get you started developing with Tauri, Solid and Typescript in Vite.
[![Build](https://github.com/USERNAME/REPOSITORY/workflows/Build%20Desktop%20App/badge.svg)](https://github.com/USERNAME/REPOSITORY/actions/workflows/build.yml)
[![CI](https://github.com/USERNAME/REPOSITORY/workflows/CI/badge.svg)](https://github.com/USERNAME/REPOSITORY/actions/workflows/ci.yml)
[![Release](https://github.com/USERNAME/REPOSITORY/workflows/Release/badge.svg)](https://github.com/USERNAME/REPOSITORY/actions/workflows/release.yml)
## Recommended IDE Setup
A desktop application built with Tauri 2.0 for ambient light control, supporting multi-monitor screen sampling and LED strip control to create immersive ambient lighting effects.
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
## ✨ Features
- 🖥️ **Multi-Monitor Support** - Automatic detection and configuration of multiple displays
- 🎨 **Real-time Screen Sampling** - High-performance screen content capture and color analysis
- 💡 **LED Strip Control** - Configurable LED strip layout and mapping support
- ⚖️ **White Balance Calibration** - Built-in white balance adjustment tool with fullscreen mode
- 🎛️ **Intuitive Configuration Interface** - Modern UI with drag-and-drop configuration support
- 🔧 **Hardware Integration** - Display brightness control and audio device management
- 📡 **Network Communication** - UDP and WebSocket communication support
## 🛠️ Tech Stack
### Frontend
- **Framework**: [Solid.js](https://solidjs.com/) - High-performance reactive UI framework
- **Build Tool**: [Vite](https://vitejs.dev/) - Fast frontend build tool
- **Styling**: [Tailwind CSS](https://tailwindcss.com/) + [DaisyUI](https://daisyui.com/) - Modern UI component library
- **Routing**: [@solidjs/router](https://github.com/solidjs/solid-router) - Client-side routing
- **Language**: TypeScript - Type-safe JavaScript
### Backend
- **Framework**: [Tauri 2.0](https://tauri.app/) - Cross-platform desktop app framework
- **Language**: Rust - High-performance systems programming language
- **Screen Capture**: [screen-capture-kit](https://crates.io/crates/screen-capture-kit) - macOS native screen capture
- **Display Control**: [ddc-hi](https://crates.io/crates/ddc-hi) - DDC/CI display control
- **Audio**: [coreaudio-rs](https://crates.io/crates/coreaudio-rs) - macOS audio system integration
- **Networking**: tokio + tokio-tungstenite - Async network communication
## 📋 System Requirements
- **Operating System**: macOS 13.0+ (primary supported platform)
- **Memory**: 4GB+ recommended
- **Graphics**: Hardware-accelerated graphics card
- **Network**: For device discovery and communication
## 🚀 Quick Start
### Prerequisites
1. **Install Rust**
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env
```
2. **Install Node.js and pnpm**
```bash
# Install Node.js 22 LTS (recommended using nvm)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 22
nvm use 22
# Install pnpm 10+
npm install -g pnpm@latest
```
3. **Install Tauri CLI**
```bash
cargo install @tauri-apps/cli@next
```
### Development Setup
1. **Clone the project**
```bash
git clone <repository-url>
cd display-ambient-light/desktop
```
2. **Install dependencies**
```bash
pnpm install
```
3. **Start development server**
```bash
pnpm tauri dev
```
### Production Build
```bash
# Build the application
pnpm tauri build
# Build artifacts are located in src-tauri/target/release/bundle/
```
## 📱 Application Interface
### Main Pages
1. **System Info** (`/info`) - Display system and hardware information
2. **Display Info** (`/displays`) - Monitor status and configuration
3. **LED Strip Configuration** (`/led-strips-configuration`) - LED strip layout and mapping configuration
4. **White Balance** (`/white-balance`) - Color calibration and white balance adjustment
### Core Features
- **Real-time Screen Preview** - WebSocket streaming of screen content
- **LED Mapping Configuration** - Visual configuration of LED strip positions and quantities
- **Color Calibration** - RGB adjustment panel with fullscreen comparison mode
- **Device Management** - Automatic discovery and management of LED control devices
## 🔧 Configuration Files
Application configuration is stored in the user directory:
```text
~/Library/Application Support/cc.ivanli.ambient-light.desktop/
├── config.toml # Main configuration file
├── led_strips.json # LED strip configuration
└── color_calibration.json # Color calibration data
```
## 🎯 Development Guide
### Project Structure
```text
desktop/
├── src/ # Frontend source code (Solid.js)
│ ├── components/ # UI components
│ ├── stores/ # State management
│ ├── models/ # Data models
│ └── contexts/ # React Context
├── src-tauri/ # Backend source code (Rust)
│ ├── src/
│ │ ├── ambient_light/ # Ambient light control
│ │ ├── display/ # Display management
│ │ ├── rpc/ # Network communication
│ │ └── screenshot/ # Screen capture
│ └── tauri.conf.json # Tauri configuration
└── package.json # Frontend dependencies
```
### Development Workflow
1. **Frontend Development**: Modify files under `src/`, supports hot reload
2. **Backend Development**: Modify files under `src-tauri/src/`, requires dev server restart
3. **Configuration Changes**: Restart required after modifying `tauri.conf.json`
### Debugging Tips
- Use browser developer tools to debug frontend
- Use `console.log` and Rust's `println!` for debugging
- Check Tauri console output for backend logs
## 🤝 Contributing
1. Fork the project
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## 📄 License
This project is licensed under the GPLv3 License - see the [LICENSE](LICENSE) file for details.
## 🔗 Related Links
- [Tauri Official Documentation](https://tauri.app/)
- [Solid.js Official Documentation](https://solidjs.com/)
- [Rust Official Documentation](https://doc.rust-lang.org/)
- [Tailwind CSS Documentation](https://tailwindcss.com/docs)
## 📞 Support
If you encounter issues or have suggestions, please:
- Create an [Issue](../../issues)
- Check the [Wiki](../../wiki) for more information
- Contact the developer
---
**Note**: This application is primarily optimized for macOS platform, support for other platforms may be limited.

16
debug_displays.rs Normal file
View File

@ -0,0 +1,16 @@
use display_info;
fn main() {
match display_info::DisplayInfo::all() {
Ok(displays) => {
println!("Found {} displays:", displays.len());
for (index, display) in displays.iter().enumerate() {
println!(" Display {}: ID={}, Scale={}, Width={}, Height={}",
index, display.id, display.scale_factor, display.width, display.height);
}
}
Err(e) => {
println!("Error getting display info: {}", e);
}
}
}

View File

@ -0,0 +1,99 @@
# LED Strip Test Device Auto-Refresh Implementation
## Overview
Implemented automatic refresh functionality for the device dropdown in the LED strip test interface. The device list now updates in real-time when devices are discovered, connected, or disconnected.
## Changes Made
### 1. Frontend Changes (`src/components/led-strip-test/led-strip-test.tsx`)
#### Added Event Listener Import
```typescript
import { listen } from '@tauri-apps/api/event';
```
#### Enhanced Device Loading Logic
- **Initial Load**: Still loads devices on component mount using `get_boards()`
- **Real-time Updates**: Added listener for `boards_changed` events from backend
- **Smart Selection**: Automatically handles device selection when devices are added/removed:
- If current device disconnects, automatically selects first available device
- If no device was selected and devices become available, selects the first one
- Properly cleans up event listeners on component unmount
#### Improved UI Display
- **Device Count**: Shows number of devices found in label
- **Connection Status**: Each device option shows:
- Status icon (🟢 Connected, 🟡 Connecting, 🔴 Disconnected)
- Device name and address
- Connection status text
- **Empty State**: Shows "Searching..." when no devices found
#### Type Safety Improvements
- Updated `BoardInfo` interface to match backend types
- Proper handling of `connect_status` union type
- Type-safe status checking functions
### 2. Backend Integration
The implementation leverages existing backend infrastructure:
- **UdpRpc Manager**: Continuously searches for devices via mDNS
- **Device Monitoring**: Checks device connectivity every second
- **Event Broadcasting**: Sends `boards_changed` events to frontend
- **Status Tracking**: Maintains real-time connection status for each device
## Technical Details
### Event Flow
1. Backend `UdpRpc` discovers devices via mDNS service discovery
2. Backend monitors device connectivity with periodic health checks
3. Backend broadcasts `boards_changed` events when device list changes
4. Frontend listens for events and updates UI automatically
5. Frontend handles device selection logic intelligently
### Connection Status Types
- `Connected`: Device is responding to ping requests
- `Connecting`: Device is in retry state (with retry count)
- `Disconnected`: Device is not responding
### Error Handling
- Graceful fallback if initial device load fails
- Proper cleanup of event listeners
- Maintains UI state consistency during device changes
## Benefits
1. **Real-time Updates**: No need to manually refresh device list
2. **Better UX**: Visual indicators for device status
3. **Automatic Recovery**: Handles device disconnections gracefully
4. **Type Safety**: Proper TypeScript types prevent runtime errors
5. **Performance**: Efficient event-driven updates instead of polling
## Implementation Status
**Completed**: LED Strip Test device dropdown auto-refresh
**Already Implemented**: Board Index page auto-refresh (was already working)
**Type Safety**: Fixed TypeScript type definitions for BoardInfo
**UI Improvements**: Added status indicators and device count display
## Testing
To test the functionality:
1. Start the application with `npm run tauri dev`
2. Navigate to LED Strip Test page
3. Observe device list updates as devices come online/offline
4. Verify status indicators show correct connection states:
- 🟢 Connected devices
- 🟡 Connecting devices (with retry count)
- 🔴 Disconnected devices
5. Test device selection behavior when devices disconnect
6. Check that device count is displayed in the label
## Code Quality
- ✅ No TypeScript errors
- ✅ Proper event listener cleanup
- ✅ Type-safe status checking
- ✅ Consistent with existing codebase patterns
- ✅ Follows SolidJS best practices
## Future Enhancements
- Add device refresh button for manual refresh
- Show device discovery progress indicator
- Add device connection retry controls
- Display device ping latency information
- Add device connection history/logs

View File

@ -0,0 +1,105 @@
# Device Auto-Refresh Testing Guide
## Test Scenarios
### 1. Initial Load Test
**Expected Behavior**: Device list loads automatically when component mounts
**Steps**:
1. Start the application: `npm run tauri dev`
2. Navigate to LED Strip Test page
3. Observe the device dropdown
**Expected Results**:
- Device dropdown shows "Searching..." if no devices found
- Device dropdown shows device count if devices are found
- First available device is automatically selected
- Status icons appear next to device names
### 2. Device Discovery Test
**Expected Behavior**: New devices appear automatically when discovered
**Steps**:
1. Start with no devices connected
2. Connect a device to the network
3. Wait for device discovery (should be automatic)
**Expected Results**:
- Device count updates automatically
- New device appears in dropdown
- If no device was selected, new device gets selected automatically
- Status icon shows connection state
### 3. Device Disconnection Test
**Expected Behavior**: Disconnected devices are handled gracefully
**Steps**:
1. Start with connected devices
2. Select a device in the dropdown
3. Disconnect the selected device from network
4. Wait for connection timeout
**Expected Results**:
- Device status changes to disconnected (🔴)
- If device becomes unavailable, another device is selected automatically
- Device count updates
- UI remains responsive
### 4. Connection Status Test
**Expected Behavior**: Status indicators reflect actual device states
**Steps**:
1. Observe devices in different connection states
2. Check status icons and text
**Expected Results**:
- 🟢 "Connected" for responsive devices
- 🟡 "Connecting" for devices in retry state
- 🔴 "Disconnected" for unresponsive devices
- Status text matches icon state
### 5. UI Responsiveness Test
**Expected Behavior**: Interface remains responsive during device changes
**Steps**:
1. Rapidly connect/disconnect devices
2. Interact with other UI elements during device changes
3. Switch between pages and return
**Expected Results**:
- No UI freezing or lag
- Event listeners are properly cleaned up
- No memory leaks
- Smooth transitions
## Verification Checklist
- [ ] Device dropdown shows correct device count
- [ ] Status icons display correctly (🟢🟡🔴)
- [ ] Automatic device selection works
- [ ] Event listeners are cleaned up on component unmount
- [ ] No TypeScript errors in console
- [ ] No runtime errors in console
- [ ] Performance remains good with multiple devices
- [ ] UI updates smoothly without flickering
## Common Issues to Watch For
1. **Memory Leaks**: Event listeners not cleaned up
2. **Type Errors**: Incorrect BoardInfo type handling
3. **Selection Logic**: Device selection not updating correctly
4. **Performance**: UI lag during rapid device changes
5. **State Consistency**: UI state not matching actual device state
## Debug Information
Check browser console for:
- `boards_changed` events
- Device list updates
- Selection changes
- Any error messages
Check Tauri logs for:
- Device discovery messages
- Connection status changes
- mDNS service events

471
docs/hardware-protocol.md Normal file
View File

@ -0,0 +1,471 @@
# LED Hardware Communication Protocol
## Overview
UDP-based bidirectional protocol for communication between desktop application and ambient light hardware boards. The protocol supports LED color data transmission, device health monitoring, and remote control capabilities.
## Connection
- **Protocol**: UDP
- **Port**: 23042
- **Discovery**: mDNS (`_ambient_light._udp.local.`)
- **Example Board**: `192.168.31.206:23042`
## mDNS Service Discovery
### Service Registration (Hardware Side)
Hardware boards must register the following mDNS service:
- **Service Type**: `_ambient_light._udp.local.`
- **Port**: 23042
- **TXT Records**: Optional, can include device information
### Service Discovery (Desktop Side)
Desktop application continuously browses for `_ambient_light._udp.local.` services and automatically connects to discovered devices.
## Protocol Messages
The protocol uses different message headers to distinguish message types:
| Header | Direction | Purpose | Format |
|--------|-----------|---------|---------|
| 0x01 | Desktop → Hardware | Ping (Health Check) | `[0x01]` |
| 0x01 | Hardware → Desktop | Pong (Health Response) | `[0x01]` |
| 0x02 | Desktop → Hardware | LED Color Data | `[0x02][Offset_H][Offset_L][Color_Data...]` |
| 0x03 | Hardware → Desktop | Display Brightness Control | `[0x03][Display_Index][Brightness]` |
| 0x04 | Hardware → Desktop | Volume Control | `[0x04][Volume_Percent]` |
## Health Check Protocol (Ping/Pong)
### Desktop → Hardware (Ping)
```text
Byte 0: Header (0x01)
```
### Hardware → Desktop (Pong)
```text
Byte 0: Header (0x01)
```
**Behavior:**
- Desktop sends ping every 1 second to each connected device
- Hardware must respond with pong within 1 second
- Timeout or incorrect response triggers reconnection logic
- After 10 failed attempts, device is marked as disconnected
## LED Color Data Protocol
### Packet Format
```text
Byte 0: Header (0x02)
Byte 1: Offset High (upper 8 bits of data byte offset)
Byte 2: Offset Low (lower 8 bits of data byte offset)
Byte 3+: LED Color Data (variable length)
```
## LED Color Data
### RGB LEDs (3 bytes per LED)
```text
[R][G][B][R][G][B][R][G][B]...
```
### RGBW LEDs (4 bytes per LED)
```text
[R][G][B][W][R][G][B][W][R][G][B][W]...
```
All values are 0-255.
### Offset Calculation
The offset field specifies the starting byte position in the LED data buffer:
- **16-bit value**: Combines Offset High and Offset Low bytes (big-endian)
- **Range**: 0-65535 bytes supported
- **Purpose**: Allows partial updates of LED strip data at any byte position
**Example Calculations:**
- Byte position 0: `Offset High = 0x00, Offset Low = 0x00`
- Byte position 30: `Offset High = 0x00, Offset Low = 0x1E` (10 RGB LEDs × 3 bytes)
- Byte position 256: `Offset High = 0x01, Offset Low = 0x00`
- Byte position 1000: `Offset High = 0x03, Offset Low = 0xE8`
**LED Position to Byte Offset Conversion:**
- **RGB LEDs**: `byte_offset = led_position × 3`
- **RGBW LEDs**: `byte_offset = led_position × 4`
## LED Chip Specifications
### WS2812B (RGB)
- **Type**: RGB
- **Data Format**: 3 bytes per LED
- **Color Order**: G-R-B (Green, Red, Blue)
- **Voltage**: 5V
- **Protocol**: Single-wire serial
- **Timing**: 800kHz data rate
### SK6812 (RGB)
- **Type**: RGB
- **Data Format**: 3 bytes per LED
- **Color Order**: G-R-B (Green, Red, Blue)
- **Voltage**: 5V
- **Protocol**: Single-wire serial
- **Timing**: 800kHz data rate
- **Features**: Improved PWM linearity compared to WS2812B
### SK6812-RGBW
- **Type**: RGBW
- **Data Format**: 4 bytes per LED
- **Color Order**: G-R-B-W (Green, Red, Blue, White)
- **Voltage**: 5V
- **Protocol**: Single-wire serial
- **Timing**: 800kHz data rate
- **Features**: Dedicated white channel for better color mixing and higher brightness
## Color Calibration
Colors are calibrated before transmission:
**RGB:**
```rust
calibrated_r = (original_r * calibration_r) / 255
calibrated_g = (original_g * calibration_g) / 255
calibrated_b = (original_b * calibration_b) / 255
```
**RGBW:**
```rust
calibrated_r = (original_r * calibration_r) / 255
calibrated_g = (original_g * calibration_g) / 255
calibrated_b = (original_b * calibration_b) / 255
calibrated_w = calibration_w // Direct value
```
## Hardware Control Protocol (Hardware → Desktop)
### Display Brightness Control
Hardware can send display brightness adjustment commands to the desktop:
```text
Byte 0: Header (0x03)
Byte 1: Display Index (0-based display number)
Byte 2: Brightness (0-255, where 255 = 100% brightness)
```
**Example:** Set display 0 to 50% brightness
```text
03 00 80
│ │ └─ Brightness (128 = ~50%)
│ └─ Display Index (0)
└─ Header (0x03)
```
### Volume Control
Hardware can send system volume adjustment commands to the desktop:
```text
Byte 0: Header (0x04)
Byte 1: Volume Percent (0-100)
```
**Example:** Set system volume to 75%
```text
04 4B
│ └─ Volume (75%)
└─ Header (0x04)
```
## Connection State Management
### Connection States
- **Unknown**: Initial state when device is first discovered
- **Connecting**: Device is being tested, includes retry count (1-10)
- **Connected**: Device is responding to ping requests normally
- **Disconnected**: Device failed to respond after 10 retry attempts
### State Transitions
```text
Unknown → Connecting(1) → Connected
↓ ↓ ↓
↓ Connecting(2-10) ↓
↓ ↓ ↓
└─→ Disconnected ←────────┘
```
### Retry Logic
1. **Initial Connection**: When device discovered via mDNS
2. **Health Check Failure**: If ping timeout or wrong response
3. **Retry Attempts**: Up to 10 attempts with 1-second intervals
4. **Disconnection**: After 10 failed attempts, mark as disconnected
5. **Recovery**: Disconnected devices continue to receive ping attempts
## Packet Examples
### RGB Example
3 RGB LEDs starting at byte offset 0: Red, Green, Blue
```text
02 00 00 FF 00 00 00 FF 00 00 00 FF
│ │ │ └─────────────────────────── 9 bytes color data
│ │ └─ Offset Low (0 bytes)
│ └─ Offset High (0)
└─ Header (0x02)
```
### RGBW Example
2 RGBW LEDs starting at byte offset 40 (LED position 10): White, Warm White
```text
02 00 28 FF FF FF FF FF C8 96 C8
│ │ │ └─────────────────────── 8 bytes color data
│ │ └─ Offset Low (40 bytes = 0x28)
│ └─ Offset High (0)
└─ Header (0x02)
```
## Implementation Notes
- **Byte Order**: Big-endian for multi-byte values (offset field)
- **Delivery**: Fire-and-forget UDP (no acknowledgment required)
- **Hardware Role**: Simple UDP-to-LED bridge, no data processing
- **LED Type Logic**: Handled entirely on desktop side, not hardware
- **Mixed Types**: Same display can have both RGB and RGBW strips
- **Data Flow**: Desktop → UDP → Hardware → LED Strip (direct forward)
- **Color Order**: Hardware must handle color order conversion for different LED chips
- **LED Compatibility**: Supports WS2812B, SK6812, and SK6812-RGBW chips
## Hardware Implementation
The hardware board handles multiple protocol functions: UDP-to-WS2812 bridge for LED data, health monitoring, and optional control input capabilities.
### Required Functions
1. **mDNS Service Registration**: Advertise `_ambient_light._udp.local.` service
2. **UDP Server**: Listen on port 23042 for incoming packets
3. **Packet Processing**: Handle different message types based on header
4. **Health Monitoring**: Respond to ping requests with pong
5. **LED Control**: Forward color data to WS2812 strips
6. **Optional Control**: Send brightness/volume commands to desktop
### Packet Processing Logic
```c
void process_packet(uint8_t* data, size_t len) {
if (len < 1) return;
switch (data[0]) {
case 0x01: // Ping request
handle_ping(data, len);
break;
case 0x02: // LED color data
handle_led_data(data, len);
break;
default:
// Unknown packet type, ignore
break;
}
}
void handle_ping(uint8_t* data, size_t len) {
if (len != 1) return;
// Respond with pong
uint8_t pong = 0x01;
udp_send_response(&pong, 1);
}
void handle_led_data(uint8_t* data, size_t len) {
if (len < 3) return;
uint16_t byte_offset = (data[1] << 8) | data[2];
uint8_t* color_data = &data[3];
size_t color_len = len - 3;
// Direct forward to LED strip - supports WS2812B, SK6812, SK6812-RGBW
// byte_offset specifies the starting byte position in LED data buffer
// Color order conversion handled by LED driver library
led_strip_update(byte_offset, color_data, color_len);
}
```
### Optional Control Features
Hardware can optionally send control commands to desktop:
```c
// Send display brightness control
void send_brightness_control(uint8_t display_index, uint8_t brightness) {
uint8_t packet[3] = {0x03, display_index, brightness};
udp_send_to_desktop(packet, 3);
}
// Send volume control
void send_volume_control(uint8_t volume_percent) {
uint8_t packet[2] = {0x04, volume_percent};
udp_send_to_desktop(packet, 2);
}
```
### LED Strip Driver Implementation
For SK6812-RGBW support, hardware must handle the G-R-B-W color order:
```c
// Example LED strip update function for SK6812-RGBW
void led_strip_update(uint16_t offset, uint8_t* data, size_t len) {
// For SK6812-RGBW: data comes as [R][G][B][W] from desktop
// Must be reordered to [G][R][B][W] for the LED chip
size_t led_count = len / 4; // 4 bytes per RGBW LED
uint8_t* output_buffer = malloc(len);
for (size_t i = 0; i < led_count; i++) {
uint8_t r = data[i * 4 + 0];
uint8_t g = data[i * 4 + 1];
uint8_t b = data[i * 4 + 2];
uint8_t w = data[i * 4 + 3];
// Reorder to G-R-B-W for SK6812-RGBW
output_buffer[i * 4 + 0] = g; // Green first
output_buffer[i * 4 + 1] = r; // Red second
output_buffer[i * 4 + 2] = b; // Blue third
output_buffer[i * 4 + 3] = w; // White fourth
}
// Send to LED strip with proper timing
sk6812_rgbw_send(offset, output_buffer, len);
free(output_buffer);
}
```
### Key Implementation Notes
- **Ping Response**: Must respond to ping (0x01) within 1 second
- **LED Data**: Direct forward to LED strip, with color order conversion if needed
- **Color Order**: SK6812-RGBW requires G-R-B-W order, desktop sends R-G-B-W
- **Control Commands**: Optional feature for hardware with input capabilities
- **mDNS Registration**: Essential for automatic device discovery
- **UDP Server**: Must handle concurrent connections from multiple desktops
- **LED Chip Support**: Must support WS2812B (RGB), SK6812 (RGB), and SK6812-RGBW
## Troubleshooting
### Device Discovery Issues
**Device Not Found**:
- Verify mDNS service registration on hardware
- Check service type: `_ambient_light._udp.local.`
- Ensure port 23042 is accessible
- Verify network connectivity between desktop and hardware
**Device Shows as Disconnected**:
- Check ping/pong response implementation
- Verify hardware responds to 0x01 packets within 1 second
- Monitor network latency and packet loss
- Check UDP server implementation on hardware
### LED Control Issues
**No LED Updates**:
- Verify hardware processes 0x02 packets correctly
- Check WS2812 wiring and power supply
- Monitor packet reception on hardware side
- Verify byte offset calculations and LED strip configuration
**Wrong Colors**:
- Check color calibration settings on desktop
- Verify RGB/RGBW data format matches LED strip type
- Monitor color data in packets (bytes 3+)
- Check LED chip color order:
- WS2812B: G-R-B order
- SK6812: G-R-B order
- SK6812-RGBW: G-R-B-W order
- Ensure hardware converts R-G-B(-W) from desktop to correct chip order
**Flickering or Lag**:
- Monitor packet rate and network congestion
- Check power supply stability for LED strips
- Verify WS2812 data signal integrity
- Consider reducing update frequency
### Control Protocol Issues
**Brightness/Volume Control Not Working**:
- Verify hardware sends correct packet format (0x03/0x04)
- Check desktop receives and processes control packets
- Monitor packet transmission from hardware
- Verify display index and value ranges
### Connection State Issues
**Frequent Disconnections**:
- Check network stability and latency
- Verify ping response timing (< 1 second)
- Monitor retry logic and connection state transitions
- Check for UDP packet loss
**Stuck in Connecting State**:
- Verify ping/pong packet format
- Check hardware UDP server implementation
- Monitor ping response timing
- Verify network firewall settings
### Network Debugging
**Packet Monitoring**:
```bash
# Monitor UDP traffic on port 23042
tcpdump -i any -X port 23042
# Check mDNS service discovery
dns-sd -B _ambient_light._udp.local.
```
**Hardware Debug Output**:
- Log received packet headers and lengths
- Monitor ping/pong timing
- Track LED data processing
- Log mDNS service registration status
## Protocol Version
- **Current**: 1.0
- **Headers**: 0x01 (Ping/Pong), 0x02 (LED Data), 0x03 (Brightness), 0x04 (Volume)
- **Future**: Additional headers for new features, backward compatibility maintained

View File

@ -1,7 +1,26 @@
{
"name": "test-demo",
"version": "0.0.0",
"description": "",
"name": "display-ambient-light",
"version": "2.0.0-alpha",
"description": "A desktop application for controlling ambient lighting based on screen content, supporting WS2812B and SK6812 LED strips with real-time color synchronization.",
"author": "Ivan Li",
"homepage": "https://github.com/IvanLi-CN/display-ambient-light",
"repository": {
"type": "git",
"url": "https://github.com/IvanLi-CN/display-ambient-light.git"
},
"keywords": [
"ambient-light",
"led-control",
"screen-sync",
"ws2812b",
"sk6812",
"tauri",
"desktop-app"
],
"engines": {
"node": ">=22.0.0",
"pnpm": ">=10.0.0"
},
"scripts": {
"start": "vite",
"dev": "vite",
@ -11,19 +30,27 @@
},
"license": "MIT",
"dependencies": {
"@tauri-apps/api": "^1.2.0",
"solid-js": "^1.4.7",
"@solid-primitives/i18n": "^2.2.1",
"@solidjs/router": "^0.8.4",
"@tauri-apps/api": "^2.6.0",
"debug": "^4.4.1",
"solid-icons": "^1.1.0",
"solid-js": "^1.9.7",
"solid-tippy": "^0.2.1",
"tippy.js": "^6.3.7"
},
"devDependencies": {
"@tauri-apps/cli": "^1.2.2",
"@types/node": "^18.7.10",
"autoprefixer": "^10.4.14",
"postcss": "^8.4.21",
"tailwindcss": "^3.2.7",
"typescript": "^4.7.4",
"vite": "^4.0.0",
"vite-plugin-solid": "^2.3.0"
"@tailwindcss/postcss": "^4.1.11",
"@tailwindcss/vite": "^4.1.11",
"@tauri-apps/cli": "^2.6.2",
"@types/debug": "^4.1.12",
"@types/node": "^24.0.7",
"autoprefixer": "^10.4.21",
"daisyui": "^5.0.43",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.11",
"typescript": "^4.9.5",
"vite": "^6.3.5",
"vite-plugin-solid": "^2.11.7"
}
}

2713
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,5 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

4741
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,25 +1,29 @@
[package]
name = "test-demo"
version = "0.0.0"
description = "A Tauri App"
authors = ["you"]
license = ""
repository = ""
name = "ambient-light-control"
version = "2.0.0-alpha"
description = "A desktop application for controlling ambient lighting based on screen content"
authors = ["Ivan Li"]
license = "MIT"
repository = "https://github.com/ivan/display-ambient-light"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.2", features = [] }
tauri-build = { version = "2.0", features = [] }
[dependencies]
tauri = { version = "1.2", features = ["shell-open"] }
tauri = { version = "2.0", features = ["tray-icon"] }
tauri-plugin-shell = "2.0"
serde = { version = "1.0", features = ["derive"] }
dirs = "5.0"
regex = "1.0"
serde_json = "1.0"
core-graphics = "0.22.3"
display-info = "0.4.1"
anyhow = "1.0.69"
tokio = {version = "1.26.0", features = ["full"] }
tokio-util = "0.7"
paris = { version = "1.5", features = ["timestamps", "macros"] }
log = "0.4.17"
env_logger = "0.10.0"
@ -28,10 +32,20 @@ url-build-parse = "9.0.0"
color_space = "0.5.3"
hex = "0.4.3"
toml = "0.7.3"
paho-mqtt = "0.12.1"
time = {version="0.3.20", features= ["formatting"] }
# paho-mqtt = "0.12.1" # Temporarily disabled due to CMake issues
time = {version="0.3.35", features= ["formatting"] }
itertools = "0.10.5"
core-foundation = "0.9.3"
tokio-stream = "0.1.14"
mdns-sd = "0.7.2"
futures = "0.3.28"
ddc-hi = "0.4.1"
coreaudio-rs = "0.11.2"
screen-capture-kit = "0.3.1"
image = { version = "0.24", features = ["jpeg"] }
tokio-tungstenite = "0.20"
futures-util = "0.3"
sha1 = "0.10"
[features]
# this feature is used for production builds or when `devPath` points to the filesystem

View File

@ -0,0 +1,12 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main application window",
"windows": ["main"],
"permissions": [
"core:default",
"shell:allow-open",
"core:window:allow-set-fullscreen",
"core:window:allow-is-fullscreen"
]
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1 @@
{"default":{"identifier":"default","description":"Capability for the main application window","local":true,"windows":["main"],"permissions":["core:default","shell:allow-open","core:window:allow-set-fullscreen","core:window:allow-is-fullscreen"]}}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,9 +3,8 @@ use std::env::current_dir;
use display_info::DisplayInfo;
use paris::{error, info};
use serde::{Deserialize, Serialize};
use tauri::api::path::config_dir;
use crate::screenshot::{self, LedSamplePoints};
use crate::screenshot::LedSamplePoints;
const CONFIG_FILE_NAME: &str = "cc.ivanli.ambient_light/led_strip_config.toml";
@ -17,6 +16,18 @@ pub enum Border {
Right,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug, PartialEq)]
pub enum LedType {
WS2812B,
SK6812,
}
impl Default for LedType {
fn default() -> Self {
LedType::WS2812B
}
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct LedStripConfig {
pub index: usize,
@ -24,12 +35,47 @@ pub struct LedStripConfig {
pub display_id: u32,
pub start_pos: usize,
pub len: usize,
#[serde(default)]
pub led_type: LedType,
}
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct ColorCalibration {
r: f32,
g: f32,
b: f32,
#[serde(default = "default_w_value")]
w: f32,
}
fn default_w_value() -> f32 {
1.0
}
impl ColorCalibration {
pub fn to_bytes(&self) -> [u8; 3] {
[
(self.r * 255.0) as u8,
(self.g * 255.0) as u8,
(self.b * 255.0) as u8,
]
}
pub fn to_bytes_rgbw(&self) -> [u8; 4] {
[
(self.r * 255.0) as u8,
(self.g * 255.0) as u8,
(self.b * 255.0) as u8,
(self.w * 255.0) as u8,
]
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LedStripConfigGroup {
pub strips: Vec<LedStripConfig>,
pub mappers: Vec<SamplePointMapper>,
pub color_calibration: ColorCalibration,
}
impl LedStripConfigGroup {
@ -37,7 +83,7 @@ impl LedStripConfigGroup {
let displays = DisplayInfo::all()?;
// config path
let path = config_dir()
let path = dirs::config_dir()
.unwrap_or(current_dir().unwrap())
.join(CONFIG_FILE_NAME);
@ -65,7 +111,7 @@ impl LedStripConfigGroup {
}
pub async fn write_config(configs: &Self) -> anyhow::Result<()> {
let path = config_dir()
let path = dirs::config_dir()
.unwrap_or(current_dir().unwrap())
.join(CONFIG_FILE_NAME);
@ -105,6 +151,7 @@ impl LedStripConfigGroup {
},
start_pos: j + i * 4 * 30,
len: 30,
led_type: LedType::WS2812B,
};
configs.push(item);
strips.push(item);
@ -115,7 +162,18 @@ impl LedStripConfigGroup {
})
}
}
Ok(Self { strips, mappers })
let color_calibration = ColorCalibration {
r: 1.0,
g: 1.0,
b: 1.0,
w: 1.0,
};
Ok(Self {
strips,
mappers,
color_calibration,
})
}
}

View File

@ -1,15 +1,14 @@
use std::{borrow::BorrowMut, sync::Arc};
use tauri::async_runtime::RwLock;
use tokio::sync::OnceCell;
use tokio::{sync::OnceCell, task::yield_now};
use crate::ambient_light::{config, LedStripConfigGroup};
use super::{Border, SamplePointMapper};
use super::{Border, SamplePointMapper, ColorCalibration, LedType};
pub struct ConfigManager {
config: Arc<RwLock<LedStripConfigGroup>>,
config_update_receiver: tokio::sync::watch::Receiver<LedStripConfigGroup>,
config_update_sender: tokio::sync::watch::Sender<LedStripConfigGroup>,
}
@ -22,10 +21,12 @@ impl ConfigManager {
let (config_update_sender, config_update_receiver) =
tokio::sync::watch::channel(configs.clone());
config_update_sender.send(configs.clone()).unwrap();
if let Err(err) = config_update_sender.send(configs.clone()) {
log::error!("Failed to send config update when read config first time: {}", err);
}
drop(config_update_receiver);
ConfigManager {
config: Arc::new(RwLock::new(configs)),
config_update_receiver,
config_update_sender,
}
})
@ -46,8 +47,9 @@ impl ConfigManager {
self.config_update_sender
.send(configs.clone())
.map_err(|e| anyhow::anyhow!("Failed to send config update: {}", e))?;
yield_now().await;
// log::info!("config updated: {:?}", configs);
log::debug!("config updated: {:?}", configs);
Ok(())
}
@ -92,6 +94,33 @@ impl ConfigManager {
Ok(())
}
pub async fn patch_led_strip_type(
&self,
display_id: u32,
border: Border,
led_type: LedType,
) -> anyhow::Result<()> {
let mut config = self.config.write().await;
for strip in config.strips.iter_mut() {
if strip.display_id == display_id && strip.border == border {
strip.led_type = led_type;
}
}
let cloned_config = config.clone();
drop(config);
self.update(&cloned_config).await?;
self.config_update_sender
.send(cloned_config)
.map_err(|e| anyhow::anyhow!("Failed to send config update: {}", e))?;
Ok(())
}
pub async fn move_strip_part(
&self,
display_id: u32,
@ -221,6 +250,17 @@ impl ConfigManager {
pub fn clone_config_update_receiver(
&self,
) -> tokio::sync::watch::Receiver<LedStripConfigGroup> {
self.config_update_receiver.clone()
self.config_update_sender.subscribe()
}
pub async fn set_color_calibration(&self, color_calibration: ColorCalibration) -> anyhow::Result<()> {
let config = self.config.write().await;
let mut cloned_config = config.clone();
cloned_config.color_calibration = color_calibration;
drop(config);
self.update(&cloned_config).await
}
}

View File

@ -1,31 +1,32 @@
use std::{collections::HashMap, sync::Arc, time::Duration};
use std::{borrow::Borrow, collections::HashMap, sync::Arc, time::Duration};
use paris::warn;
use tauri::async_runtime::RwLock;
use tokio::{
net::UdpSocket,
sync::{broadcast, watch},
time::sleep,
};
use crate::{
ambient_light::{config, ConfigManager},
rpc::MqttRpc,
screenshot::LedSamplePoints,
led_color::LedColor,
rpc::UdpRpc,
screenshot::{self, LedSamplePoints},
screenshot_manager::{self, ScreenshotManager},
};
use itertools::Itertools;
use super::{LedStripConfigGroup, SamplePointConfig, SamplePointMapper};
use super::{LedStripConfigGroup, SamplePointMapper, LedStripConfig, ColorCalibration, LedType};
pub struct LedColorsPublisher {
sorted_colors_rx: Arc<RwLock<watch::Receiver<Vec<u8>>>>,
sorted_colors_tx: Arc<RwLock<watch::Sender<Vec<u8>>>>,
colors_rx: Arc<RwLock<watch::Receiver<Vec<u8>>>>,
colors_tx: Arc<RwLock<watch::Sender<Vec<u8>>>>,
display_colors_rx: Arc<RwLock<broadcast::Receiver<(u32, Vec<u8>)>>>,
display_colors_tx: Arc<RwLock<broadcast::Sender<(u32, Vec<u8>)>>>,
inner_tasks_version: Arc<RwLock<usize>>,
test_mode_active: Arc<RwLock<bool>>,
}
impl LedColorsPublisher {
@ -35,7 +36,6 @@ impl LedColorsPublisher {
let (sorted_tx, sorted_rx) = watch::channel(Vec::new());
let (tx, rx) = watch::channel(Vec::new());
let (display_colors_tx, display_colors_rx) = broadcast::channel(8);
LED_COLORS_PUBLISHER_GLOBAL
.get_or_init(|| async {
@ -44,67 +44,65 @@ impl LedColorsPublisher {
sorted_colors_tx: Arc::new(RwLock::new(sorted_tx)),
colors_rx: Arc::new(RwLock::new(rx)),
colors_tx: Arc::new(RwLock::new(tx)),
display_colors_rx: Arc::new(RwLock::new(display_colors_rx)),
display_colors_tx: Arc::new(RwLock::new(display_colors_tx)),
inner_tasks_version: Arc::new(RwLock::new(0)),
test_mode_active: Arc::new(RwLock::new(false)),
}
})
.await
}
fn start_one_display_colors_fetcher(
async fn start_one_display_colors_fetcher(
&self,
display_id: u32,
sample_points: Vec<Vec<LedSamplePoints>>,
sample_points: Vec<LedSamplePoints>,
bound_scale_factor: f32,
mappers: Vec<SamplePointMapper>,
display_colors_tx: broadcast::Sender<(u32, Vec<u8>)>,
strips: Vec<LedStripConfig>,
color_calibration: ColorCalibration,
) {
let display_colors_tx = self.display_colors_tx.clone();
let internal_tasks_version = self.inner_tasks_version.clone();
let screenshot_manager = ScreenshotManager::global().await;
tokio::spawn(async move {
let display_colors_tx = display_colors_tx.read().await.clone();
let screenshot_rx = screenshot_manager.subscribe_by_display_id(display_id).await;
let colors = screenshot_manager::get_display_colors(display_id, &sample_points);
if let Err(err) = colors {
warn!("Failed to get colors: {}", err);
if let Err(err) = screenshot_rx {
log::error!("{}", err);
return;
}
let mut screenshot_rx = screenshot_rx.unwrap();
let mut start: tokio::time::Instant = tokio::time::Instant::now();
let mut interval = tokio::time::interval(Duration::from_millis(66));
tokio::spawn(async move {
let init_version = internal_tasks_version.read().await.clone();
loop {
interval.tick().await;
tokio::time::sleep(Duration::from_millis(1)).await;
while screenshot_rx.changed().await.is_ok() {
let screenshot = screenshot_rx.borrow().clone();
let colors = screenshot.get_colors_by_sample_points(&sample_points).await;
if internal_tasks_version.read().await.clone() != init_version {
log::info!(
"inner task version changed, stop. {} != {}",
internal_tasks_version.read().await.clone(),
init_version
);
let colors_copy = colors.clone();
break;
let mappers = mappers.clone();
// Check if test mode is active before sending normal colors
let test_mode_active = {
let publisher = LedColorsPublisher::global().await;
*publisher.test_mode_active.read().await
};
if !test_mode_active {
match Self::send_colors_by_display(colors, mappers, &strips, &color_calibration).await {
Ok(_) => {
// log::info!("sent colors: #{: >15}", display_id);
}
Err(err) => {
warn!("Failed to send colors: #{: >15}\t{}", display_id, err);
}
}
// log::info!("tick: {}ms", start.elapsed().as_millis());
start = tokio::time::Instant::now();
let colors = screenshot_manager::get_display_colors(display_id, &sample_points);
if let Err(err) = colors {
warn!("Failed to get colors: {}", err);
sleep(Duration::from_millis(100)).await;
continue;
}
let colors = colors.unwrap();
let color_len = colors.len();
match display_colors_tx.send((
display_id,
colors
colors_copy
.into_iter()
.map(|color| color.get_rgb())
.flatten()
@ -117,34 +115,48 @@ impl LedColorsPublisher {
warn!("Failed to send display_colors: {}", err);
}
};
// Check if the inner task version changed
let version = internal_tasks_version.read().await.clone();
if version != init_version {
log::info!(
"inner task version changed, stop. {} != {}",
internal_tasks_version.read().await.clone(),
init_version
);
break;
}
}
});
}
fn start_all_colors_worker(&self, display_ids: Vec<u32>, mappers: Vec<SamplePointMapper>) {
fn start_all_colors_worker(
&self,
display_ids: Vec<u32>,
mappers: Vec<SamplePointMapper>,
mut display_colors_rx: broadcast::Receiver<(u32, Vec<u8>)>,
) {
let sorted_colors_tx = self.sorted_colors_tx.clone();
let colors_tx = self.colors_tx.clone();
let display_colors_rx = self.display_colors_rx.clone();
tokio::spawn(async move {
for _ in 0..10 {
let mut rx = display_colors_rx.read().await.resubscribe();
let sorted_colors_tx = sorted_colors_tx.write().await;
let colors_tx = colors_tx.write().await;
let mut all_colors: Vec<Option<Vec<u8>>> = vec![None; display_ids.len()];
let mut start: tokio::time::Instant = tokio::time::Instant::now();
log::info!("start all_colors_worker");
loop {
// log::info!("display_colors_rx changed");
let color_info = rx.recv().await;
let color_info = display_colors_rx.recv().await;
if let Err(err) = color_info {
match err {
broadcast::error::RecvError::Closed => {
break;
return;
}
broadcast::error::RecvError::Lagged(_) => {
warn!("display_colors_rx lagged");
@ -186,7 +198,7 @@ impl LedColorsPublisher {
warn!("Failed to send sorted colors: {}", err);
}
};
log::info!("tick: {}ms", start.elapsed().as_millis());
start = tokio::time::Instant::now();
}
}
@ -194,170 +206,242 @@ impl LedColorsPublisher {
});
}
pub fn start(&self) {
let inner_tasks_version = self.inner_tasks_version.clone();
pub async fn start(&self) {
tokio::spawn(async move {
let publisher = Self::global().await;
let mut inner_tasks_version = inner_tasks_version.write().await;
*inner_tasks_version = inner_tasks_version.overflowing_add(1).0;
let config_manager = ConfigManager::global().await;
let mut config_receiver = config_manager.clone_config_update_receiver();
let configs = config_receiver.borrow().clone();
log::info!("waiting for config update...");
self.handle_config_change(configs).await;
while config_receiver.changed().await.is_ok() {
log::info!("config updated, restart inner tasks...");
let configs = config_receiver.borrow().clone();
let configs = Self::get_colors_configs(&configs).await;
self.handle_config_change(configs).await;
}
}
async fn handle_config_change(&self, original_configs: LedStripConfigGroup) {
let inner_tasks_version = self.inner_tasks_version.clone();
let configs = Self::get_colors_configs(&original_configs).await;
if let Err(err) = configs {
warn!("Failed to get configs: {}", err);
sleep(Duration::from_millis(100)).await;
continue;
return;
}
let configs = configs.unwrap();
let mut inner_tasks_version = inner_tasks_version.write().await;
*inner_tasks_version = inner_tasks_version.overflowing_add(1).0;
drop(inner_tasks_version);
let (display_colors_tx, display_colors_rx) = broadcast::channel::<(u32, Vec<u8>)>(8);
for sample_point_group in configs.sample_point_groups.clone() {
let display_id = sample_point_group.display_id;
let sample_points = sample_point_group.points;
let bound_scale_factor = sample_point_group.bound_scale_factor;
publisher.start_one_display_colors_fetcher(display_id, sample_points);
// Get strips for this display
let display_strips: Vec<LedStripConfig> = original_configs.strips
.iter()
.filter(|strip| strip.display_id == display_id)
.cloned()
.collect();
self.start_one_display_colors_fetcher(
display_id,
sample_points,
bound_scale_factor,
sample_point_group.mappers,
display_colors_tx.clone(),
display_strips,
original_configs.color_calibration,
)
.await;
}
let display_ids = configs.sample_point_groups;
publisher.start_all_colors_worker(
self.start_all_colors_worker(
display_ids.iter().map(|c| c.display_id).collect(),
configs.mappers,
display_colors_rx,
);
break;
}
});
// tokio::spawn(async move {
// loop {
// let sorted_colors_tx = sorted_colors_tx.write().await;
// let colors_tx = colors_tx.write().await;
// let screenshot_manager = ScreenshotManager::global().await;
// let config_manager = ConfigManager::global().await;
// let config_receiver = config_manager.clone_config_update_receiver();
// let configs = config_receiver.borrow().clone();
// let configs = Self::get_colors_configs(&configs).await;
// if let Err(err) = configs {
// warn!("Failed to get configs: {}", err);
// sleep(Duration::from_millis(100)).await;
// continue;
// }
// let configs = configs.unwrap();
// let mut merged_screenshot_receiver =
// screenshot_manager.clone_merged_screenshot_rx().await;
// let mut screenshots = HashMap::new();
// // let mut start = tokio::time::Instant::now();
// loop {
// let screenshot = merged_screenshot_receiver.recv().await;
// if let Err(err) = screenshot {
// match err {
// tokio::sync::broadcast::error::RecvError::Closed => {
// warn!("closed");
// continue;
// }
// tokio::sync::broadcast::error::RecvError::Lagged(_) => {
// warn!("lagged");
// continue;
// }
// }
// }
// let screenshot = screenshot.unwrap();
// // log::info!("got screenshot: {:?}", screenshot.display_id);
// screenshots.insert(screenshot.display_id, screenshot);
// if screenshots.len() == configs.sample_point_groups.len() {
// // log::info!("{}", start.elapsed().as_millis().to_string());
// {
// let screenshots = configs
// .sample_point_groups
// .iter()
// .map(|strip| screenshots.get(&strip.display_id).unwrap())
// .collect::<Vec<_>>();
// let colors = screenshot_manager
// .get_all_colors(&configs.sample_point_groups, &screenshots)
// .await;
// let sorted_colors =
// ScreenshotManager::get_sorted_colors(&colors, &configs.mappers)
// .await;
// match colors_tx.send(colors) {
// Ok(_) => {
// // log::info!("colors updated");
// }
// Err(_) => {
// warn!("colors update failed");
// }
// }
// match sorted_colors_tx.send(sorted_colors) {
// Ok(_) => {
// // log::info!("colors updated");
// }
// Err(_) => {
// warn!("colors update failed");
// }
// }
// }
// // screenshots.clear();
// // start = tokio::time::Instant::now();
// }
// }
// }
// });
let rx = self.sorted_colors_rx.clone();
tokio::spawn(async move {
let mut rx = rx.read().await.clone();
loop {
if let Err(err) = rx.changed().await {
warn!("rx changed error: {}", err);
sleep(Duration::from_millis(1000)).await;
continue;
}
let colors = rx.borrow().clone();
pub async fn send_colors(offset: u16, mut payload: Vec<u8>) -> anyhow::Result<()> {
// let mqtt = MqttRpc::global().await;
let len = colors.len();
// mqtt.publish_led_sub_pixels(payload).await;
match Self::send_colors(colors).await {
Ok(_) => {
// log::info!("colors sent. len: {}", len);
let socket = UdpSocket::bind("0.0.0.0:8000").await?;
let mut buffer = vec![2];
buffer.push((offset >> 8) as u8);
buffer.push((offset & 0xff) as u8);
buffer.append(&mut payload);
socket.send_to(&buffer, "192.168.31.206:23042").await?;
Ok(())
}
Err(err) => {
warn!("colors send failed: {}", err);
pub async fn send_colors_by_display(
colors: Vec<LedColor>,
mappers: Vec<SamplePointMapper>,
strips: &[LedStripConfig],
color_calibration: &ColorCalibration,
) -> anyhow::Result<()> {
// let color_len = colors.len();
let display_led_offset = mappers
.clone()
.iter()
.flat_map(|mapper| [mapper.start, mapper.end])
.min()
.unwrap();
let udp_rpc = UdpRpc::global().await;
if let Err(err) = udp_rpc {
warn!("udp_rpc can not be initialized: {}", err);
}
let udp_rpc = udp_rpc.as_ref().unwrap();
// let socket = UdpSocket::bind("0.0.0.0:0").await?;
for (group_index, group) in mappers.clone().iter().enumerate() {
if (group.start.abs_diff(group.end)) > colors.len() {
return Err(anyhow::anyhow!(
"get_sorted_colors: color_index out of range. color_index: {}, strip len: {}, colors.len(): {}",
group.pos,
group.start.abs_diff(group.end),
colors.len()
));
}
let group_size = group.start.abs_diff(group.end);
// Find the corresponding LED strip config to get LED type
let led_type = if group_index < strips.len() {
strips[group_index].led_type
} else {
LedType::WS2812B // fallback to WS2812B
};
let bytes_per_led = match led_type {
LedType::WS2812B => 3,
LedType::SK6812 => 4,
};
let mut buffer = Vec::<u8>::with_capacity(group_size * bytes_per_led);
if group.end > group.start {
// Prevent integer underflow by using saturating subtraction
let start_index = if group.pos >= display_led_offset {
group.pos - display_led_offset
} else {
0
};
let end_index = if group.pos + group_size >= display_led_offset {
group_size + group.pos - display_led_offset
} else {
0
};
for i in start_index..end_index {
if i < colors.len() {
let bytes = match led_type {
LedType::WS2812B => {
let calibration_bytes = color_calibration.to_bytes();
let color_bytes = colors[i].as_bytes();
// Apply calibration to RGB values
vec![
((color_bytes[0] as f32 * calibration_bytes[0] as f32 / 255.0) as u8),
((color_bytes[1] as f32 * calibration_bytes[1] as f32 / 255.0) as u8),
((color_bytes[2] as f32 * calibration_bytes[2] as f32 / 255.0) as u8),
]
}
LedType::SK6812 => {
let calibration_bytes = color_calibration.to_bytes_rgbw();
let color_bytes = colors[i].as_bytes();
// Apply calibration to RGB values and use calibrated W
vec![
((color_bytes[0] as f32 * calibration_bytes[0] as f32 / 255.0) as u8),
((color_bytes[1] as f32 * calibration_bytes[1] as f32 / 255.0) as u8),
((color_bytes[2] as f32 * calibration_bytes[2] as f32 / 255.0) as u8),
calibration_bytes[3], // W channel
]
}
};
buffer.extend_from_slice(&bytes);
} else {
log::warn!("Index {} out of bounds for colors array of length {}", i, colors.len());
// Add black color as fallback
match led_type {
LedType::WS2812B => buffer.extend_from_slice(&[0, 0, 0]),
LedType::SK6812 => buffer.extend_from_slice(&[0, 0, 0, 0]),
}
}
}
} else {
// Prevent integer underflow by using saturating subtraction
let start_index = if group.pos >= display_led_offset {
group.pos - display_led_offset
} else {
0
};
let end_index = if group.pos + group_size >= display_led_offset {
group_size + group.pos - display_led_offset
} else {
0
};
for i in (start_index..end_index).rev() {
if i < colors.len() {
let bytes = match led_type {
LedType::WS2812B => {
let calibration_bytes = color_calibration.to_bytes();
let color_bytes = colors[i].as_bytes();
// Apply calibration to RGB values
vec![
((color_bytes[0] as f32 * calibration_bytes[0] as f32 / 255.0) as u8),
((color_bytes[1] as f32 * calibration_bytes[1] as f32 / 255.0) as u8),
((color_bytes[2] as f32 * calibration_bytes[2] as f32 / 255.0) as u8),
]
}
LedType::SK6812 => {
let calibration_bytes = color_calibration.to_bytes_rgbw();
let color_bytes = colors[i].as_bytes();
// Apply calibration to RGB values and use calibrated W
vec![
((color_bytes[0] as f32 * calibration_bytes[0] as f32 / 255.0) as u8),
((color_bytes[1] as f32 * calibration_bytes[1] as f32 / 255.0) as u8),
((color_bytes[2] as f32 * calibration_bytes[2] as f32 / 255.0) as u8),
calibration_bytes[3], // W channel
]
}
};
buffer.extend_from_slice(&bytes);
} else {
log::warn!("Index {} out of bounds for colors array of length {}", i, colors.len());
// Add black color as fallback
match led_type {
LedType::WS2812B => buffer.extend_from_slice(&[0, 0, 0]),
LedType::SK6812 => buffer.extend_from_slice(&[0, 0, 0, 0]),
}
}
}
});
}
pub async fn send_colors(payload: Vec<u8>) -> anyhow::Result<()> {
let mqtt = MqttRpc::global().await;
// Calculate byte offset based on LED position and LED type
let led_offset = group.start.min(group.end);
let byte_offset = led_offset * bytes_per_led;
let mut tx_buffer = vec![2];
tx_buffer.push((byte_offset >> 8) as u8);
tx_buffer.push((byte_offset & 0xff) as u8);
tx_buffer.append(&mut buffer);
mqtt.publish_led_sub_pixels(payload).await
udp_rpc.send_to_all(&tx_buffer).await?;
}
Ok(())
}
pub async fn clone_sorted_colors_receiver(&self) -> watch::Receiver<Vec<u8>> {
@ -380,11 +464,12 @@ impl LedColorsPublisher {
let mut colors_configs = Vec::new();
let mut merged_screenshot_receiver = screenshot_manager.clone_merged_screenshot_rx().await;
merged_screenshot_receiver.resubscribe();
let mut screenshots = HashMap::new();
loop {
log::info!("waiting merged screenshot...");
let screenshot = merged_screenshot_receiver.recv().await;
if let Err(err) = screenshot {
@ -406,35 +491,51 @@ impl LedColorsPublisher {
screenshots.insert(screenshot.display_id, screenshot);
if screenshots.len() == display_ids.len() {
let mut led_start = 0;
for display_id in display_ids {
let led_strip_configs: Vec<_> = configs
let led_strip_configs = configs
.strips
.iter()
.filter(|c| c.display_id == display_id)
.enumerate()
.filter(|(_, c)| c.display_id == display_id);
let screenshot = screenshots.get(&display_id).unwrap();
let points: Vec<_> = led_strip_configs
.clone()
.map(|(_, config)| screenshot.get_sample_points(&config))
.flatten()
.collect();
if led_strip_configs.len() == 0 {
if points.len() == 0 {
warn!("no led strip config for display_id: {}", display_id);
continue;
}
let screenshot = screenshots.get(&display_id).unwrap();
log::debug!("screenshot updated: {:?}", display_id);
let bound_scale_factor = screenshot.bound_scale_factor;
let points: Vec<_> = led_strip_configs
.iter()
.map(|config| screenshot.get_sample_points(&config))
.collect();
let led_end = led_start + points.iter().map(|p| p.len()).sum::<usize>();
let colors_config = DisplaySamplePointGroup { display_id, points };
let mappers = led_strip_configs.map(|(i, _)| mappers[i].clone()).collect();
let colors_config = DisplaySamplePointGroup {
display_id,
points,
bound_scale_factor,
mappers,
};
colors_configs.push(colors_config);
led_start = led_end;
}
return Ok(AllColorConfig {
sample_point_groups: colors_configs,
mappers,
// screenshot_receivers: local_rx_list,
});
}
}
@ -443,6 +544,35 @@ impl LedColorsPublisher {
pub async fn clone_colors_receiver(&self) -> watch::Receiver<Vec<u8>> {
self.colors_rx.read().await.clone()
}
/// Enable test mode - this will pause normal LED data publishing
pub async fn enable_test_mode(&self) {
let mut test_mode = self.test_mode_active.write().await;
*test_mode = true;
log::info!("Test mode enabled - normal LED publishing paused");
}
/// Disable test mode - this will resume normal LED data publishing
pub async fn disable_test_mode(&self) {
let mut test_mode = self.test_mode_active.write().await;
*test_mode = false;
log::info!("Test mode disabled - normal LED publishing resumed");
}
/// Disable test mode with a delay to ensure clean transition
pub async fn disable_test_mode_with_delay(&self, delay_ms: u64) {
// Wait for the specified delay
tokio::time::sleep(tokio::time::Duration::from_millis(delay_ms)).await;
let mut test_mode = self.test_mode_active.write().await;
*test_mode = false;
log::info!("Test mode disabled with delay - normal LED publishing resumed");
}
/// Check if test mode is currently active
pub async fn is_test_mode_active(&self) -> bool {
*self.test_mode_active.read().await
}
}
#[derive(Debug)]
@ -455,5 +585,7 @@ pub struct AllColorConfig {
#[derive(Debug, Clone)]
pub struct DisplaySamplePointGroup {
pub display_id: u32,
pub points: Vec<Vec<LedSamplePoints>>,
pub points: Vec<LedSamplePoints>,
pub bound_scale_factor: f32,
pub mappers: Vec<config::SamplePointMapper>,
}

View File

@ -0,0 +1,117 @@
use std::{sync::Arc, time::SystemTime};
use ddc_hi::{Ddc, Display};
use tokio::sync::RwLock;
use super::DisplayState;
// Safe wrapper for Display that implements Send + Sync
pub struct SafeDisplay {
display: Display,
}
unsafe impl Send for SafeDisplay {}
unsafe impl Sync for SafeDisplay {}
impl SafeDisplay {
pub fn new(display: Display) -> Self {
Self { display }
}
pub fn get_mut(&mut self) -> &mut Display {
&mut self.display
}
}
pub struct DisplayHandler {
pub state: Arc<RwLock<DisplayState>>,
pub controller: Arc<RwLock<SafeDisplay>>,
}
impl DisplayHandler {
pub async fn fetch_state(&self) {
let mut controller = self.controller.write().await;
let mut temp_state = self.state.read().await.clone();
match controller.get_mut().handle.get_vcp_feature(0x10) {
Ok(value) => {
temp_state.max_brightness = value.maximum();
temp_state.min_brightness = 0;
temp_state.brightness = value.value();
}
Err(_) => {}
};
match controller.get_mut().handle.get_vcp_feature(0x12) {
Ok(value) => {
temp_state.max_contrast = value.maximum();
temp_state.min_contrast = 0;
temp_state.contrast = value.value();
}
Err(_) => {}
};
match controller.get_mut().handle.get_vcp_feature(0xdc) {
Ok(value) => {
temp_state.max_mode = value.maximum();
temp_state.min_mode = 0;
temp_state.mode = value.value();
}
Err(_) => {}
};
temp_state.last_fetched_at = SystemTime::now();
let mut state = self.state.write().await;
*state = temp_state;
}
pub async fn set_brightness(&self, brightness: u16) -> anyhow::Result<()> {
let mut controller = self.controller.write().await;
let mut state = self.state.write().await;
controller
.get_mut()
.handle
.set_vcp_feature(0x10, brightness)
.map_err(|err| anyhow::anyhow!("can not set brightness. {:?}", err))?;
state.brightness = brightness;
state.last_modified_at = SystemTime::now();
Ok(())
}
pub async fn set_contrast(&self, contrast: u16) -> anyhow::Result<()> {
let mut controller = self.controller.write().await;
let mut state = self.state.write().await;
controller
.get_mut()
.handle
.set_vcp_feature(0x12, contrast)
.map_err(|err| anyhow::anyhow!("can not set contrast. {:?}", err))?;
state.contrast = contrast;
state.last_modified_at = SystemTime::now();
Ok(())
}
pub async fn set_mode(&self, mode: u16) -> anyhow::Result<()> {
let mut controller = self.controller.write().await;
let mut state = self.state.write().await;
controller
.get_mut()
.handle
.set_vcp_feature(0xdc, mode)
.map_err(|err| anyhow::anyhow!("can not set mode. {:?}", err))?;
state.mode = mode;
state.last_modified_at = SystemTime::now();
Ok(())
}
}

View File

@ -3,8 +3,7 @@ use std::time::SystemTime;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct DisplayConfig {
pub id: usize,
pub struct DisplayState {
pub brightness: u16,
pub max_brightness: u16,
pub min_brightness: u16,
@ -15,22 +14,35 @@ pub struct DisplayConfig {
pub max_mode: u16,
pub min_mode: u16,
pub last_modified_at: SystemTime,
pub last_fetched_at: SystemTime,
}
impl DisplayConfig {
pub fn default(index: usize) -> Self {
impl DisplayState {
pub fn default() -> Self {
Self {
id: index,
brightness: 30,
contrast: 50,
mode: 0,
last_modified_at: SystemTime::now(),
last_modified_at: SystemTime::UNIX_EPOCH,
max_brightness: 100,
min_brightness: 0,
max_contrast: 100,
min_contrast: 0,
max_mode: 15,
min_mode: 0,
last_fetched_at: SystemTime::UNIX_EPOCH,
}
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DisplayStateWrapper {
pub version: u8,
pub states: Vec<DisplayState>,
}
impl DisplayStateWrapper {
pub fn new(states: Vec<DisplayState>) -> Self {
Self { version: 1, states }
}
}

View File

@ -1,187 +1,283 @@
use std::{
borrow::Borrow,
collections::HashMap,
ops::Sub,
sync::Arc,
time::{Duration, SystemTime},
};
use std::{env::current_dir, sync::Arc, time::Duration};
use base64::Config;
use ddc_hi::Display;
use paris::{error, info, warn};
use tauri::async_runtime::Mutex;
use tokio::sync::{broadcast, OwnedMutexGuard};
use tracing::warn;
use crate::{display::Brightness, models, rpc};
use super::{display_config::DisplayConfig, DisplayBrightness};
use ddc_hi::Ddc;
pub struct Manager {
displays: Arc<Mutex<HashMap<usize, Arc<Mutex<DisplayConfig>>>>>,
}
impl Manager {
pub fn global() -> &'static Self {
static DISPLAY_MANAGER: once_cell::sync::OnceCell<Manager> =
once_cell::sync::OnceCell::new();
DISPLAY_MANAGER.get_or_init(|| Self::create())
}
pub fn create() -> Self {
let instance = Self {
displays: Arc::new(Mutex::new(HashMap::new())),
use dirs::config_dir;
use tokio::{
sync::{broadcast, watch, OnceCell, RwLock},
task::yield_now,
};
use crate::{
display::DisplayStateWrapper,
rpc::{BoardMessageChannels, DisplaySetting},
};
use super::{display_handler::{DisplayHandler, SafeDisplay}, display_state::DisplayState};
const CONFIG_FILE_NAME: &str = "cc.ivanli.ambient_light/displays.toml";
pub struct DisplayManager {
displays: Arc<RwLock<Vec<Arc<RwLock<DisplayHandler>>>>>,
setting_request_handler: Option<tokio::task::JoinHandle<()>>,
displays_changed_sender: Arc<watch::Sender<Vec<DisplayState>>>,
auto_save_state_handler: Option<tokio::task::JoinHandle<()>>,
}
impl DisplayManager {
pub async fn global() -> &'static Self {
static DISPLAY_MANAGER: OnceCell<DisplayManager> = OnceCell::const_new();
DISPLAY_MANAGER.get_or_init(|| Self::create()).await
}
pub async fn create() -> Self {
let (displays_changed_sender, _) = watch::channel(Vec::new());
let displays_changed_sender = Arc::new(displays_changed_sender);
let mut instance = Self {
displays: Arc::new(RwLock::new(Vec::new())),
setting_request_handler: None,
displays_changed_sender,
auto_save_state_handler: None,
};
instance.fetch_displays().await;
instance.restore_states().await;
instance.fetch_state_of_displays().await;
instance.subscribe_setting_request();
instance.auto_save_state_of_displays();
instance
}
pub async fn subscribe_display_brightness(&self) {
let rpc = rpc::Manager::global().await;
fn auto_save_state_of_displays(&mut self) {
let displays = self.displays.clone();
let mut rx = rpc.client().subscribe_change_display_brightness_rx();
let handler = tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
Self::save_states(displays.clone()).await;
Self::send_displays_changed(displays.clone()).await;
}
});
self.auto_save_state_handler = Some(handler);
}
async fn send_displays_changed(displays: Arc<RwLock<Vec<Arc<RwLock<DisplayHandler>>>>>) {
let mut states = Vec::new();
for display in displays.read().await.iter() {
let state = display.read().await.state.read().await.clone();
states.push(state);
}
let channel = BoardMessageChannels::global().await;
let tx = channel.displays_changed_sender.clone();
if let Err(err) = tx.send(states) {
error!("Failed to send displays changed: {}", err);
}
}
async fn fetch_displays(&self) {
let mut displays = self.displays.write().await;
displays.clear();
let controllers = Display::enumerate();
for display in controllers {
let safe_display = SafeDisplay::new(display);
let controller = Arc::new(RwLock::new(safe_display));
let state = Arc::new(RwLock::new(DisplayState::default()));
let handler = DisplayHandler {
state: state.clone(),
controller: controller.clone(),
};
displays.push(Arc::new(RwLock::new(handler)));
}
}
async fn fetch_state_of_displays(&self) {
let displays = self.displays.read().await;
for display in displays.iter() {
let display = display.read().await;
display.fetch_state().await;
}
}
pub async fn get_displays(&self) -> Vec<DisplayState> {
let displays = self.displays.read().await;
let mut states = Vec::new();
for display in displays.iter() {
let state = display.read().await.state.read().await.clone();
states.push(state);
}
states
}
fn subscribe_setting_request(&mut self) {
let displays = self.displays.clone();
let displays_changed_sender = self.displays_changed_sender.clone();
let handler = tokio::spawn(async move {
let channels = BoardMessageChannels::global().await;
let mut request_rx = channels.display_setting_request_sender.subscribe();
loop {
if let Ok(display_brightness) = rx.recv().await {
if let Err(err) = self.set_display_brightness(display_brightness).await {
error!("set_display_brightness failed. {:?}", err);
if let Err(err) = request_rx.recv().await {
match err {
broadcast::error::RecvError::Closed => {
info!("display setting request channel closed");
break;
}
broadcast::error::RecvError::Lagged(_) => {
warn!("display setting request channel lagged");
continue;
}
}
}
fn read_display_config_by_ddc(index: usize) -> anyhow::Result<DisplayConfig> {
let mut displays = Display::enumerate();
match displays.get_mut(index) {
Some(display) => {
let mut config = DisplayConfig::default(index);
match display.handle.get_vcp_feature(0x10) {
Ok(value) => {
config.max_brightness = value.maximum();
config.min_brightness = 0;
config.brightness = value.value();
let message = request_rx.recv().await.unwrap();
let displays = displays.write().await;
let display = displays.get(message.display_index);
if display.is_none() {
warn!("display#{} not found", message.display_index);
continue;
}
Err(_) => {}
};
match display.handle.get_vcp_feature(0x12) {
Ok(value) => {
config.max_contrast = value.maximum();
config.min_contrast = 0;
config.contrast = value.value();
}
Err(_) => {}
};
match display.handle.get_vcp_feature(0xdc) {
Ok(value) => {
config.max_mode = value.maximum();
config.min_mode = 0;
config.mode = value.value();
}
Err(_) => {}
let display = display.unwrap().write().await;
let result = match message.setting {
DisplaySetting::Brightness(value) => display.set_brightness(value as u16).await,
DisplaySetting::Contrast(value) => display.set_contrast(value as u16).await,
DisplaySetting::Mode(value) => display.set_mode(value as u16).await,
};
Ok(config)
if let Err(err) = result {
error!("failed to set display setting: {}", err);
continue;
}
None => anyhow::bail!("display#{} is missed.", index),
drop(display);
let mut states = Vec::new();
for display in displays.iter() {
let state = display.read().await.state.read().await.clone();
states.push(state);
}
if let Err(err) = displays_changed_sender.send(states) {
error!("failed to send displays changed event: {}", err);
}
yield_now().await;
}
});
self.setting_request_handler = Some(handler);
}
async fn restore_states(&self) {
let path = config_dir()
.unwrap_or(current_dir().unwrap())
.join(CONFIG_FILE_NAME);
if !path.exists() {
log::info!("config file not found: {}. skip read.", path.display());
return;
}
let text = std::fs::read_to_string(path);
if let Err(err) = text {
log::error!("failed to read config file: {}", err);
return;
}
let text = text.unwrap();
let wrapper = toml::from_str::<DisplayStateWrapper>(&text);
if let Err(err) = wrapper {
log::error!("failed to parse display states file: {}", err);
return;
}
let states = wrapper.unwrap().states;
let displays = self.displays.read().await;
for (index, display) in displays.iter().enumerate() {
let display = display.read().await;
let mut state = display.state.write().await;
let saved = states.get(index);
if let Some(saved) = saved {
state.brightness = saved.brightness;
state.contrast = saved.contrast;
state.mode = saved.mode;
log::info!("restore display config. display#{}: {:?}", index, state);
}
}
async fn get_display(&self, index: usize) -> anyhow::Result<OwnedMutexGuard<DisplayConfig>> {
let mut displays = self.displays.lock().await;
match displays.get_mut(&index) {
Some(config) => {
let mut config = config.to_owned().lock_owned().await;
if config.last_modified_at > SystemTime::now().sub(Duration::from_secs(10)) {
info!("cached");
return Ok(config);
}
return match Self::read_display_config_by_ddc(index) {
Ok(config) => {
let id = config.id;
let value = Arc::new(Mutex::new(config));
let valueGuard = value.clone().lock_owned().await;
displays.insert(id, value);
info!("read form ddc");
Ok(valueGuard)
}
Err(err) => {
warn!(
"can not read config from display by ddc, use CACHED value. {:?}",
err
log::info!(
"restore display config. store displays: {}, online displays: {}",
states.len(),
displays.len()
);
config.last_modified_at = SystemTime::now();
Ok(config)
}
};
async fn save_states(displays: Arc<RwLock<Vec<Arc<RwLock<DisplayHandler>>>>>) {
let path = config_dir()
.unwrap_or(current_dir().unwrap())
.join(CONFIG_FILE_NAME);
let displays = displays.read().await;
let mut states = Vec::new();
for display in displays.iter() {
let state = display.read().await.state.read().await.clone();
states.push(state);
}
None => {
let config = Self::read_display_config_by_ddc(index).map_err(|err| {
anyhow::anyhow!(
"can not read config from display by ddc,use DEFAULT value. {:?}",
err
)
})?;
let id = config.id;
let value = Arc::new(Mutex::new(config));
let valueGuard = value.clone().lock_owned().await;
displays.insert(id, value);
Ok(valueGuard)
let wrapper = DisplayStateWrapper::new(states);
let text = toml::to_string(&wrapper);
if let Err(err) = text {
log::error!("failed to serialize display states: {}", err);
log::error!("display states: {:?}", &wrapper);
return;
}
let text = text.unwrap();
if path.exists() {
if let Err(err) = std::fs::remove_file(&path) {
log::error!("failed to remove old config file: {}", err);
return;
}
}
pub async fn set_display_brightness(
&self,
display_brightness: DisplayBrightness,
) -> anyhow::Result<()> {
match Display::enumerate().get_mut(display_brightness.display_index) {
Some(display) => {
match self.get_display(display_brightness.display_index).await {
Ok(mut config) => {
let curr = config.brightness;
info!("curr_brightness: {:?}", curr);
let mut target = match display_brightness.brightness {
Brightness::Relative(v) => curr.wrapping_add_signed(v),
Brightness::Absolute(v) => v,
};
if target.gt(&config.max_brightness) {
target = config.max_brightness;
} else if target.lt(&config.min_brightness) {
target = config.min_brightness;
if let Err(err) = std::fs::write(&path, text) {
log::error!("failed to write config file: {}", err);
return;
}
config.brightness = target;
display
.handle
.set_vcp_feature(0x10, target as u16)
.map_err(|err| anyhow::anyhow!("can not set brightness. {:?}", err))?;
let rpc = rpc::Manager::global().await;
rpc.publish_desktop_cmd(
format!("display{}/brightness", display_brightness.display_index)
.as_str(),
target.to_be_bytes().to_vec(),
)
.await;
}
Err(err) => {
info!(
"can not get display#{} brightness. {:?}",
display_brightness.display_index, err
log::debug!(
"save display config. store displays: {}, online displays: {}",
wrapper.states.len(),
displays.len()
);
if let Brightness::Absolute(v) = display_brightness.brightness {
display.handle.set_vcp_feature(0x10, v).map_err(|err| {
anyhow::anyhow!("can not set brightness. {:?}", err)
})?;
};
}
};
}
None => {
warn!("display#{} is not found.", display_brightness.display_index);
pub fn subscribe_displays_changed(&self) -> watch::Receiver<Vec<DisplayState>> {
self.displays_changed_sender.subscribe()
}
}
Ok(())
impl Drop for DisplayManager {
fn drop(&mut self) {
log::info!("dropping display manager=============");
if let Some(handler) = self.setting_request_handler.take() {
handler.abort();
}
if let Some(handler) = self.auto_save_state_handler.take() {
handler.abort();
}
}
}

View File

@ -1,11 +1,13 @@
// mod brightness;
// mod manager;
mod display_config;
mod display_state;
mod manager;
mod display_handler;
pub use display_config::*;
pub use display_state::*;
// pub use brightness::*;
// pub use manager::*;
pub use manager::*;

View File

@ -2,45 +2,51 @@ use color_space::{Hsv, Rgb};
use serde::Serialize;
#[derive(Clone, Copy, Debug)]
pub struct LedColor {
bits: [u8; 3],
}
pub struct LedColor([u8; 3]);
impl LedColor {
pub fn default() -> Self {
Self { bits: [0, 0, 0] }
Self ([0, 0, 0] )
}
pub fn new(r: u8, g: u8, b: u8) -> Self {
Self { bits: [r, g, b] }
Self ([r, g, b])
}
pub fn from_hsv(h: f64, s: f64, v: f64) -> Self {
let rgb = Rgb::from(Hsv::new(h, s, v));
Self { bits: [rgb.r as u8, rgb.g as u8, rgb.b as u8] }
Self ([rgb.r as u8, rgb.g as u8, rgb.b as u8])
}
pub fn get_rgb(&self) -> [u8; 3] {
self.bits
self.0
}
pub fn is_empty(&self) -> bool {
self.bits.iter().any(|bit| *bit == 0)
self.0.iter().any(|bit| *bit == 0)
}
pub fn set_rgb(&mut self, r: u8, g: u8, b: u8) -> &Self {
self.bits = [r, g, b];
self.0 = [r, g, b];
self
}
pub fn merge(&mut self, r: u8, g: u8, b: u8) -> &Self {
self.bits = [
(self.bits[0] / 2 + r / 2),
(self.bits[1] / 2 + g / 2),
(self.bits[2] / 2 + b / 2),
self.0 = [
(self.0[0] / 2 + r / 2),
(self.0[1] / 2 + g / 2),
(self.0[2] / 2 + b / 2),
];
self
}
pub fn as_bytes (&self) -> [u8; 3] {
self.0
}
pub fn as_bytes_rgbw(&self, w: u8) -> [u8; 4] {
[self.0[0], self.0[1], self.0[2], w]
}
}
impl Serialize for LedColor {
@ -48,7 +54,7 @@ impl Serialize for LedColor {
where
S: serde::Serializer,
{
let hex = format!("#{}", hex::encode(self.bits));
let hex = format!("#{}", hex::encode(self.0));
serializer.serialize_str(hex.as_str())
}
}

View File

@ -0,0 +1,243 @@
use std::f64::consts::PI;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TestEffectType {
FlowingRainbow,
GroupCounting,
SingleScan,
Breathing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestEffectConfig {
pub effect_type: TestEffectType,
pub led_count: u32,
pub led_type: LedType,
pub speed: f64, // Speed multiplier
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LedType {
WS2812B,
SK6812,
}
pub struct LedTestEffects;
impl LedTestEffects {
/// Check if LED type supports white channel (RGBW)
fn is_rgbw_type(led_type: &LedType) -> bool {
matches!(led_type, LedType::SK6812)
}
/// Generate LED colors for a specific test effect at a given time
pub fn generate_colors(config: &TestEffectConfig, time_ms: u64) -> Vec<u8> {
let time_seconds = time_ms as f64 / 1000.0;
match config.effect_type {
TestEffectType::FlowingRainbow => {
Self::flowing_rainbow(config.led_count, config.led_type.clone(), time_seconds, config.speed)
}
TestEffectType::GroupCounting => {
Self::group_counting(config.led_count, config.led_type.clone())
}
TestEffectType::SingleScan => {
Self::single_scan(config.led_count, config.led_type.clone(), time_seconds, config.speed)
}
TestEffectType::Breathing => {
Self::breathing(config.led_count, config.led_type.clone(), time_seconds, config.speed)
}
}
}
/// Flowing rainbow effect - smooth rainbow colors flowing along the strip
fn flowing_rainbow(led_count: u32, led_type: LedType, time: f64, speed: f64) -> Vec<u8> {
let mut buffer = Vec::new();
let time_offset = (time * speed * 60.0) % 360.0; // 60 degrees per second at speed 1.0
for i in 0..led_count {
// Create longer wavelength for smoother color transitions
let hue = ((i as f64 * 720.0 / led_count as f64) + time_offset) % 360.0;
let rgb = Self::hsv_to_rgb(hue, 1.0, 1.0);
buffer.push(rgb.0);
buffer.push(rgb.1);
buffer.push(rgb.2);
if Self::is_rgbw_type(&led_type) {
buffer.push(0); // White channel
}
}
buffer
}
/// Group counting effect - every 10 LEDs have different colors
fn group_counting(led_count: u32, led_type: LedType) -> Vec<u8> {
let mut buffer = Vec::new();
let group_colors = [
(255, 0, 0), // Red (1-10)
(0, 255, 0), // Green (11-20)
(0, 0, 255), // Blue (21-30)
(255, 255, 0), // Yellow (31-40)
(255, 0, 255), // Magenta (41-50)
(0, 255, 255), // Cyan (51-60)
(255, 128, 0), // Orange (61-70)
(128, 255, 0), // Lime (71-80)
(255, 255, 255), // White (81-90)
(128, 128, 128), // Gray (91-100)
];
for i in 0..led_count {
let group_index = (i / 10) % group_colors.len() as u32;
let color = group_colors[group_index as usize];
buffer.push(color.0);
buffer.push(color.1);
buffer.push(color.2);
if Self::is_rgbw_type(&led_type) {
buffer.push(0); // White channel
}
}
buffer
}
/// Single LED scan effect - one LED moves along the strip
fn single_scan(led_count: u32, led_type: LedType, time: f64, speed: f64) -> Vec<u8> {
let mut buffer = Vec::new();
let scan_period = 2.0 / speed; // 2 seconds per full scan at speed 1.0
let active_index = ((time / scan_period * led_count as f64) as u32) % led_count;
for i in 0..led_count {
if i == active_index {
// Bright white LED
buffer.push(255);
buffer.push(255);
buffer.push(255);
if Self::is_rgbw_type(&led_type) {
buffer.push(255); // White channel
}
} else {
// Off
buffer.push(0);
buffer.push(0);
buffer.push(0);
if Self::is_rgbw_type(&led_type) {
buffer.push(0); // White channel
}
}
}
buffer
}
/// Breathing effect - entire strip breathes with white light
fn breathing(led_count: u32, led_type: LedType, time: f64, speed: f64) -> Vec<u8> {
let mut buffer = Vec::new();
let breathing_period = 4.0 / speed; // 4 seconds per breath at speed 1.0
let brightness = ((time / breathing_period * 2.0 * PI).sin() * 0.5 + 0.5) * 255.0;
let brightness = brightness as u8;
for _i in 0..led_count {
buffer.push(brightness);
buffer.push(brightness);
buffer.push(brightness);
if Self::is_rgbw_type(&led_type) {
buffer.push(brightness); // White channel
}
}
buffer
}
/// Convert HSV to RGB
/// H: 0-360, S: 0-1, V: 0-1
/// Returns: (R, G, B) where each component is 0-255
fn hsv_to_rgb(h: f64, s: f64, v: f64) -> (u8, u8, u8) {
let c = v * s;
let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
let m = v - c;
let (r_prime, g_prime, b_prime) = if h < 60.0 {
(c, x, 0.0)
} else if h < 120.0 {
(x, c, 0.0)
} else if h < 180.0 {
(0.0, c, x)
} else if h < 240.0 {
(0.0, x, c)
} else if h < 300.0 {
(x, 0.0, c)
} else {
(c, 0.0, x)
};
let r = ((r_prime + m) * 255.0).round() as u8;
let g = ((g_prime + m) * 255.0).round() as u8;
let b = ((b_prime + m) * 255.0).round() as u8;
(r, g, b)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hsv_to_rgb() {
// Test red
let (r, g, b) = LedTestEffects::hsv_to_rgb(0.0, 1.0, 1.0);
assert_eq!((r, g, b), (255, 0, 0));
// Test green
let (r, g, b) = LedTestEffects::hsv_to_rgb(120.0, 1.0, 1.0);
assert_eq!((r, g, b), (0, 255, 0));
// Test blue
let (r, g, b) = LedTestEffects::hsv_to_rgb(240.0, 1.0, 1.0);
assert_eq!((r, g, b), (0, 0, 255));
}
#[test]
fn test_flowing_rainbow() {
let config = TestEffectConfig {
effect_type: TestEffectType::FlowingRainbow,
led_count: 10,
led_type: LedType::RGB,
speed: 1.0,
};
let colors = LedTestEffects::generate_colors(&config, 0);
assert_eq!(colors.len(), 30); // 10 LEDs * 3 bytes each
}
#[test]
fn test_group_counting() {
let config = TestEffectConfig {
effect_type: TestEffectType::GroupCounting,
led_count: 20,
led_type: LedType::RGB,
speed: 1.0,
};
let colors = LedTestEffects::generate_colors(&config, 0);
assert_eq!(colors.len(), 60); // 20 LEDs * 3 bytes each
// First 10 should be red
assert_eq!(colors[0], 255); // R
assert_eq!(colors[1], 0); // G
assert_eq!(colors[2], 0); // B
// Next 10 should be green
assert_eq!(colors[30], 0); // R
assert_eq!(colors[31], 255); // G
assert_eq!(colors[32], 0); // B
}
}

View File

@ -4,22 +4,36 @@
mod ambient_light;
mod display;
mod led_color;
mod led_test_effects;
mod rpc;
pub mod screenshot;
mod screenshot;
mod screenshot_manager;
mod screen_stream;
mod volume;
use ambient_light::{Border, LedColorsPublisher, LedStripConfig, LedStripConfigGroup};
use core_graphics::display::{
kCGNullWindowID, kCGWindowImageDefault, kCGWindowListOptionOnScreenOnly, CGDisplay,
};
use ambient_light::{Border, ColorCalibration, LedStripConfig, LedStripConfigGroup, LedType};
use display::{DisplayManager, DisplayState};
use display_info::DisplayInfo;
use led_test_effects::{LedTestEffects, TestEffectConfig, TestEffectType};
use paris::{error, info, warn};
use rpc::{BoardInfo, UdpRpc};
use screenshot::Screenshot;
use screenshot_manager::ScreenshotManager;
use serde::{Deserialize, Serialize};
use serde_json::to_string;
use tauri::{http::ResponseBuilder, regex, Manager};
use tauri::{Manager, Emitter, Runtime};
use regex;
use tauri::http::{Request, Response};
use volume::VolumeManager;
use std::sync::Arc;
use tokio::sync::RwLock;
// Global static variables for LED test effect management
static EFFECT_HANDLE: tokio::sync::OnceCell<Arc<RwLock<Option<tokio::task::JoinHandle<()>>>>> =
tokio::sync::OnceCell::const_new();
static CANCEL_TOKEN: tokio::sync::OnceCell<Arc<RwLock<Option<tokio_util::sync::CancellationToken>>>> =
tokio::sync::OnceCell::const_new();
#[derive(Serialize, Deserialize)]
#[serde(remote = "DisplayInfo")]
struct DisplayInfoDef {
@ -87,7 +101,7 @@ async fn get_led_strips_sample_points(
let screenshot_manager = ScreenshotManager::global().await;
let channels = screenshot_manager.channels.read().await;
if let Some(rx) = channels.get(&config.display_id) {
let rx = rx.clone();
let rx = rx.read().await;
let screenshot = rx.borrow().clone();
let sample_points = screenshot.get_sample_points(&config);
Ok(sample_points)
@ -104,7 +118,7 @@ async fn get_one_edge_colors(
let screenshot_manager = ScreenshotManager::global().await;
let channels = screenshot_manager.channels.read().await;
if let Some(rx) = channels.get(&display_id) {
let rx = rx.clone();
let rx = rx.read().await;
let screenshot = rx.borrow().clone();
let bytes = screenshot.bytes.read().await.to_owned();
let colors =
@ -135,8 +149,22 @@ async fn patch_led_strip_len(display_id: u32, border: Border, delta_len: i8) ->
}
#[tauri::command]
async fn send_colors(buffer: Vec<u8>) -> Result<(), String> {
ambient_light::LedColorsPublisher::send_colors(buffer)
async fn patch_led_strip_type(display_id: u32, border: Border, led_type: LedType) -> Result<(), String> {
let config_manager = ambient_light::ConfigManager::global().await;
config_manager
.patch_led_strip_type(display_id, border, led_type)
.await
.map_err(|e| {
error!("can not patch led strip type: {}", e);
e.to_string()
})?;
Ok(())
}
#[tauri::command]
async fn send_colors(offset: u16, buffer: Vec<u8>) -> Result<(), String> {
ambient_light::LedColorsPublisher::send_colors(offset, buffer)
.await
.map_err(|e| {
error!("can not send colors: {}", e);
@ -145,14 +173,201 @@ async fn send_colors(buffer: Vec<u8>) -> Result<(), String> {
}
#[tauri::command]
async fn move_strip_part(display_id: u32, border: Border, target_start: usize) -> Result<(), String> {
async fn send_test_colors_to_board(board_address: String, offset: u16, buffer: Vec<u8>) -> Result<(), String> {
use tokio::net::UdpSocket;
let socket = UdpSocket::bind("0.0.0.0:0").await.map_err(|e| {
error!("Failed to bind UDP socket: {}", e);
e.to_string()
})?;
let mut packet = vec![0x02]; // Header
packet.push((offset >> 8) as u8); // Byte offset high
packet.push((offset & 0xff) as u8); // Byte offset low
packet.extend_from_slice(&buffer); // Color data
socket.send_to(&packet, &board_address).await.map_err(|e| {
error!("Failed to send test colors to board {}: {}", board_address, e);
e.to_string()
})?;
info!("Sent test colors to board {} with offset {} and {} bytes", board_address, offset, buffer.len());
Ok(())
}
#[tauri::command]
async fn enable_test_mode() -> Result<(), String> {
let publisher = ambient_light::LedColorsPublisher::global().await;
publisher.enable_test_mode().await;
Ok(())
}
#[tauri::command]
async fn disable_test_mode() -> Result<(), String> {
info!("🔄 disable_test_mode command called from frontend");
let publisher = ambient_light::LedColorsPublisher::global().await;
publisher.disable_test_mode().await;
info!("✅ disable_test_mode command completed");
Ok(())
}
#[tauri::command]
async fn is_test_mode_active() -> Result<bool, String> {
let publisher = ambient_light::LedColorsPublisher::global().await;
Ok(publisher.is_test_mode_active().await)
}
#[tauri::command]
async fn start_led_test_effect(
board_address: String,
effect_config: TestEffectConfig,
update_interval_ms: u64,
) -> Result<(), String> {
use tokio::time::{interval, Duration};
// Enable test mode first
let publisher = ambient_light::LedColorsPublisher::global().await;
publisher.enable_test_mode().await;
let handle_storage = EFFECT_HANDLE.get_or_init(|| async {
Arc::new(RwLock::new(None))
}).await;
let cancel_storage = CANCEL_TOKEN.get_or_init(|| async {
Arc::new(RwLock::new(None))
}).await;
// Stop any existing effect
{
let mut cancel_guard = cancel_storage.write().await;
if let Some(token) = cancel_guard.take() {
token.cancel();
}
let mut handle_guard = handle_storage.write().await;
if let Some(handle) = handle_guard.take() {
let _ = handle.await; // Wait for graceful shutdown
}
}
// Start new effect
let effect_config = Arc::new(effect_config);
let board_address = Arc::new(board_address);
let start_time = std::time::Instant::now();
// Create new cancellation token
let cancel_token = tokio_util::sync::CancellationToken::new();
let cancel_token_clone = cancel_token.clone();
let handle = tokio::spawn(async move {
let mut interval = interval(Duration::from_millis(update_interval_ms));
loop {
tokio::select! {
_ = interval.tick() => {
let elapsed_ms = start_time.elapsed().as_millis() as u64;
let colors = LedTestEffects::generate_colors(&effect_config, elapsed_ms);
// Send to board
if let Err(e) = send_test_colors_to_board_internal(&board_address, 0, colors).await {
error!("Failed to send test effect colors: {}", e);
break;
}
}
_ = cancel_token_clone.cancelled() => {
info!("LED test effect cancelled gracefully");
break;
}
}
}
info!("LED test effect task ended");
});
// Store the handle and cancel token
{
let mut handle_guard = handle_storage.write().await;
*handle_guard = Some(handle);
let mut cancel_guard = cancel_storage.write().await;
*cancel_guard = Some(cancel_token);
}
Ok(())
}
#[tauri::command]
async fn stop_led_test_effect(board_address: String, led_count: u32, led_type: led_test_effects::LedType) -> Result<(), String> {
// Stop the effect task first
info!("🛑 Stopping LED test effect - board: {}", board_address);
// Cancel the task gracefully first
if let Some(cancel_storage) = CANCEL_TOKEN.get() {
let mut cancel_guard = cancel_storage.write().await;
if let Some(token) = cancel_guard.take() {
info!("🔄 Cancelling test effect task gracefully");
token.cancel();
}
}
// Wait for the task to finish
if let Some(handle_storage) = EFFECT_HANDLE.get() {
let mut handle_guard = handle_storage.write().await;
if let Some(handle) = handle_guard.take() {
info!("⏳ Waiting for test effect task to finish");
match handle.await {
Ok(_) => info!("✅ Test effect task finished successfully"),
Err(e) => warn!("⚠️ Test effect task finished with error: {}", e),
}
}
}
// Turn off all LEDs
let bytes_per_led = match led_type {
led_test_effects::LedType::WS2812B => 3,
led_test_effects::LedType::SK6812 => 4,
};
let buffer = vec![0u8; (led_count * bytes_per_led) as usize];
send_test_colors_to_board_internal(&board_address, 0, buffer).await
.map_err(|e| e.to_string())?;
info!("💡 Sent LED off command");
// Disable test mode to resume normal publishing
let publisher = ambient_light::LedColorsPublisher::global().await;
publisher.disable_test_mode().await;
info!("🔄 Test mode disabled, normal publishing resumed");
info!("✅ LED test effect stopped completely");
Ok(())
}
// Internal helper function
async fn send_test_colors_to_board_internal(board_address: &str, offset: u16, buffer: Vec<u8>) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
use tokio::net::UdpSocket;
let socket = UdpSocket::bind("0.0.0.0:0").await?;
let mut packet = vec![0x02]; // Header
packet.push((offset >> 8) as u8); // Byte offset high
packet.push((offset & 0xff) as u8); // Byte offset low
packet.extend_from_slice(&buffer); // Color data
socket.send_to(&packet, board_address).await?;
Ok(())
}
#[tauri::command]
async fn move_strip_part(
display_id: u32,
border: Border,
target_start: usize,
) -> Result<(), String> {
let config_manager = ambient_light::ConfigManager::global().await;
config_manager
.move_strip_part(
display_id,
border,
target_start,
)
.move_strip_part(display_id, border, target_start)
.await
.map_err(|e| {
error!("can not move strip part: {}", e);
@ -172,17 +387,192 @@ async fn reverse_led_strip_part(display_id: u32, border: Border) -> Result<(), S
})
}
#[tauri::command]
async fn set_color_calibration(calibration: ColorCalibration) -> Result<(), String> {
let config_manager = ambient_light::ConfigManager::global().await;
config_manager
.set_color_calibration(calibration)
.await
.map_err(|e| {
error!("can not set color calibration: {}", e);
e.to_string()
})
}
#[tauri::command]
async fn read_config() -> ambient_light::LedStripConfigGroup {
let config_manager = ambient_light::ConfigManager::global().await;
config_manager.configs().await
}
#[tauri::command]
async fn get_boards() -> Result<Vec<BoardInfo>, String> {
let udp_rpc = UdpRpc::global().await;
if let Err(e) = udp_rpc {
return Err(format!("can not ping: {}", e));
}
let udp_rpc = udp_rpc.as_ref().unwrap();
let boards = udp_rpc.get_boards().await;
let boards = boards.into_iter().collect::<Vec<_>>();
Ok(boards)
}
#[tauri::command]
async fn get_displays() -> Vec<DisplayState> {
let display_manager = DisplayManager::global().await;
display_manager.get_displays().await
}
// Protocol handler for ambient-light://
fn handle_ambient_light_protocol<R: Runtime>(
_ctx: tauri::UriSchemeContext<R>,
request: Request<Vec<u8>>
) -> Response<Vec<u8>> {
let url = request.uri();
// info!("Handling ambient-light protocol request: {}", url);
// Parse the URL to extract parameters
let url_str = url.to_string();
let re = regex::Regex::new(r"ambient-light://displays/(\d+)\?width=(\d+)&height=(\d+)").unwrap();
if let Some(captures) = re.captures(&url_str) {
let display_id: u32 = captures[1].parse().unwrap_or(0);
let width: u32 = captures[2].parse().unwrap_or(400);
let height: u32 = captures[3].parse().unwrap_or(300);
// info!("Efficient screenshot request for display {}, {}x{}", display_id, width, height);
// Optimized screenshot processing with much smaller intermediate size
// info!("Screenshot request received: display_id={}, width={}, height={}", display_id, width, height);
let screenshot_data = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(async {
let screenshot_manager = ScreenshotManager::global().await;
let channels = screenshot_manager.channels.read().await;
if let Some(rx) = channels.get(&display_id) {
let rx = rx.read().await;
let screenshot = rx.borrow().clone();
let bytes = screenshot.bytes.read().await.to_owned();
// Use much smaller intermediate resolution for performance
let intermediate_width = 800; // Much smaller than original 5120
let intermediate_height = 450; // Much smaller than original 2880
// Convert BGRA to RGBA format
let mut rgba_bytes = bytes.as_ref().clone();
for chunk in rgba_bytes.chunks_exact_mut(4) {
chunk.swap(0, 2); // Swap B and R channels
}
let image_result = image::RgbaImage::from_raw(
screenshot.width as u32,
screenshot.height as u32,
rgba_bytes,
);
if let Some(img) = image_result {
// Step 1: Fast downscale to intermediate size
let intermediate_image = image::imageops::resize(
&img,
intermediate_width,
intermediate_height,
image::imageops::FilterType::Nearest, // Fastest possible
);
// Step 2: Scale to final target size
let final_image = if width == intermediate_width && height == intermediate_height {
intermediate_image
} else {
image::imageops::resize(
&intermediate_image,
width,
height,
image::imageops::FilterType::Triangle,
)
};
let raw_data = final_image.into_raw();
// info!("Efficient resize completed: {}x{}, {} bytes", width, height, raw_data.len());
Ok(raw_data)
} else {
error!("Failed to create image from raw bytes");
Err("Failed to create image from raw bytes".to_string())
}
} else {
error!("Display {} not found", display_id);
Err(format!("Display {} not found", display_id))
}
})
});
match screenshot_data {
Ok(data) => {
Response::builder()
.header("Content-Type", "application/octet-stream")
.header("Access-Control-Allow-Origin", "*")
.header("X-Image-Width", width.to_string())
.header("X-Image-Height", height.to_string())
.body(data)
.unwrap_or_else(|_| {
Response::builder()
.status(500)
.body("Failed to build response".as_bytes().to_vec())
.unwrap()
})
}
Err(e) => {
error!("Failed to get screenshot: {}", e);
Response::builder()
.status(500)
.body(format!("Error: {}", e).into_bytes())
.unwrap()
}
}
} else {
warn!("Invalid ambient-light URL format: {}", url_str);
Response::builder()
.status(400)
.body("Invalid URL format".as_bytes().to_vec())
.unwrap()
}
}
#[tokio::main]
async fn main() {
env_logger::init();
let screenshot_manager = ScreenshotManager::global().await;
screenshot_manager.start().unwrap();
// Initialize display info (removed debug output)
tokio::spawn(async move {
let screenshot_manager = ScreenshotManager::global().await;
screenshot_manager.start().await.unwrap_or_else(|e| {
error!("can not start screenshot manager: {}", e);
})
});
tokio::spawn(async move {
let led_color_publisher = ambient_light::LedColorsPublisher::global().await;
led_color_publisher.start();
led_color_publisher.start().await;
});
// Start WebSocket server for screen streaming
tokio::spawn(async move {
if let Err(e) = start_websocket_server().await {
error!("Failed to start WebSocket server: {}", e);
}
});
let _volume = VolumeManager::global().await;
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![
greet,
list_display_info,
@ -191,143 +581,29 @@ async fn main() {
get_led_strips_sample_points,
get_one_edge_colors,
patch_led_strip_len,
patch_led_strip_type,
send_colors,
send_test_colors_to_board,
enable_test_mode,
disable_test_mode,
is_test_mode_active,
start_led_test_effect,
stop_led_test_effect,
move_strip_part,
reverse_led_strip_part,
set_color_calibration,
read_config,
get_boards,
get_displays
])
.register_uri_scheme_protocol("ambient-light", move |_app, request| {
let response = ResponseBuilder::new().header("Access-Control-Allow-Origin", "*");
.register_uri_scheme_protocol("ambient-light", handle_ambient_light_protocol)
let uri = request.uri();
let uri = percent_encoding::percent_decode_str(uri)
.decode_utf8()
.unwrap()
.to_string();
let url = url_build_parse::parse_url(uri.as_str());
if let Err(err) = url {
error!("url parse error: {}", err);
return response
.status(500)
.mimetype("text/plain")
.body("Parse uri failed.".as_bytes().to_vec());
}
let url = url.unwrap();
let re = regex::Regex::new(r"^/displays/(\d+)$").unwrap();
let path = url.path;
let captures = re.captures(path.as_str());
if let None = captures {
error!("path not matched: {:?}", path);
return response
.status(404)
.mimetype("text/plain")
.body("Path Not Found.".as_bytes().to_vec());
}
let captures = captures.unwrap();
let display_id = captures[1].parse::<u32>().unwrap();
let bytes = tokio::task::block_in_place(move || {
tauri::async_runtime::block_on(async move {
let screenshot_manager = ScreenshotManager::global().await;
let channels = screenshot_manager.channels.read().await;
if let Some(rx) = channels.get(&display_id) {
let rx = rx.clone();
let screenshot = rx.borrow().clone();
let bytes = screenshot.bytes.read().await;
let (scale_factor_x, scale_factor_y, width, height) = if url.query.is_some()
&& url.query.as_ref().unwrap().contains_key("height")
&& url.query.as_ref().unwrap().contains_key("width")
{
let width = url.query.as_ref().unwrap()["width"]
.parse::<u32>()
.map_err(|err| {
warn!("width parse error: {}", err);
err
})?;
let height = url.query.as_ref().unwrap()["height"]
.parse::<u32>()
.map_err(|err| {
warn!("height parse error: {}", err);
err
})?;
(
screenshot.width as f32 / width as f32,
screenshot.height as f32 / height as f32,
width,
height,
)
} else {
log::debug!("scale by scale_factor");
let scale_factor = screenshot.scale_factor;
(
scale_factor,
scale_factor,
(screenshot.width as f32 / scale_factor) as u32,
(screenshot.height as f32 / scale_factor) as u32,
)
};
log::debug!(
"scale by query. width: {}, height: {}, scale_factor: {}, len: {}",
width,
height,
screenshot.width as f32 / width as f32,
width * height * 4,
);
let bytes_per_row = screenshot.bytes_per_row as f32;
let mut rgba_buffer = vec![0u8; (width * height * 4) as usize];
for y in 0..height {
for x in 0..width {
let offset = ((y as f32) * scale_factor_y).floor() as usize
* bytes_per_row as usize
+ ((x as f32) * scale_factor_x).floor() as usize * 4;
let b = bytes[offset];
let g = bytes[offset + 1];
let r = bytes[offset + 2];
let a = bytes[offset + 3];
let offset_2 = (y * width + x) as usize * 4;
rgba_buffer[offset_2] = r;
rgba_buffer[offset_2 + 1] = g;
rgba_buffer[offset_2 + 2] = b;
rgba_buffer[offset_2 + 3] = a;
}
}
Ok(rgba_buffer.clone())
} else {
anyhow::bail!("Display#{}: not found", display_id);
}
})
});
if let Ok(bytes) = bytes {
return response
.mimetype("octet/stream")
.status(200)
.body(bytes.to_vec());
}
let err = bytes.unwrap_err();
error!("request screenshot bin data failed: {}", err);
return response
.mimetype("text/plain")
.status(500)
.body(err.to_string().into_bytes());
})
.setup(move |app| {
let app_handle = app.handle().clone();
tokio::spawn(async move {
let config_manager = ambient_light::ConfigManager::global().await;
let config_update_receiver = config_manager.clone_config_update_receiver();
let mut config_update_receiver = config_update_receiver;
let mut config_update_receiver = config_manager.clone_config_update_receiver();
loop {
if let Err(err) = config_update_receiver.changed().await {
error!("config update receiver changed error: {}", err);
@ -338,7 +614,7 @@ async fn main() {
let config = config_update_receiver.borrow().clone();
app_handle.emit_all("config_changed", config).unwrap();
app_handle.emit("config_changed", config).unwrap();
}
});
@ -355,10 +631,11 @@ async fn main() {
let publisher = publisher_update_receiver.borrow().clone();
app_handle
.emit_all("led_sorted_colors_changed", publisher)
.emit("led_sorted_colors_changed", publisher)
.unwrap();
}
});
let app_handle = app.handle().clone();
tokio::spawn(async move {
let publisher = ambient_light::LedColorsPublisher::global().await;
@ -372,13 +649,81 @@ async fn main() {
let publisher = publisher_update_receiver.borrow().clone();
app_handle
.emit_all("led_colors_changed", publisher)
.emit("led_colors_changed", publisher)
.unwrap();
}
});
let app_handle = app.handle().clone();
tokio::spawn(async move {
loop {
match UdpRpc::global().await {
Ok(udp_rpc) => {
let mut receiver = udp_rpc.subscribe_boards_change();
loop {
if let Err(err) = receiver.changed().await {
error!("boards change receiver changed error: {}", err);
return;
}
let boards = receiver.borrow().clone();
let boards = boards.into_iter().collect::<Vec<_>>();
app_handle.emit("boards_changed", boards).unwrap();
}
}
Err(err) => {
error!("udp rpc error: {}", err);
return;
}
}
}
});
let app_handle = app.handle().clone();
tokio::spawn(async move {
let display_manager = DisplayManager::global().await;
let mut rx = display_manager.subscribe_displays_changed();
while rx.changed().await.is_ok() {
let displays = rx.borrow().clone();
log::info!("displays changed. emit displays_changed event.");
app_handle.emit("displays_changed", displays).unwrap();
}
});
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
// WebSocket server for screen streaming
async fn start_websocket_server() -> anyhow::Result<()> {
use tokio::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:8765").await?;
info!("WebSocket server listening on ws://127.0.0.1:8765");
while let Ok((stream, addr)) = listener.accept().await {
info!("New WebSocket connection from: {}", addr);
tokio::spawn(async move {
info!("Starting WebSocket handler for connection from: {}", addr);
match screen_stream::handle_websocket_connection(stream).await {
Ok(_) => {
info!("WebSocket connection from {} completed successfully", addr);
}
Err(e) => {
warn!("WebSocket connection error from {}: {}", addr, e);
}
}
info!("WebSocket handler task completed for: {}", addr);
});
}
Ok(())
}

328
src-tauri/src/rpc/board.rs Normal file
View File

@ -0,0 +1,328 @@
use std::{sync::Arc, time::Duration};
use paris::{error, info, warn};
use tokio::{io, net::UdpSocket, sync::RwLock, task::yield_now, time::timeout};
use crate::{
ambient_light::{ConfigManager, LedStripConfig},
rpc::DisplaySettingRequest,
volume::{self, VolumeManager},
};
use super::{BoardConnectStatus, BoardInfo, BoardMessageChannels};
#[derive(Debug)]
pub struct Board {
pub info: Arc<RwLock<BoardInfo>>,
socket: Option<Arc<UdpSocket>>,
listen_handler: Option<tokio::task::JoinHandle<()>>,
volume_changed_subscriber_handler: Option<tokio::task::JoinHandle<()>>,
state_of_displays_changed_subscriber_handler: Option<tokio::task::JoinHandle<()>>,
led_strip_config_changed_subscriber_handler: Option<tokio::task::JoinHandle<()>>,
}
impl Board {
pub fn new(info: BoardInfo) -> Self {
Self {
info: Arc::new(RwLock::new(info)),
socket: None,
listen_handler: None,
volume_changed_subscriber_handler: None,
state_of_displays_changed_subscriber_handler: None,
led_strip_config_changed_subscriber_handler: None,
}
}
pub async fn init_socket(&mut self) -> anyhow::Result<()> {
let info = self.info.clone();
let info = info.read().await;
let socket = UdpSocket::bind("0.0.0.0:0").await?;
socket.connect((info.address, info.port)).await?;
let socket = Arc::new(socket);
self.socket = Some(socket.clone());
let handler = tokio::spawn(async move {
let mut buf = [0u8; 128];
let board_message_channels = crate::rpc::channels::BoardMessageChannels::global().await;
let display_setting_request_sender = board_message_channels
.display_setting_request_sender
.clone();
let volume_setting_request_sender =
board_message_channels.volume_setting_request_sender.clone();
loop {
match socket.recv(&mut buf).await {
Ok(len) => {
log::info!("recv: {:?}", &buf[..len]);
if buf[0] == 3 {
let result =
display_setting_request_sender.send(DisplaySettingRequest {
display_index: buf[1] as usize,
setting: crate::rpc::DisplaySetting::Brightness(buf[2]),
});
if let Err(err) = result {
error!("send display setting request to channel failed: {:?}", err);
}
} else if buf[0] == 4 {
let result = volume_setting_request_sender.send(buf[1] as f32 / 100.0);
if let Err(err) = result {
error!("send volume setting request to channel failed: {:?}", err);
}
}
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
yield_now().await;
continue;
}
Err(e) => {
error!("socket recv error: {:?}", e);
break;
}
}
}
});
self.listen_handler = Some(handler);
self.subscribe_volume_changed().await;
self.subscribe_state_of_displays_changed().await;
self.subscribe_led_strip_config_changed().await;
Ok(())
}
async fn subscribe_volume_changed(&mut self) {
let channel = BoardMessageChannels::global().await;
let mut volume_changed_rx = channel.volume_changed_sender.subscribe();
let info = self.info.clone();
let socket = self.socket.clone();
let handler = tokio::spawn(async move {
loop {
let volume: Result<f32, tokio::sync::broadcast::error::RecvError> =
volume_changed_rx.recv().await;
if let Err(err) = volume {
match err {
tokio::sync::broadcast::error::RecvError::Closed => {
log::error!("volume changed channel closed");
break;
}
tokio::sync::broadcast::error::RecvError::Lagged(_) => {
log::info!("volume changed channel lagged");
continue;
}
}
}
let volume = volume.unwrap();
let info = info.read().await;
if socket.is_none() || info.connect_status != BoardConnectStatus::Connected {
log::info!("board is not connected, skip send volume changed");
continue;
}
let socket = socket.as_ref().unwrap();
let mut buf = [0u8; 2];
buf[0] = 4;
buf[1] = (volume * 100.0) as u8;
if let Err(err) = socket.send(&buf).await {
log::warn!("send volume changed failed: {:?}", err);
}
}
});
let volume_manager = VolumeManager::global().await;
let volume = volume_manager.get_volume().await;
if let Some(socket) = self.socket.as_ref() {
let buf = [4, (volume * 100.0) as u8];
if let Err(err) = socket.send(&buf).await {
log::warn!("send volume failed: {:?}", err);
}
} else {
log::warn!("socket is none, skip send volume");
}
self.volume_changed_subscriber_handler = Some(handler);
}
async fn subscribe_state_of_displays_changed(&mut self) {
let channel: &BoardMessageChannels = BoardMessageChannels::global().await;
let mut state_of_displays_changed_rx = channel.displays_changed_sender.subscribe();
let info = self.info.clone();
let socket = self.socket.clone();
let handler = tokio::spawn(async move {
loop {
let states: Result<
Vec<crate::display::DisplayState>,
tokio::sync::broadcast::error::RecvError,
> = state_of_displays_changed_rx.recv().await;
if let Err(err) = states {
match err {
tokio::sync::broadcast::error::RecvError::Closed => {
log::error!("state of displays changed channel closed");
break;
}
tokio::sync::broadcast::error::RecvError::Lagged(_) => {
log::info!("state of displays changed channel lagged");
continue;
}
}
}
let info = info.read().await;
if socket.is_none() || info.connect_status != BoardConnectStatus::Connected {
log::info!("board is not connected, skip send state of displays changed");
continue;
}
let socket = socket.as_ref().unwrap();
let mut buf = [0u8; 3];
let states = states.unwrap();
for (index, state) in states.iter().enumerate() {
buf[0] = 3;
buf[1] = index as u8;
buf[2] = state.brightness as u8;
log::info!("send state of displays changed: {:?}", &buf[..]);
if let Err(err) = socket.send(&buf).await {
log::warn!("send state of displays changed failed: {:?}", err);
}
}
}
});
self.state_of_displays_changed_subscriber_handler = Some(handler);
}
async fn subscribe_led_strip_config_changed(&mut self) {
let config_manager = ConfigManager::global().await;
let mut led_strip_config_changed_rx = config_manager.clone_config_update_receiver();
let info = self.info.clone();
let socket = self.socket.clone();
let handler = tokio::spawn(async move {
while led_strip_config_changed_rx.changed().await.is_ok() {
let config = led_strip_config_changed_rx.borrow().clone();
let info = info.read().await;
if socket.is_none() || info.connect_status != BoardConnectStatus::Connected {
log::info!("board is not connected, skip send led strip config changed");
continue;
}
let socket = socket.as_ref().unwrap();
let mut buf = [0u8; 4];
buf[0] = 5;
buf[1..].copy_from_slice(&config.color_calibration.to_bytes());
log::info!("send led strip config changed: {:?}", &buf[..]);
if let Err(err) = socket.send(&buf).await {
log::warn!("send led strip config changed failed: {:?}", err);
}
}
});
self.led_strip_config_changed_subscriber_handler = Some(handler);
}
pub async fn send_colors(&self, buf: &[u8]) {
let info = self.info.read().await;
if self.socket.is_none() || info.connect_status != BoardConnectStatus::Connected {
return;
}
let socket = self.socket.as_ref().unwrap();
socket.send(buf).await.unwrap();
}
pub async fn check(&self) -> anyhow::Result<()> {
let info = self.info.read().await;
let socket = UdpSocket::bind("0.0.0.0:0").await?;
socket.connect((info.address, info.port)).await?;
drop(info);
let instant = std::time::Instant::now();
socket.send(&[1]).await?;
let mut buf = [0u8; 1];
let recv_future = socket.recv(&mut buf);
let check_result = timeout(Duration::from_secs(1), recv_future).await;
let mut info = self.info.write().await;
match check_result {
Ok(_) => {
let ttl = instant.elapsed();
if buf == [1] {
info.connect_status = BoardConnectStatus::Connected;
} else {
if let BoardConnectStatus::Connecting(retry) = info.connect_status {
if retry < 10 {
info.connect_status = BoardConnectStatus::Connecting(retry + 1);
info!("reconnect: {}", retry + 1);
} else {
info.connect_status = BoardConnectStatus::Disconnected;
warn!("board Disconnected: bad pong.");
}
} else if info.connect_status != BoardConnectStatus::Disconnected {
info.connect_status = BoardConnectStatus::Connecting(1);
}
}
info.ttl = Some(ttl.as_millis());
}
Err(_) => {
if let BoardConnectStatus::Connecting(retry) = info.connect_status {
if retry < 10 {
info.connect_status = BoardConnectStatus::Connecting(retry + 1);
info!("reconnect: {}", retry + 1);
} else {
info.connect_status = BoardConnectStatus::Disconnected;
warn!("board Disconnected: timeout");
}
} else if info.connect_status != BoardConnectStatus::Disconnected {
info.connect_status = BoardConnectStatus::Connecting(1);
}
info.ttl = None;
}
}
info.checked_at = Some(std::time::SystemTime::now());
Ok(())
}
}
impl Drop for Board {
fn drop(&mut self) {
info!("board drop");
if let Some(handler) = self.listen_handler.take() {
handler.abort();
}
if let Some(handler) = self.volume_changed_subscriber_handler.take() {
handler.abort();
}
if let Some(handler) = self.state_of_displays_changed_subscriber_handler.take() {
handler.abort();
}
if let Some(handler) = self.led_strip_config_changed_subscriber_handler.take() {
handler.abort();
}
}
}

View File

@ -0,0 +1,36 @@
use std::{net::Ipv4Addr, time::Duration};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum BoardConnectStatus {
Connected,
Connecting(u8),
Disconnected,
Unknown,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct BoardInfo {
pub fullname: String,
pub host: String,
pub address: Ipv4Addr,
pub port: u16,
pub connect_status: BoardConnectStatus,
pub checked_at: Option<std::time::SystemTime>,
pub ttl: Option<u128>,
}
impl BoardInfo {
pub fn new(fullname: String, host: String, address: Ipv4Addr, port: u16) -> Self {
Self {
fullname,
host,
address,
port,
connect_status: BoardConnectStatus::Unknown,
checked_at: None,
ttl: None,
}
}
}

View File

@ -0,0 +1,43 @@
use std::sync::Arc;
use tokio::sync::{broadcast, OnceCell};
use crate::display::DisplayState;
use super::DisplaySettingRequest;
pub struct BoardMessageChannels {
pub display_setting_request_sender: Arc<broadcast::Sender<DisplaySettingRequest>>,
pub volume_setting_request_sender: Arc<broadcast::Sender<f32>>,
pub volume_changed_sender: Arc<broadcast::Sender<f32>>,
pub displays_changed_sender: Arc<broadcast::Sender<Vec<DisplayState>>>,
}
impl BoardMessageChannels {
pub async fn global() -> &'static Self {
static BOARD_MESSAGE_CHANNELS: OnceCell<BoardMessageChannels> = OnceCell::const_new();
BOARD_MESSAGE_CHANNELS.get_or_init(|| async {Self::new()}).await
}
pub fn new() -> Self {
let (display_setting_request_sender, _) = broadcast::channel(16);
let display_setting_request_sender = Arc::new(display_setting_request_sender);
let (volume_setting_request_sender, _) = broadcast::channel(16);
let volume_setting_request_sender = Arc::new(volume_setting_request_sender);
let (volume_changed_sender, _) = broadcast::channel(2);
let volume_changed_sender = Arc::new(volume_changed_sender);
let (displays_changed_sender, _) = broadcast::channel(2);
let displays_changed_sender = Arc::new(displays_changed_sender);
Self {
display_setting_request_sender,
volume_setting_request_sender,
volume_changed_sender,
displays_changed_sender,
}
}
}

View File

@ -0,0 +1,13 @@
#[derive(Clone, Debug)]
pub enum DisplaySetting {
Brightness(u8),
Contrast(u8),
Mode(u8),
}
#[derive(Clone, Debug)]
pub struct DisplaySettingRequest {
pub display_index: usize,
pub setting: DisplaySetting,
}

View File

@ -1,3 +1,11 @@
mod mqtt;
mod board_info;
mod udp;
mod board;
mod display_setting_request;
mod channels;
pub use mqtt::*;
pub use board_info::*;
pub use udp::*;
pub use board::*;
pub use display_setting_request::*;
pub use channels::*;

View File

@ -1,241 +0,0 @@
use paho_mqtt as mqtt;
use paris::{error, info, warn};
use serde_json::json;
use std::time::Duration;
use time::{format_description, OffsetDateTime};
use tokio::{sync::OnceCell, task};
const DISPLAY_TOPIC: &'static str = "display-ambient-light/display";
const DESKTOP_TOPIC: &'static str = "display-ambient-light/desktop";
const DISPLAY_BRIGHTNESS_TOPIC: &'static str = "display-ambient-light/board/brightness";
const BOARD_SEND_CMD: &'static str = "display-ambient-light/board/cmd";
pub struct MqttRpc {
client: mqtt::AsyncClient,
// change_display_brightness_tx: broadcast::Sender<display::DisplayBrightness>,
// message_tx: broadcast::Sender<models::CmdMqMessage>,
}
impl MqttRpc {
pub async fn global() -> &'static Self {
static MQTT_RPC: OnceCell<MqttRpc> = OnceCell::const_new();
MQTT_RPC
.get_or_init(|| async {
let mqtt_rpc = MqttRpc::new().await.unwrap();
mqtt_rpc.initialize().await.unwrap();
mqtt_rpc
})
.await
}
pub async fn new() -> anyhow::Result<Self> {
let client = mqtt::AsyncClient::new("tcp://192.168.31.11:1883")
.map_err(|err| anyhow::anyhow!("can not create MQTT client. {:?}", err))?;
client.set_connected_callback(|client| {
info!("MQTT server connected.");
client.subscribe("display-ambient-light/board/#", mqtt::QOS_1);
client.subscribe(format!("{}/#", DISPLAY_TOPIC), mqtt::QOS_1);
});
client.set_connection_lost_callback(|client| {
info!("MQTT server connection lost.");
});
client.set_disconnected_callback(|_, a1, a2| {
info!("MQTT server disconnected. {:?} {:?}", a1, a2);
});
let mut last_will_payload = serde_json::Map::new();
last_will_payload.insert("message".to_string(), json!("offline"));
last_will_payload.insert(
"time".to_string(),
serde_json::Value::String(
OffsetDateTime::now_utc()
.format(&time::format_description::well_known::iso8601::Iso8601::DEFAULT)
.unwrap()
.to_string(),
),
);
let last_will = mqtt::Message::new(
format!("{}/status", DESKTOP_TOPIC),
serde_json::to_string(&last_will_payload)
.unwrap()
.as_bytes(),
mqtt::QOS_1,
);
let connect_options = mqtt::ConnectOptionsBuilder::new()
.keep_alive_interval(Duration::from_secs(5))
.will_message(last_will)
.automatic_reconnect(Duration::from_secs(1), Duration::from_secs(5))
.finalize();
let token = client.connect(connect_options);
token.await.map_err(|err| {
anyhow::anyhow!(
"can not connect MQTT server. wait for connect token failed. {:?}",
err
)
})?;
// let (change_display_brightness_tx, _) =
// broadcast::channel::<display::DisplayBrightness>(16);
// let (message_tx, _) = broadcast::channel::<models::CmdMqMessage>(32);
Ok(Self { client })
}
pub async fn listen(&self) {
// let change_display_brightness_tx2 = self.change_display_brightness_tx.clone();
// let message_tx_cloned = self.message_tx.clone();
// let mut stream = self.client.to_owned().get_stream(100);
// while let Some(notification) = stream.next().await {
// match notification {
// Some(notification) => match notification.topic() {
// DISPLAY_BRIGHTNESS_TOPIC => {
// let payload_text = String::from_utf8(notification.payload().to_vec());
// match payload_text {
// Ok(payload_text) => {
// let display_brightness: Result<display::DisplayBrightness, _> =
// serde_json::from_str(payload_text.as_str());
// match display_brightness {
// Ok(display_brightness) => {
// match change_display_brightness_tx2.send(display_brightness)
// {
// Ok(_) => {}
// Err(err) => {
// warn!(
// "can not send display brightness to channel. {:?}",
// err
// );
// }
// }
// }
// Err(err) => {
// warn!(
// "can not parse display brightness from payload. {:?}",
// err
// );
// }
// }
// }
// Err(err) => {
// warn!("can not parse display brightness from payload. {:?}", err);
// }
// }
// }
// BOARD_SEND_CMD => {
// let payload_text = String::from_utf8(notification.payload().to_vec());
// match payload_text {
// Ok(payload_text) => {
// let message: Result<models::CmdMqMessage, _> =
// serde_json::from_str(payload_text.as_str());
// match message {
// Ok(message) => match message_tx_cloned.send(message) {
// Ok(_) => {}
// Err(err) => {
// warn!("can not send message to channel. {:?}", err);
// }
// },
// Err(err) => {
// warn!("can not parse message from payload. {:?}", err);
// }
// }
// }
// Err(err) => {
// warn!("can not parse message from payload. {:?}", err);
// }
// }
// }
// _ => {}
// },
// _ => {
// warn!("can not get notification from MQTT server.");
// }
// }
// }
}
pub async fn initialize(&self) -> anyhow::Result<()> {
// self.subscribe_board()?;
// self.subscribe_display()?;
self.broadcast_desktop_online();
anyhow::Ok(())
}
fn subscribe_board(&self) -> anyhow::Result<()> {
self.client
.subscribe("display-ambient-light/board/#", mqtt::QOS_1)
.wait()
.map_err(|err| anyhow::anyhow!("subscribe board failed. {:?}", err))
.map(|_| ())
}
fn subscribe_display(&self) -> anyhow::Result<()> {
self.client
.subscribe(format!("{}/#", DISPLAY_TOPIC), mqtt::QOS_1)
.wait()
.map_err(|err| anyhow::anyhow!("subscribe board failed. {:?}", err))
.map(|_| ())
}
fn broadcast_desktop_online(&self) {
let client = self.client.to_owned();
task::spawn(async move {
loop {
match OffsetDateTime::now_utc()
.format(&format_description::well_known::Iso8601::DEFAULT)
{
Ok(now_str) => {
let msg = mqtt::Message::new(
"display-ambient-light/desktop/online",
now_str.as_bytes(),
mqtt::QOS_0,
);
match client.publish(msg).await {
Ok(_) => {}
Err(error) => {
warn!("can not publish last online time. {}", error)
}
}
}
Err(error) => {
warn!("can not get time for now. {}", error);
}
}
tokio::time::sleep(Duration::from_millis(1000)).await;
}
});
}
pub async fn publish_led_sub_pixels(&self, payload: Vec<u8>) -> anyhow::Result<()> {
self.client
.publish(mqtt::Message::new(
"display-ambient-light/desktop/colors",
payload,
mqtt::QOS_1,
))
.await
.map_err(|error| anyhow::anyhow!("mqtt publish failed. {}", error))
}
// pub fn subscribe_change_display_brightness_rx(
// &self,
// ) -> broadcast::Receiver<display::DisplayBrightness> {
// self.change_display_brightness_tx.subscribe()
// }
pub async fn publish_desktop_cmd(&self, field: &str, payload: Vec<u8>) -> anyhow::Result<()> {
self.client
.publish(mqtt::Message::new(
format!("{}/{}", DESKTOP_TOPIC, field),
payload,
mqtt::QOS_1,
))
.await
.map_err(|error| anyhow::anyhow!("mqtt publish failed. {}", error))
}
}

235
src-tauri/src/rpc/udp.rs Normal file
View File

@ -0,0 +1,235 @@
use std::{collections::HashMap, sync::Arc, time::Duration};
use futures::future::join_all;
use mdns_sd::{ServiceDaemon, ServiceEvent};
use paris::{error, info, warn};
use tokio::sync::{watch, OnceCell, RwLock};
use super::{Board, BoardInfo};
#[derive(Debug, Clone)]
pub struct UdpRpc {
boards: Arc<RwLock<HashMap<String, Board>>>,
boards_change_sender: Arc<watch::Sender<Vec<BoardInfo>>>,
}
impl UdpRpc {
pub async fn global() -> &'static anyhow::Result<Self> {
static UDP_RPC: OnceCell<anyhow::Result<UdpRpc>> = OnceCell::const_new();
UDP_RPC
.get_or_init(|| async {
let udp_rpc = UdpRpc::new().await?;
udp_rpc.initialize().await;
Ok(udp_rpc)
})
.await
}
async fn new() -> anyhow::Result<Self> {
let boards = Arc::new(RwLock::new(HashMap::new()));
let (boards_change_sender, _) = watch::channel(Vec::new());
let boards_change_sender = Arc::new(boards_change_sender);
Ok(Self {
boards,
boards_change_sender,
})
}
async fn initialize(&self) {
let shared_self = Arc::new(self.clone());
let shared_self_for_search = shared_self.clone();
tokio::spawn(async move {
loop {
match shared_self_for_search.search_boards().await {
Ok(_) => {
info!("search_boards finished");
}
Err(err) => {
error!("search_boards failed: {:?}", err);
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
});
let shared_self_for_check = shared_self.clone();
tokio::spawn(async move {
shared_self_for_check.check_boards().await;
});
}
async fn search_boards(&self) -> anyhow::Result<()> {
let service_type = "_ambient_light._udp.local.";
let mdns = ServiceDaemon::new()?;
let receiver = mdns.browse(&service_type).map_err(|e| {
warn!("Failed to browse for {:?}: {:?}", service_type, e);
e
})?;
let sender = self.boards_change_sender.clone();
while let Ok(event) = receiver.recv() {
match event {
ServiceEvent::ServiceResolved(info) => {
info!(
"Resolved a new service: {} host: {} port: {} IP: {:?} TXT properties: {:?}",
info.get_fullname(),
info.get_hostname(),
info.get_port(),
info.get_addresses(),
info.get_properties(),
);
let mut boards = self.boards.write().await;
let board_info = BoardInfo::new(
info.get_fullname().to_string(),
info.get_hostname().to_string(),
info.get_addresses().iter().next().unwrap().clone(),
info.get_port(),
);
let mut board = Board::new(board_info.clone());
if let Err(err) = board.init_socket().await {
error!("failed to init socket: {:?}", err);
continue;
}
if boards.insert(board_info.fullname.clone(), board).is_some() {
info!("replace board {:?}", board_info);
} else {
info!("add board {:?}", board_info);
}
let tx_boards = boards
.values()
.map(|it| async move { it.info.read().await.clone() });
let tx_boards = join_all(tx_boards).await;
drop(boards);
sender.send(tx_boards)?;
}
ServiceEvent::ServiceRemoved(_, fullname) => {
info!("removed board {:?}", fullname);
let mut boards = self.boards.write().await;
if boards.remove(&fullname).is_some() {
info!("removed board {:?} successful", fullname);
}
let tx_boards = boards
.values()
.map(|it| async move { it.info.read().await.clone() });
let tx_boards = join_all(tx_boards).await;
drop(boards);
sender.send(tx_boards)?;
}
other_event => {
// log::info!("{:?}", &other_event);
}
}
tokio::task::yield_now().await;
}
Ok(())
}
pub fn subscribe_boards_change(&self) -> watch::Receiver<Vec<BoardInfo>> {
self.boards_change_sender.subscribe()
}
pub async fn get_boards(&self) -> Vec<BoardInfo> {
self.boards_change_sender.borrow().clone()
}
pub async fn send_to_all(&self, buff: &Vec<u8>) -> anyhow::Result<()> {
let boards = self.boards.read().await;
for board in boards.values() {
board.send_colors(buff).await;
}
// let socket = self.socket.clone();
// let handlers = boards.into_iter().map(|board| {
// if board.connect_status == BoardConnectStatus::Disconnected {
// return tokio::spawn(async move {
// log::debug!("board {} is disconnected, skip.", board.host);
// });
// }
// let socket = socket.clone();
// let buff = buff.clone();
// tokio::spawn(async move {
// match socket.send_to(&buff, (board.address, board.port)).await {
// Ok(_) => {}
// Err(err) => {
// error!("failed to send to {}: {:?}", board.host, err);
// }
// }
// })
// });
// join_all(handlers).await;
Ok(())
}
pub async fn check_boards(&self) {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::task::yield_now().await;
interval.tick().await;
let boards = self.boards.read().await;
if boards.is_empty() {
info!("no boards found");
continue;
}
// Store previous board states to detect changes
let prev_boards = boards
.values()
.map(|it| async move { it.info.read().await.clone() });
let prev_boards = join_all(prev_boards).await;
// Check all boards
for board in boards.values() {
if let Err(err) = board.check().await {
error!("failed to check board: {:?}", err);
}
}
// Get current board states after check
let current_boards = boards
.values()
.map(|it| async move { it.info.read().await.clone() });
let current_boards = join_all(current_boards).await;
drop(boards);
// Only send update if there are actual changes
let has_changes = prev_boards.len() != current_boards.len() ||
prev_boards.iter().zip(current_boards.iter()).any(|(prev, current)| {
prev.connect_status != current.connect_status ||
prev.ttl != current.ttl ||
prev.checked_at != current.checked_at
});
if has_changes {
let board_change_sender = self.boards_change_sender.clone();
if let Err(err) = board_change_sender.send(current_boards) {
error!("failed to send board change: {:?}", err);
}
drop(board_change_sender);
}
}
}
}

View File

@ -0,0 +1,520 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::io::Cursor;
use anyhow::Result;
use image::{ImageFormat, RgbaImage};
use tokio::sync::{broadcast, RwLock};
use tokio::time::sleep;
use tokio_tungstenite::{accept_async, tungstenite::Message};
use futures_util::{SinkExt, StreamExt};
use crate::screenshot::Screenshot;
use crate::screenshot_manager::ScreenshotManager;
#[derive(Debug, Clone)]
pub struct StreamConfig {
pub display_id: u32,
pub target_width: u32,
pub target_height: u32,
pub quality: u8, // JPEG quality 1-100
pub max_fps: u8, // Maximum frames per second
}
impl Default for StreamConfig {
fn default() -> Self {
Self {
display_id: 0,
target_width: 320, // Reduced from 400 for better performance
target_height: 180, // Reduced from 225 for better performance
quality: 50, // Reduced from 75 for faster compression
max_fps: 15,
}
}
}
#[derive(Debug, Clone)]
pub struct StreamFrame {
pub display_id: u32,
pub timestamp: Instant,
pub jpeg_data: Vec<u8>,
pub width: u32,
pub height: u32,
}
pub struct ScreenStreamManager {
streams: Arc<RwLock<HashMap<u32, Arc<RwLock<StreamState>>>>>,
}
struct StreamState {
config: StreamConfig,
subscribers: Vec<broadcast::Sender<StreamFrame>>,
last_frame: Option<StreamFrame>,
last_screenshot_hash: Option<u64>,
last_force_send: Instant,
is_running: bool,
}
impl ScreenStreamManager {
pub fn new() -> Self {
Self {
streams: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn start_stream(&self, config: StreamConfig) -> Result<broadcast::Receiver<StreamFrame>> {
let display_id = config.display_id;
let mut streams = self.streams.write().await;
if let Some(stream_state) = streams.get(&display_id) {
// Stream already exists, just add a new subscriber
let mut state = stream_state.write().await;
let (tx, rx) = broadcast::channel(10);
state.subscribers.push(tx);
return Ok(rx);
}
// Create new stream
let (tx, rx) = broadcast::channel(10);
let stream_state = Arc::new(RwLock::new(StreamState {
config: config.clone(),
subscribers: vec![tx],
last_frame: None,
last_screenshot_hash: None,
last_force_send: Instant::now(),
is_running: false,
}));
streams.insert(display_id, stream_state.clone());
drop(streams);
// Start the stream processing task
let streams_ref = self.streams.clone();
tokio::spawn(async move {
if let Err(e) = Self::run_stream(display_id, streams_ref).await {
log::error!("Stream {} error: {}", display_id, e);
}
});
Ok(rx)
}
async fn run_stream(display_id: u32, streams: Arc<RwLock<HashMap<u32, Arc<RwLock<StreamState>>>>>) -> Result<()> {
log::info!("Starting stream for display_id: {}", display_id);
let screenshot_manager = ScreenshotManager::global().await;
// If display_id is 0, try to get the first available display
let actual_display_id = if display_id == 0 {
// Get available displays and use the first one
let displays = display_info::DisplayInfo::all().map_err(|e| anyhow::anyhow!("Failed to get displays: {}", e))?;
if displays.is_empty() {
return Err(anyhow::anyhow!("No displays available"));
}
log::info!("Using first available display: {}", displays[0].id);
displays[0].id
} else {
display_id
};
log::info!("Attempting to subscribe to display_id: {}", actual_display_id);
let screenshot_rx = match screenshot_manager.subscribe_by_display_id(actual_display_id).await {
Ok(rx) => {
log::info!("Successfully subscribed to display_id: {}", actual_display_id);
rx
}
Err(e) => {
log::error!("Failed to subscribe to display_id {}: {}", actual_display_id, e);
return Err(e);
}
};
let mut screenshot_rx = screenshot_rx;
// Mark stream as running
{
let streams_lock = streams.read().await;
if let Some(stream_state) = streams_lock.get(&display_id) {
let mut state = stream_state.write().await;
state.is_running = true;
}
}
let mut last_process_time = Instant::now();
loop {
// Check if stream still has subscribers and is still running
let should_continue = {
let streams_lock = streams.read().await;
if let Some(stream_state) = streams_lock.get(&display_id) {
let state = stream_state.read().await;
!state.subscribers.is_empty() && state.is_running
} else {
false
}
};
if !should_continue {
break;
}
// Wait for new screenshot
if let Ok(_) = screenshot_rx.changed().await {
let screenshot = screenshot_rx.borrow().clone();
// Rate limiting based on max_fps
let config = {
let streams_lock = streams.read().await;
if let Some(stream_state) = streams_lock.get(&display_id) {
let state = stream_state.read().await;
state.config.clone()
} else {
break;
}
};
let min_interval = Duration::from_millis(1000 / config.max_fps as u64);
let elapsed = last_process_time.elapsed();
if elapsed < min_interval {
sleep(min_interval - elapsed).await;
}
// Process screenshot into JPEG frame
if let Ok(frame) = Self::process_screenshot(&screenshot, &config).await {
last_process_time = Instant::now();
// Check if frame content changed (simple hash comparison) or force send
let frame_hash = Self::calculate_frame_hash(&frame.jpeg_data);
let should_send = {
let streams_lock = streams.read().await;
if let Some(stream_state) = streams_lock.get(&display_id) {
let mut state = stream_state.write().await;
let changed = state.last_screenshot_hash.map_or(true, |hash| hash != frame_hash);
let elapsed_ms = state.last_force_send.elapsed().as_millis();
let force_send = elapsed_ms > 500; // Force send every 500ms for better CPU performance
if changed || force_send {
state.last_screenshot_hash = Some(frame_hash);
state.last_frame = Some(frame.clone());
if force_send {
state.last_force_send = Instant::now();
}
}
changed || force_send
} else {
false
}
};
if should_send {
// Send to all subscribers
let streams_lock = streams.read().await;
if let Some(stream_state) = streams_lock.get(&display_id) {
let state = stream_state.read().await;
for tx in state.subscribers.iter() {
if let Err(_) = tx.send(frame.clone()) {
log::warn!("Failed to send frame to subscriber for display_id: {}", display_id);
}
}
}
}
}
}
}
// Mark stream as stopped
{
let streams_lock = streams.read().await;
if let Some(stream_state) = streams_lock.get(&display_id) {
let mut state = stream_state.write().await;
state.is_running = false;
}
}
Ok(())
}
async fn process_screenshot(screenshot: &Screenshot, config: &StreamConfig) -> Result<StreamFrame> {
let total_start = Instant::now();
let bytes = screenshot.bytes.read().await;
// Convert BGRA to RGBA using unsafe with optimized batch processing for maximum performance
let mut rgba_bytes = bytes.as_ref().clone();
unsafe {
let ptr = rgba_bytes.as_mut_ptr() as *mut u32;
let len = rgba_bytes.len() / 4;
// Process in larger chunks of 64 for better cache efficiency and loop unrolling
let chunk_size = 64;
let full_chunks = len / chunk_size;
let remainder = len % chunk_size;
// Process full chunks with manual loop unrolling
for chunk_idx in 0..full_chunks {
let base_ptr = ptr.add(chunk_idx * chunk_size);
// Unroll the inner loop for better performance
for i in (0..chunk_size).step_by(4) {
// Process 4 pixels at once
let p0 = base_ptr.add(i).read();
let p1 = base_ptr.add(i + 1).read();
let p2 = base_ptr.add(i + 2).read();
let p3 = base_ptr.add(i + 3).read();
// BGRA (0xAABBGGRR) -> RGBA (0xAAGGBBRR)
let s0 = (p0 & 0xFF00FF00) | ((p0 & 0x00FF0000) >> 16) | ((p0 & 0x000000FF) << 16);
let s1 = (p1 & 0xFF00FF00) | ((p1 & 0x00FF0000) >> 16) | ((p1 & 0x000000FF) << 16);
let s2 = (p2 & 0xFF00FF00) | ((p2 & 0x00FF0000) >> 16) | ((p2 & 0x000000FF) << 16);
let s3 = (p3 & 0xFF00FF00) | ((p3 & 0x00FF0000) >> 16) | ((p3 & 0x000000FF) << 16);
base_ptr.add(i).write(s0);
base_ptr.add(i + 1).write(s1);
base_ptr.add(i + 2).write(s2);
base_ptr.add(i + 3).write(s3);
}
}
// Process remaining pixels
let remainder_start = full_chunks * chunk_size;
for i in 0..remainder {
let idx = remainder_start + i;
let pixel = ptr.add(idx).read();
let swapped = (pixel & 0xFF00FF00) | ((pixel & 0x00FF0000) >> 16) | ((pixel & 0x000000FF) << 16);
ptr.add(idx).write(swapped);
}
}
// Create image from raw bytes
let img = RgbaImage::from_raw(
screenshot.width,
screenshot.height,
rgba_bytes,
).ok_or_else(|| anyhow::anyhow!("Failed to create image from raw bytes"))?;
// Resize if needed
let final_img = if screenshot.width != config.target_width || screenshot.height != config.target_height {
image::imageops::resize(
&img,
config.target_width,
config.target_height,
image::imageops::FilterType::Nearest, // Fastest filter for real-time streaming
)
} else {
img
};
// Convert to JPEG
let mut jpeg_buffer = Vec::new();
let mut cursor = Cursor::new(&mut jpeg_buffer);
let rgb_img = image::DynamicImage::ImageRgba8(final_img).to_rgb8();
rgb_img.write_to(&mut cursor, ImageFormat::Jpeg)?;
let total_duration = total_start.elapsed();
log::debug!("Screenshot processed for display {} in {}ms, JPEG size: {} bytes",
config.display_id, total_duration.as_millis(), jpeg_buffer.len());
Ok(StreamFrame {
display_id: config.display_id,
timestamp: Instant::now(),
jpeg_data: jpeg_buffer,
width: config.target_width,
height: config.target_height,
})
}
fn calculate_frame_hash(data: &[u8]) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
// Sample every 100th byte for better sensitivity (was 1000)
for (i, &byte) in data.iter().enumerate() {
if i % 100 == 0 {
byte.hash(&mut hasher);
}
}
hasher.finish()
}
pub async fn stop_stream(&self, display_id: u32) {
log::info!("Stopping stream for display_id: {}", display_id);
let mut streams = self.streams.write().await;
if let Some(stream_state) = streams.get(&display_id) {
// Mark stream as not running to stop the processing task
let mut state = stream_state.write().await;
state.is_running = false;
log::info!("Marked stream as not running for display_id: {}", display_id);
}
// Remove the stream from the map
streams.remove(&display_id);
log::info!("Removed stream from manager for display_id: {}", display_id);
}
}
// Global instance
static SCREEN_STREAM_MANAGER: tokio::sync::OnceCell<ScreenStreamManager> = tokio::sync::OnceCell::const_new();
impl ScreenStreamManager {
pub async fn global() -> &'static Self {
SCREEN_STREAM_MANAGER.get_or_init(|| async {
ScreenStreamManager::new()
}).await
}
}
// WebSocket handler for screen streaming
pub async fn handle_websocket_connection(
stream: tokio::net::TcpStream,
) -> Result<()> {
log::info!("Accepting WebSocket connection...");
let ws_stream = match accept_async(stream).await {
Ok(ws) => {
log::info!("WebSocket handshake completed successfully");
ws
}
Err(e) => {
log::error!("WebSocket handshake failed: {}", e);
return Err(e.into());
}
};
let (ws_sender, mut ws_receiver) = ws_stream.split();
log::info!("WebSocket connection established, waiting for configuration...");
// Wait for the first configuration message
let config = loop {
// Add timeout to prevent hanging
let timeout_duration = tokio::time::Duration::from_secs(10);
match tokio::time::timeout(timeout_duration, ws_receiver.next()).await {
Ok(Some(msg)) => {
match msg {
Ok(Message::Text(text)) => {
log::info!("Received configuration message: {}", text);
if let Ok(config_json) = serde_json::from_str::<serde_json::Value>(&text) {
// Parse configuration from JSON
let display_id = config_json.get("display_id")
.and_then(|v| v.as_u64())
.unwrap_or(0) as u32;
let width = config_json.get("width")
.and_then(|v| v.as_u64())
.unwrap_or(320) as u32; // Reduced from 400 for better performance
let height = config_json.get("height")
.and_then(|v| v.as_u64())
.unwrap_or(180) as u32; // Reduced from 225 for better performance
let quality = config_json.get("quality")
.and_then(|v| v.as_u64())
.unwrap_or(50) as u8; // Reduced from 75 for faster compression
let config = StreamConfig {
display_id,
target_width: width,
target_height: height,
quality,
max_fps: 15,
};
log::info!("Parsed stream config: display_id={}, width={}, height={}, quality={}",
display_id, width, height, quality);
break config;
} else {
log::warn!("Failed to parse configuration JSON: {}", text);
}
}
Ok(Message::Close(_)) => {
log::info!("WebSocket connection closed before configuration");
return Ok(());
}
Err(e) => {
log::warn!("WebSocket error while waiting for config: {}", e);
return Err(e.into());
}
_ => {}
}
}
Ok(None) => {
log::warn!("WebSocket connection closed while waiting for configuration");
return Ok(());
}
Err(_) => {
log::warn!("Timeout waiting for WebSocket configuration message");
return Err(anyhow::anyhow!("Timeout waiting for configuration"));
}
}
};
// Start the stream with the received configuration
log::info!("Starting stream with config: display_id={}, width={}, height={}",
config.display_id, config.target_width, config.target_height);
let stream_manager = ScreenStreamManager::global().await;
let display_id_for_cleanup = config.display_id;
let mut frame_rx = match stream_manager.start_stream(config).await {
Ok(rx) => {
log::info!("Screen stream started successfully");
rx
}
Err(e) => {
log::error!("Failed to start screen stream: {}", e);
return Err(e);
}
};
// Handle incoming WebSocket messages (for control)
let ws_sender = Arc::new(tokio::sync::Mutex::new(ws_sender));
let ws_sender_clone = ws_sender.clone();
// Task to handle outgoing frames
let frame_task = tokio::spawn(async move {
while let Ok(frame) = frame_rx.recv().await {
let mut sender = ws_sender_clone.lock().await;
match sender.send(Message::Binary(frame.jpeg_data)).await {
Ok(_) => {},
Err(e) => {
log::warn!("Failed to send frame: {}", e);
break;
}
}
}
log::info!("Frame sending task completed");
});
// Task to handle incoming messages
let control_task = tokio::spawn(async move {
while let Some(msg) = ws_receiver.next().await {
match msg {
Ok(Message::Text(text)) => {
log::info!("Received control message: {}", text);
// Additional configuration updates could be handled here
}
Ok(Message::Close(_)) => {
log::info!("WebSocket connection closed");
break;
}
Err(e) => {
log::warn!("WebSocket error: {}", e);
break;
}
_ => {}
}
}
log::info!("Control message task completed");
});
// Wait for either task to complete
tokio::select! {
_ = frame_task => {},
_ = control_task => {},
}
// Clean up resources when connection ends
log::info!("WebSocket connection ending, cleaning up resources for display_id: {}", display_id_for_cleanup);
let stream_manager = ScreenStreamManager::global().await;
stream_manager.stop_stream(display_id_for_cleanup).await;
log::info!("WebSocket connection handler completed");
Ok(())
}

View File

@ -1,20 +1,35 @@
use std::cell::RefCell;
use std::{iter, cell::Ref};
use std::fmt::Formatter;
use std::{iter, fmt::Debug};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use tauri::async_runtime::{RwLock, Mutex};
use tauri::async_runtime::RwLock;
use crate::{ambient_light::LedStripConfig, led_color::LedColor};
#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct Screenshot {
pub display_id: u32,
pub height: u32,
pub width: u32,
pub bytes_per_row: usize,
pub bytes: Arc<RwLock<Vec<u8>>>,
pub bytes: Arc<RwLock<Arc<Vec<u8>>>>,
pub scale_factor: f32,
pub bound_scale_factor: f32,
}
impl Debug for Screenshot {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Screenshot")
.field("display_id", &self.display_id)
.field("height", &self.height)
.field("width", &self.width)
.field("bytes_per_row", &self.bytes_per_row)
.field("scale_factor", &self.scale_factor)
.field("bound_scale_factor", &self.bound_scale_factor)
.finish()
}
}
static SINGLE_AXIS_POINTS: usize = 5;
@ -25,8 +40,9 @@ impl Screenshot {
height: u32,
width: u32,
bytes_per_row: usize,
bytes: Vec<u8>,
bytes: Arc<Vec<u8>>,
scale_factor: f32,
bound_scale_factor: f32,
) -> Self {
Self {
display_id,
@ -35,12 +51,15 @@ impl Screenshot {
bytes_per_row,
bytes: Arc::new(RwLock::new(bytes)),
scale_factor,
bound_scale_factor,
}
}
pub fn get_sample_points(&self, config: &LedStripConfig) -> Vec<LedSamplePoints> {
let height = self.height as usize;
let width = self.width as usize;
// let height = CGDisplay::new(self.display_id).bounds().size.height as usize;
// let width = CGDisplay::new(self.display_id).bounds().size.width as usize;
match config.border {
crate::ambient_light::Border::Top => {
@ -126,9 +145,16 @@ impl Screenshot {
for (x, y) in led_points {
// log::info!("x: {}, y: {}, bytes_per_row: {}", x, y, bytes_per_row);
let position = x * 4 + y * bytes_per_row;
// Add bounds checking to prevent index out of bounds
if position + 2 < bitmap.len() {
b += bitmap[position] as f64;
g += bitmap[position + 1] as f64;
r += bitmap[position + 2] as f64;
} else {
// Skip invalid positions or use default values
log::warn!("Invalid pixel position: x={}, y={}, position={}, bitmap_len={}", x, y, position, bitmap.len());
}
}
let color = LedColor::new((r / len) as u8, (g / len) as u8, (b / len) as u8);
colors.push(color);
@ -150,9 +176,17 @@ impl Screenshot {
for (x, y) in led_points {
// log::info!("x: {}, y: {}, bytes_per_row: {}", x, y, bytes_per_row);
let position = x * 4 + y * bytes_per_row;
// Add bounds checking to prevent index out of bounds
if position + 2 < bitmap.len() as usize {
b += bitmap[position] as f64;
g += bitmap[position + 1] as f64;
r += bitmap[position + 2] as f64;
} else {
// Skip invalid positions or use default values
log::warn!("Invalid pixel position in CG image: x={}, y={}, position={}, bitmap_len={}", x, y, position, bitmap.len());
}
// log::info!("position: {}, total: {}", position, bitmap.len());
}
let color = LedColor::new((r / len) as u8, (g / len) as u8, (b / len) as u8);
colors.push(color);

View File

@ -1,61 +1,31 @@
use std::cell::{Ref, RefCell};
use std::time::Duration;
use std::{collections::HashMap, sync::Arc};
use core_graphics::display::{
kCGNullWindowID, kCGWindowImageDefault, kCGWindowListOptionOnScreenOnly, CGDisplay,
};
use core_graphics::geometry::{CGPoint, CGRect, CGSize};
use paris::warn;
use paris::{info, warn};
use screen_capture_kit::shareable_content::{SCDisplay, SCShareableContent};
use screen_capture_kit::stream::{SCStream, SCStreamConfiguration, SCContentFilter, SCStreamOutput};
use screen_capture_kit::stream::SCStreamDelegate;
use tauri::async_runtime::RwLock;
use tokio::sync::{broadcast, watch, OnceCell};
use tokio::time::{self, Duration};
use tokio::task::yield_now;
use tokio::time::sleep;
use crate::screenshot::LedSamplePoints;
use crate::{
ambient_light::{SamplePointConfig, SamplePointMapper},
led_color::LedColor,
screenshot::{ScreenSamplePoints, Screenshot},
};
pub fn take_screenshot(display_id: u32, scale_factor: f32) -> anyhow::Result<Screenshot> {
log::debug!("take_screenshot");
let cg_display = CGDisplay::new(display_id);
let cg_image = CGDisplay::screenshot(
cg_display.bounds(),
kCGWindowListOptionOnScreenOnly,
kCGNullWindowID,
kCGWindowImageDefault,
)
.ok_or_else(|| anyhow::anyhow!("Display#{}: take screenshot failed", display_id))?;
let buffer = cg_image.data();
let bytes_per_row = cg_image.bytes_per_row();
let height = cg_image.height();
let width = cg_image.width();
let bytes = buffer.bytes().to_owned();
Ok(Screenshot::new(
display_id,
height as u32,
width as u32,
bytes_per_row,
bytes,
scale_factor,
))
}
use crate::{ambient_light::SamplePointMapper, led_color::LedColor, screenshot::Screenshot};
pub fn get_display_colors(
display_id: u32,
sample_points: &Vec<Vec<LedSamplePoints>>,
bound_scale_factor: f32,
) -> anyhow::Result<Vec<LedColor>> {
log::debug!("take_screenshot");
let cg_display = CGDisplay::new(display_id);
let mut colors = vec![];
let start_at = std::time::Instant::now();
for points in sample_points {
if points.len() == 0 {
continue;
@ -69,14 +39,23 @@ pub fn get_display_colors(
let (start_y, end_y) = (usize::min(start_y, end_y), usize::max(start_y, end_y));
let origin = CGPoint {
x: start_x as f64 + cg_display.bounds().origin.x,
y: start_y as f64 + cg_display.bounds().origin.y,
x: start_x as f64 * bound_scale_factor as f64 + cg_display.bounds().origin.x,
y: start_y as f64 * bound_scale_factor as f64 + cg_display.bounds().origin.y,
};
let size = CGSize {
width: (end_x - start_x + 1) as f64,
height: (end_y - start_y + 1) as f64,
};
// log::info!(
// "origin: {:?}, size: {:?}, start_x: {}, start_y: {}, bounds: {:?}",
// origin,
// size,
// start_x,
// start_y,
// cg_display.bounds().size
// );
let cg_image = CGDisplay::screenshot(
CGRect::new(&origin, &size),
kCGWindowListOptionOnScreenOnly,
@ -102,18 +81,11 @@ pub fn get_display_colors(
colors.append(&mut part_colors);
}
// if display_id == 4849664 {
// log::info!(
// "======= get_display_colors {} took {}ms",
// display_id,
// start_at.elapsed().as_millis()
// );
// }
Ok(colors)
}
pub struct ScreenshotManager {
pub channels: Arc<RwLock<HashMap<u32, watch::Receiver<Screenshot>>>>,
pub channels: Arc<RwLock<HashMap<u32, Arc<RwLock<watch::Sender<Screenshot>>>>>>,
merged_screenshot_tx: Arc<RwLock<broadcast::Sender<Screenshot>>>,
}
@ -133,90 +105,139 @@ impl ScreenshotManager {
.await
}
pub fn start(&self) -> anyhow::Result<()> {
pub async fn start(&self) -> anyhow::Result<()> {
let displays = display_info::DisplayInfo::all()?;
for display in displays {
self.start_one(display.id, display.scale_factor)?;
}
Ok(())
log::info!("ScreenshotManager starting with {} displays:", displays.len());
for display in &displays {
log::info!(" Display ID: {}, Scale: {}", display.id, display.scale_factor);
}
fn start_one(&self, display_id: u32, scale_factor: f32) -> anyhow::Result<()> {
let channels = self.channels.to_owned();
let merged_screenshot_tx = self.merged_screenshot_tx.clone();
tokio::spawn(async move {
let screenshot = take_screenshot(display_id, scale_factor);
if screenshot.is_err() {
warn!("take_screenshot_loop: {}", screenshot.err().unwrap());
return;
}
let mut interval = time::interval(Duration::from_millis(3300));
let mut start = tokio::time::Instant::now();
let screenshot = screenshot.unwrap();
let (screenshot_tx, screenshot_rx) = watch::channel(screenshot);
{
let channels = channels.clone();
let mut channels = channels.write().await;
channels.insert(display_id, screenshot_rx.clone());
}
let merged_screenshot_tx = merged_screenshot_tx.read().await.clone();
loop {
start = tokio::time::Instant::now();
Self::take_screenshot_loop(
display_id,
scale_factor,
&screenshot_tx,
&merged_screenshot_tx,
)
.await;
interval.tick().await;
tokio::time::sleep(Duration::from_millis(1)).await;
}
let futures = displays.iter().map(|display| async {
self.start_one(display.id, display.scale_factor)
.await
.unwrap_or_else(|err| {
warn!("start_one failed: display_id: {}, err: {}", display.id, err);
});
});
futures::future::join_all(futures).await;
log::info!("ScreenshotManager started successfully");
Ok(())
}
async fn take_screenshot_loop(
display_id: u32,
scale_factor: f32,
screenshot_tx: &watch::Sender<Screenshot>,
merged_screenshot_tx: &broadcast::Sender<Screenshot>,
) {
let screenshot = take_screenshot(display_id, scale_factor);
if let Ok(screenshot) = screenshot {
match merged_screenshot_tx.send(screenshot.clone()) {
Ok(_) => {}
async fn start_one(&self, display_id: u32, scale_factor: f32) -> anyhow::Result<()> {
log::info!("Starting screenshot capture for display_id: {}", display_id);
let merged_screenshot_tx = self.merged_screenshot_tx.clone();
let (tx, _) = watch::channel(Screenshot::new(
display_id,
0,
0,
0,
Arc::new(vec![]),
scale_factor,
scale_factor,
));
let tx = Arc::new(RwLock::new(tx));
let mut channels = self.channels.write().await;
channels.insert(display_id, tx.clone());
drop(channels);
// Implement screen capture using screen-capture-kit
loop {
match Self::capture_display_screenshot(display_id, scale_factor).await {
Ok(screenshot) => {
let tx_for_send = tx.read().await;
let merged_screenshot_tx = merged_screenshot_tx.write().await;
if let Err(err) = merged_screenshot_tx.send(screenshot.clone()) {
// log::warn!("merged_screenshot_tx.send failed: {}", err);
}
if let Err(err) = tx_for_send.send(screenshot.clone()) {
log::warn!("display {} screenshot_tx.send failed: {}", display_id, err);
}
}
Err(err) => {
// warn!("take_screenshot_loop: merged_screenshot_tx.send failed. display#{}. err: {}", display_id, err);
warn!("Failed to capture screenshot for display {}: {}", display_id, err);
// Create a fallback empty screenshot to maintain the interface
let screenshot = Screenshot::new(
display_id,
1080,
1920,
1920 * 4, // Assuming RGBA format
Arc::new(vec![0u8; 1920 * 1080 * 4]),
scale_factor,
scale_factor,
);
let tx_for_send = tx.read().await;
let merged_screenshot_tx = merged_screenshot_tx.write().await;
if let Err(err) = merged_screenshot_tx.send(screenshot.clone()) {
// log::warn!("merged_screenshot_tx.send failed: {}", err);
}
if let Err(err) = tx_for_send.send(screenshot.clone()) {
log::warn!("display {} screenshot_tx.send failed: {}", display_id, err);
}
screenshot_tx.send(screenshot).unwrap();
// log::info!("take_screenshot_loop: send success. display#{}", display_id)
} else {
warn!("take_screenshot_loop: {}", screenshot.err().unwrap());
}
}
pub async fn get_all_colors(
&self,
configs: &Vec<SamplePointConfig>,
screenshots: &Vec<&Screenshot>,
) -> Vec<LedColor> {
let mut all_colors = vec![];
for (index, screenshot) in screenshots.iter().enumerate() {
let config = &configs[index];
let mut colors = screenshot.get_colors_by_sample_points(&config.points).await;
all_colors.append(&mut colors);
// Sleep for a frame duration (5 FPS for much better CPU performance)
sleep(Duration::from_millis(200)).await;
yield_now().await;
}
}
all_colors
async fn capture_display_screenshot(display_id: u32, scale_factor: f32) -> anyhow::Result<Screenshot> {
// For now, use the existing CGDisplay approach as a fallback
// TODO: Implement proper screen-capture-kit integration
let cg_display = CGDisplay::new(display_id);
let bounds = cg_display.bounds();
let cg_image = CGDisplay::screenshot(
bounds,
kCGWindowListOptionOnScreenOnly,
kCGNullWindowID,
kCGWindowImageDefault,
)
.ok_or_else(|| anyhow::anyhow!("Display#{}: take screenshot failed - possibly no screen recording permission", display_id))?;
let bitmap = cg_image.data();
let width = cg_image.width() as u32;
let height = cg_image.height() as u32;
let bytes_per_row = cg_image.bytes_per_row();
// Convert CFData to Vec<u8>
let data_ptr = bitmap.bytes().as_ptr();
let data_len = bitmap.len() as usize;
let screenshot_data = unsafe {
std::slice::from_raw_parts(data_ptr, data_len).to_vec()
};
Ok(Screenshot::new(
display_id,
height,
width,
bytes_per_row,
Arc::new(screenshot_data),
scale_factor,
scale_factor,
))
}
pub fn get_sorted_colors(colors: &Vec<u8>, mappers: &Vec<SamplePointMapper>) -> Vec<u8> {
@ -271,4 +292,16 @@ impl ScreenshotManager {
pub async fn clone_merged_screenshot_rx(&self) -> broadcast::Receiver<Screenshot> {
self.merged_screenshot_tx.read().await.subscribe()
}
pub async fn subscribe_by_display_id(
&self,
display_id: u32,
) -> anyhow::Result<watch::Receiver<Screenshot>> {
let channels = self.channels.read().await;
if let Some(tx) = channels.get(&display_id) {
Ok(tx.read().await.subscribe())
} else {
Err(anyhow::anyhow!("display_id: {} not found", display_id))
}
}
}

View File

@ -0,0 +1,203 @@
use std::{mem, sync::Arc};
use coreaudio::{
audio_unit::macos_helpers::get_default_device_id,
sys::{
kAudioHardwareServiceDeviceProperty_VirtualMasterVolume, kAudioObjectPropertyScopeOutput,
AudioObjectGetPropertyData, AudioObjectHasProperty, AudioObjectPropertyAddress,
AudioObjectSetPropertyData,
},
};
use paris::error;
use tokio::sync::{OnceCell, RwLock};
use crate::rpc::BoardMessageChannels;
pub struct VolumeManager {
current_volume: Arc<RwLock<f32>>,
handler: Option<tokio::task::JoinHandle<()>>,
read_handler: Option<tokio::task::JoinHandle<()>>,
}
impl VolumeManager {
pub async fn global() -> &'static Self {
static VOLUME_MANAGER: OnceCell<VolumeManager> = OnceCell::const_new();
VOLUME_MANAGER
.get_or_init(|| async { Self::create() })
.await
}
pub fn create() -> Self {
let mut instance = Self {
current_volume: Arc::new(RwLock::new(0.0)),
handler: None,
read_handler: None,
};
instance.subscribe_volume_setting_request();
instance.auto_read_volume();
instance
}
fn subscribe_volume_setting_request(&mut self) {
let handler = tokio::spawn(async {
let channels = BoardMessageChannels::global().await;
let mut request_rx = channels.volume_setting_request_sender.subscribe();
while let Ok(volume) = request_rx.recv().await {
if let Err(err) = Self::set_volume(volume) {
error!("failed to set volume: {}", err);
}
}
});
self.handler = Some(handler);
}
fn auto_read_volume(&mut self) {
let current_volume = self.current_volume.clone();
let handler = tokio::spawn(async move {
let channel = BoardMessageChannels::global().await;
let volume_changed_tx = channel.volume_changed_sender.clone();
loop {
match Self::read_volume() {
Ok(value) => {
let mut volume = current_volume.write().await;
if *volume != value {
if let Err(err) = volume_changed_tx.send(value) {
error!("failed to send volume changed event: {}", err);
}
}
*volume = value;
}
Err(err) => {
error!("failed to read volume: {}", err);
}
}
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
}
});
self.read_handler = Some(handler);
}
fn set_volume(volume: f32) -> anyhow::Result<()> {
log::debug!("set volume: {}", volume);
let device_id = get_default_device_id(false);
if device_id.is_none() {
anyhow::bail!("default audio output device is not found.");
}
let device_id = device_id.unwrap();
let address = AudioObjectPropertyAddress {
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
mScope: kAudioObjectPropertyScopeOutput,
mElement: 0,
};
log::debug!("device id: {}", device_id);
log::debug!("address: {:?}", address);
if 0 == unsafe { AudioObjectHasProperty(device_id, &address) } {
anyhow::bail!("Can not get audio property");
}
let size = mem::size_of::<f32>() as u32;
let result = unsafe {
AudioObjectSetPropertyData(
device_id,
&address,
0,
std::ptr::null(),
size,
&volume as *const f32 as *const std::ffi::c_void,
)
};
if result != 0 {
anyhow::bail!("Can not set audio property");
}
Ok(())
}
fn read_volume() -> anyhow::Result<f32> {
let device_id = get_default_device_id(false);
if device_id.is_none() {
anyhow::bail!("default audio output device is not found.");
}
let device_id = device_id.unwrap();
let address = AudioObjectPropertyAddress {
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
mScope: kAudioObjectPropertyScopeOutput,
mElement: 0,
};
log::debug!("device id: {}", device_id);
log::debug!("address: {:?}", address);
if 0 == unsafe { AudioObjectHasProperty(device_id, &address) } {
anyhow::bail!("Can not get audio property");
}
let mut size = mem::size_of::<f32>() as u32;
let mut volume = 0.0f32;
let result = unsafe {
AudioObjectGetPropertyData(
device_id,
&address,
0,
std::ptr::null(),
&mut size,
&mut volume as *mut f32 as *mut std::ffi::c_void,
)
};
if result != 0 {
anyhow::bail!("Can not get audio property. result: {}", result);
}
if size != mem::size_of::<f32>() as u32 {
anyhow::bail!("Can not get audio property. data size is not matched.");
}
log::debug!("current system volume of primary device: {}", volume);
Ok(volume)
}
pub async fn get_volume(&self) -> f32 {
self.current_volume.read().await.clone()
}
}
impl Drop for VolumeManager {
fn drop(&mut self) {
log::info!("drop volume manager");
if let Some(handler) = self.handler.take() {
tokio::task::block_in_place(move || {
handler.abort();
});
}
if let Some(handler) = self.read_handler.take() {
tokio::task::block_in_place(move || {
handler.abort();
});
}
}
}

View File

@ -0,0 +1,3 @@
mod manager;
pub use manager::*;

View File

@ -1,23 +1,34 @@
{
"$schema": "https://schema.tauri.app/config/2.0.0",
"productName": "Ambient Light Control",
"version": "2.0.0-alpha",
"identifier": "cc.ivanli.ambient-light.desktop",
"build": {
"beforeDevCommand": "pnpm dev",
"beforeBuildCommand": "pnpm build",
"devPath": "http://localhost:1420",
"distDir": "../dist",
"withGlobalTauri": false
"devUrl": "http://localhost:1420",
"frontendDist": "../dist"
},
"package": {
"productName": "test-demo",
"version": "0.0.1"
},
"tauri": {
"allowlist": {
"all": false,
"shell": {
"all": false,
"open": true
"app": {
"withGlobalTauri": true,
"security": {
"csp": null,
"assetProtocol": {
"scope": [
"**"
]
}
},
"windows": [
{
"fullscreen": false,
"resizable": true,
"title": "Ambient Light Control",
"width": 800,
"height": 600
}
]
},
"bundle": {
"active": true,
"icon": [
@ -27,23 +38,9 @@
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "cc.ivanli.ambient-light.desktop",
"targets": "all"
},
"security": {
"csp": null
},
"updater": {
"active": false
},
"windows": [
{
"fullscreen": false,
"resizable": true,
"title": "test-demo",
"width": 800,
"height": 600
}
]
"targets": "all",
"macOS": {
"minimumSystemVersion": "13"
}
}
}

View File

@ -1,104 +1,120 @@
import { createEffect, onCleanup } from 'solid-js';
import { invoke } from '@tauri-apps/api/tauri';
import { DisplayView } from './components/display-view';
import { DisplayListContainer } from './components/display-list-container';
import { displayStore, setDisplayStore } from './stores/display.store';
import { LedStripConfigContainer } from './models/led-strip-config';
import { Routes, Route, useLocation, A } from '@solidjs/router';
import { LedStripConfiguration } from './components/led-strip-configuration/led-strip-configuration';
import { WhiteBalance } from './components/white-balance/white-balance';
import { LedStripTest } from './components/led-strip-test/led-strip-test';
import { createEffect, createSignal } from 'solid-js';
import { invoke } from '@tauri-apps/api/core';
import { setLedStripStore } from './stores/led-strip.store';
import { listen } from '@tauri-apps/api/event';
import { LedStripPartsSorter } from './components/led-strip-parts-sorter';
import { createStore } from 'solid-js/store';
import {
LedStripConfigurationContext,
LedStripConfigurationContextType,
} from './contexts/led-strip-configuration.context';
import { LedStripConfigContainer } from './models/led-strip-config';
import { InfoIndex } from './components/info/info-index';
import { DisplayStateIndex } from './components/displays/display-state-index';
import { useLanguage } from './i18n/index';
function App() {
const location = useLocation();
const [previousPath, setPreviousPath] = createSignal<string>('');
const { t, locale, setLocale } = useLanguage();
// Monitor route changes and cleanup LED tests when leaving the test page
createEffect(() => {
invoke<string>('list_display_info').then((displays) => {
setDisplayStore({
displays: JSON.parse(displays),
});
});
invoke<LedStripConfigContainer>('read_led_strip_configs').then((configs) => {
console.log(configs);
setLedStripStore(configs);
const currentPath = location.pathname;
const prevPath = previousPath();
// Check if we're leaving the LED test page
const isLeavingTestPage = prevPath === '/led-strip-test' && currentPath !== '/led-strip-test';
if (isLeavingTestPage) {
// The LED test component will handle stopping the test effect via onCleanup
// We just need to ensure test mode is disabled to resume normal LED publishing
invoke('disable_test_mode').catch((error) => {
console.error('Failed to disable test mode:', error);
});
}
// Update previousPath after the condition check
setPreviousPath(currentPath);
});
// listen to config_changed event
createEffect(() => {
const unlisten = listen('config_changed', (event) => {
const { strips, mappers } = event.payload as LedStripConfigContainer;
console.log(event.payload);
invoke<LedStripConfigContainer>('read_config').then((config) => {
setLedStripStore({
strips,
mappers,
strips: config.strips,
mappers: config.mappers,
colorCalibration: config.color_calibration,
});
}).catch((error) => {
console.error('Failed to read config:', error);
});
});
onCleanup(() => {
unlisten.then((unlisten) => unlisten());
});
});
// listen to led_colors_changed event
createEffect(() => {
const unlisten = listen<Uint8ClampedArray>('led_colors_changed', (event) => {
const colors = event.payload;
setLedStripStore({
colors,
});
});
onCleanup(() => {
unlisten.then((unlisten) => unlisten());
});
});
// listen to led_sorted_colors_changed event
createEffect(() => {
const unlisten = listen<Uint8ClampedArray>('led_sorted_colors_changed', (event) => {
const sortedColors = event.payload;
setLedStripStore({
sortedColors,
});
});
onCleanup(() => {
unlisten.then((unlisten) => unlisten());
});
});
const [ledStripConfiguration, setLedStripConfiguration] = createStore<
LedStripConfigurationContextType[0]
>({
selectedStripPart: null,
});
const ledStripConfigurationContextValue: LedStripConfigurationContextType = [
ledStripConfiguration,
{
setSelectedStripPart: (v) => {
setLedStripConfiguration({
selectedStripPart: v,
});
},
},
];
return (
<div>
<LedStripConfigurationContext.Provider value={ledStripConfigurationContextValue}>
<LedStripPartsSorter />
<DisplayListContainer>
{displayStore.displays.map((display) => {
return <DisplayView display={display} />;
})}
</DisplayListContainer>
</LedStripConfigurationContext.Provider>
<div class="h-screen bg-base-100 flex flex-col" data-theme="dark">
{/* Fixed Navigation */}
<div class="navbar bg-base-200 shadow-lg flex-shrink-0 z-50">
<div class="navbar-start">
<div class="dropdown dropdown-hover">
<div tabindex="0" role="button" class="btn btn-ghost lg:hidden">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16"></path>
</svg>
</div>
<ul class="menu menu-sm dropdown-content z-[100] p-2 shadow bg-base-100 rounded-box w-52 border border-base-300">
<li><A href="/info" class="text-base-content hover:bg-base-200">{t('nav.info')}</A></li>
<li><A href="/displays" class="text-base-content hover:bg-base-200">{t('nav.displays')}</A></li>
<li><A href="/led-strips-configuration" class="text-base-content hover:bg-base-200">{t('nav.ledConfiguration')}</A></li>
<li><A href="/white-balance" class="text-base-content hover:bg-base-200">{t('nav.whiteBalance')}</A></li>
<li><A href="/led-strip-test" class="text-base-content hover:bg-base-200">{t('nav.ledTest')}</A></li>
</ul>
</div>
<a class="btn btn-ghost text-xl text-primary font-bold">{t('nav.title')}</a>
</div>
<div class="navbar-center hidden lg:flex">
<ul class="menu menu-horizontal px-1">
<li><A href="/info" class="btn btn-ghost text-base-content hover:text-primary">{t('nav.info')}</A></li>
<li><A href="/displays" class="btn btn-ghost text-base-content hover:text-primary">{t('nav.displays')}</A></li>
<li><A href="/led-strips-configuration" class="btn btn-ghost text-base-content hover:text-primary">{t('nav.ledConfiguration')}</A></li>
<li><A href="/white-balance" class="btn btn-ghost text-base-content hover:text-primary">{t('nav.whiteBalance')}</A></li>
<li><A href="/led-strip-test" class="btn btn-ghost text-base-content hover:text-primary">{t('nav.ledTest')}</A></li>
</ul>
</div>
<div class="navbar-end">
<div class="dropdown dropdown-end dropdown-hover">
<div tabindex="0" role="button" class="btn btn-ghost btn-sm">
{locale() === 'zh-CN' ? '中文' : 'English'}
</div>
<ul class="dropdown-content z-[100] menu p-2 shadow bg-base-100 rounded-box w-32 border border-base-300">
<li>
<button
class={`${locale() === 'zh-CN' ? 'active' : ''}`}
onClick={() => setLocale('zh-CN')}
>
</button>
</li>
<li>
<button
class={`${locale() === 'en-US' ? 'active' : ''}`}
onClick={() => setLocale('en-US')}
>
English
</button>
</li>
</ul>
</div>
<div class="badge badge-primary badge-outline ml-2">v1.0</div>
</div>
</div>
{/* Main Content - fills remaining height */}
<main class="flex-1 container mx-auto px-2 sm:px-4 py-4 max-w-full overflow-x-auto min-h-0">
<Routes>
<Route path="/info" component={InfoIndex} />
<Route path="/displays" component={DisplayStateIndex} />
<Route path="/led-strips-configuration" component={LedStripConfiguration} />
<Route path="/white-balance" component={WhiteBalance} />
<Route path="/led-strip-test" element={<LedStripTest />} />
</Routes>
</main>
</div>
);
}

View File

@ -1,42 +0,0 @@
import { Component, JSX, ParentComponent, splitProps } from 'solid-js';
import { DisplayInfo } from '../models/display-info.model';
type DisplayInfoItemProps = {
label: string;
};
export const DisplayInfoItem: ParentComponent<DisplayInfoItemProps> = (props) => {
return (
<dl class="px-3 py-1 flex hover:bg-slate-900/50 gap-2 text-white drop-shadow-[0_2px_2px_rgba(0,0,0,0.8)] rounded">
<dt class="uppercase w-1/2 select-all whitespace-nowrap">{props.label}</dt>
<dd class="select-all w-1/2 whitespace-nowrap">{props.children}</dd>
</dl>
);
};
type DisplayInfoPanelProps = {
display: DisplayInfo;
} & JSX.HTMLAttributes<HTMLElement>;
export const DisplayInfoPanel: Component<DisplayInfoPanelProps> = (props) => {
const [localProps, rootProps] = splitProps(props, ['display']);
return (
<section {...rootProps} class={'m-2 flex flex-col gap-1 py-2 ' + rootProps.class}>
<DisplayInfoItem label="ID">
<code>{localProps.display.id}</code>
</DisplayInfoItem>
<DisplayInfoItem label="Position">
({localProps.display.x}, {localProps.display.y})
</DisplayInfoItem>
<DisplayInfoItem label="Size">
{localProps.display.width} x {localProps.display.height}
</DisplayInfoItem>
<DisplayInfoItem label="Scale Factor">
{localProps.display.scale_factor}
</DisplayInfoItem>
<DisplayInfoItem label="is Primary">
{localProps.display.is_primary ? 'True' : 'False'}
</DisplayInfoItem>
</section>
);
};

View File

@ -0,0 +1,71 @@
import { Component, ParentComponent } from 'solid-js';
import { DisplayState } from '../../models/display-state.model';
import { useLanguage } from '../../i18n/index';
type DisplayStateCardProps = {
state: DisplayState;
};
type ItemProps = {
label: string;
};
const Item: ParentComponent<ItemProps> = (props) => {
return (
<div class="flex justify-between items-center py-1">
<dt class="text-sm font-medium text-base-content/70">{props.label}</dt>
<dd class="text-sm font-mono text-base-content">{props.children}</dd>
</div>
);
};
export const DisplayStateCard: Component<DisplayStateCardProps> = (props) => {
const { t } = useLanguage();
return (
<div class="card bg-base-200 shadow-lg hover:shadow-xl transition-shadow duration-200">
<div class="card-body p-4">
<div class="card-title text-base mb-3 flex items-center justify-between">
<span>{t('displays.title')}</span>
<div class="badge badge-primary badge-outline">{t('common.realtime')}</div>
</div>
<div class="grid grid-cols-1 gap-3">
{/* 亮度信息 */}
<div class="bg-base-100 rounded-lg p-3">
<h4 class="text-sm font-semibold text-base-content mb-2">{t('displays.brightnessSettings')}</h4>
<div class="space-y-1">
<Item label={t('displays.currentBrightness')}>{props.state.brightness}</Item>
<Item label={t('displays.maxBrightness')}>{props.state.max_brightness}</Item>
<Item label={t('displays.minBrightness')}>{props.state.min_brightness}</Item>
</div>
</div>
{/* 对比度信息 */}
<div class="bg-base-100 rounded-lg p-3">
<h4 class="text-sm font-semibold text-base-content mb-2">{t('displays.contrastSettings')}</h4>
<div class="space-y-1">
<Item label={t('displays.currentContrast')}>{props.state.contrast}</Item>
<Item label={t('displays.maxContrast')}>{props.state.max_contrast}</Item>
<Item label={t('displays.minContrast')}>{props.state.min_contrast}</Item>
</div>
</div>
{/* 模式信息 */}
<div class="bg-base-100 rounded-lg p-3">
<h4 class="text-sm font-semibold text-base-content mb-2">{t('displays.modeSettings')}</h4>
<div class="space-y-1">
<Item label={t('displays.currentMode')}>{props.state.mode}</Item>
<Item label={t('displays.maxMode')}>{props.state.max_mode}</Item>
<Item label={t('displays.minMode')}>{props.state.min_mode}</Item>
</div>
</div>
{/* 更新时间 */}
<div class="text-xs text-base-content/50 text-center pt-2 border-t border-base-300">
{t('displays.lastModified')}: {props.state.last_modified_at.toLocaleString()}
</div>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,74 @@
import { Component, For, createEffect, createSignal } from 'solid-js';
import { listen } from '@tauri-apps/api/event';
import debug from 'debug';
import { invoke } from '@tauri-apps/api/core';
import { DisplayState, RawDisplayState } from '../../models/display-state.model';
import { DisplayStateCard } from './display-state-card';
import { useLanguage } from '../../i18n/index';
const logger = debug('app:components:displays:display-state-index');
export const DisplayStateIndex: Component = () => {
const [states, setStates] = createSignal<DisplayState[]>([]);
const { t } = useLanguage();
createEffect(() => {
const unlisten = listen<RawDisplayState[]>('displays_changed', (ev) => {
logger('displays_changed', ev);
setStates(
ev.payload.map((it) => ({
...it,
last_modified_at: new Date(it.last_modified_at.secs_since_epoch * 1000),
})),
);
});
invoke<RawDisplayState[]>('get_displays').then((states) => {
logger('get_displays', states);
setStates(
states.map((it) => ({
...it,
last_modified_at: new Date(it.last_modified_at.secs_since_epoch * 1000),
})),
);
});
return () => {
unlisten.then((unlisten) => unlisten());
};
});
return (
<div class="space-y-6">
<div class="flex items-center justify-between">
<h1 class="text-2xl font-bold text-base-content">{t('displays.title')}</h1>
<div class="stats shadow">
<div class="stat">
<div class="stat-title">{t('displays.displayCount')}</div>
<div class="stat-value text-primary">{states().length}</div>
</div>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
<For each={states()}>
{(state, index) => (
<div class="relative">
<DisplayStateCard state={state} />
<div class="absolute -top-2 -left-2 w-6 h-6 bg-primary text-primary-content rounded-full flex items-center justify-center text-xs font-bold">
{index() + 1}
</div>
</div>
)}
</For>
</div>
{states().length === 0 && (
<div class="text-center py-12">
<div class="text-6xl mb-4">🖥</div>
<h3 class="text-lg font-semibold text-base-content mb-2">{t('displays.noDisplaysFound')}</h3>
<p class="text-base-content/70">{t('displays.checkConnection')}</p>
</div>
)}
</div>
);
};

View File

@ -0,0 +1,64 @@
import { Component, For, createEffect, createSignal } from 'solid-js';
import { BoardInfo } from '../../models/board-info.model';
import { listen } from '@tauri-apps/api/event';
import debug from 'debug';
import { invoke } from '@tauri-apps/api/core';
import { BoardInfoPanel } from './board-info-panel';
import { useLanguage } from '../../i18n/index';
const logger = debug('app:components:info:board-index');
export const BoardIndex: Component = () => {
const [boards, setBoards] = createSignal<BoardInfo[]>([]);
const { t } = useLanguage();
createEffect(() => {
const unlisten = listen<BoardInfo[]>('boards_changed', (ev) => {
logger('boards_changed', ev);
setBoards(ev.payload);
});
invoke<BoardInfo[]>('get_boards').then((boards) => {
logger('get_boards', boards);
setBoards(boards);
});
return () => {
unlisten.then((unlisten) => unlisten());
};
});
return (
<div class="space-y-6">
<div class="flex items-center justify-between">
<h1 class="text-2xl font-bold text-base-content">{t('info.boardInfo')}</h1>
<div class="stats shadow">
<div class="stat">
<div class="stat-title">{t('info.deviceCount')}</div>
<div class="stat-value text-primary">{boards().length}</div>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<For each={boards()}>
{(board, index) => (
<div class="relative">
<BoardInfoPanel board={board} />
<div class="absolute -top-2 -left-2 w-6 h-6 bg-primary text-primary-content rounded-full flex items-center justify-center text-xs font-bold">
{index() + 1}
</div>
</div>
)}
</For>
</div>
{boards().length === 0 && (
<div class="text-center py-12">
<div class="text-6xl mb-4">🔍</div>
<h3 class="text-lg font-semibold text-base-content mb-2">{t('info.noDevicesFound')}</h3>
<p class="text-base-content/70">{t('info.checkConnection')}</p>
</div>
)}
</div>
);
};

View File

@ -0,0 +1,73 @@
import { Component, ParentComponent, createMemo } from 'solid-js';
import { BoardInfo } from '../../models/board-info.model';
import { useLanguage } from '../../i18n/index';
type ItemProps = {
label: string;
};
const Item: ParentComponent<ItemProps> = (props) => {
return (
<div class="flex justify-between items-center py-1">
<dt class="text-sm font-medium text-base-content/70">{props.label}</dt>
<dd class="text-sm font-mono text-base-content">{props.children}</dd>
</div>
);
};
export const BoardInfoPanel: Component<{ board: BoardInfo }> = (props) => {
const { t } = useLanguage();
const ttl = createMemo(() => {
if (props.board.connect_status !== 'Connected') {
return '--';
}
if (props.board.ttl == null) {
return t('info.timeout');
}
return (
<>
<span class="font-mono">{props.board.ttl.toFixed(0)}</span> ms
</>
);
});
const connectStatus = createMemo(() => {
if (typeof props.board.connect_status === 'string') {
return props.board.connect_status;
}
if ('Connecting' in props.board.connect_status) {
return `${t('info.connecting')} (${props.board.connect_status.Connecting.toFixed(0)})`;
}
});
const statusBadgeClass = createMemo(() => {
const status = connectStatus();
if (status === 'Connected') {
return 'badge badge-success badge-sm';
} else if (status?.startsWith('Connecting')) {
return 'badge badge-warning badge-sm';
} else {
return 'badge badge-error badge-sm';
}
});
return (
<div class="card bg-base-200 shadow-lg hover:shadow-xl transition-shadow duration-200">
<div class="card-body p-4">
<div class="card-title text-base mb-3 flex items-center justify-between">
<span class="truncate">{props.board.fullname}</span>
<div class={statusBadgeClass()}>{connectStatus()}</div>
</div>
<div class="space-y-2">
<Item label={t('info.hostname')}>{props.board.host}</Item>
<Item label={t('info.ipAddress')}>{props.board.address}</Item>
<Item label={t('info.port')}>{props.board.port}</Item>
<Item label={t('info.latency')}>{ttl()}</Item>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,10 @@
import { Component } from 'solid-js';
import { BoardIndex } from './board-index';
export const InfoIndex: Component = () => {
return (
<div>
<BoardIndex />
</div>
);
};

View File

@ -0,0 +1,52 @@
import { Component, JSX, ParentComponent, splitProps } from 'solid-js';
import { DisplayInfo } from '../../models/display-info.model';
import { useLanguage } from '../../i18n/index';
type DisplayInfoItemProps = {
label: string;
};
export const DisplayInfoItem: ParentComponent<DisplayInfoItemProps> = (props) => {
return (
<div class="flex justify-between items-center py-1 px-2 hover:bg-base-300/50 rounded transition-colors">
<dt class="text-sm font-medium text-base-content/80 uppercase">{props.label}</dt>
<dd class="text-sm font-mono text-base-content select-all">{props.children}</dd>
</div>
);
};
type DisplayInfoPanelProps = {
display: DisplayInfo;
} & JSX.HTMLAttributes<HTMLElement>;
export const DisplayInfoPanel: Component<DisplayInfoPanelProps> = (props) => {
const [localProps, rootProps] = splitProps(props, ['display']);
const { t } = useLanguage();
return (
<div {...rootProps} class={'card bg-base-100/95 backdrop-blur shadow-lg border border-base-300 ' + rootProps.class}>
<div class="card-body p-4">
<div class="card-title text-sm mb-3 flex items-center justify-between">
<span class="text-base-content">{t('displays.displayInfo')}</span>
{localProps.display.is_primary && (
<div class="badge badge-primary badge-sm">{t('displays.isPrimary')}</div>
)}
</div>
<div class="space-y-1">
<DisplayInfoItem label={t('displays.id')}>
<code class="bg-base-200 px-1 rounded text-xs">{localProps.display.id}</code>
</DisplayInfoItem>
<DisplayInfoItem label={t('displays.position')}>
({localProps.display.x}, {localProps.display.y})
</DisplayInfoItem>
<DisplayInfoItem label={t('displays.size')}>
{localProps.display.width} × {localProps.display.height}
</DisplayInfoItem>
<DisplayInfoItem label={t('displays.scale')}>
{localProps.display.scale_factor}×
</DisplayInfoItem>
</div>
</div>
</div>
);
};

View File

@ -6,8 +6,8 @@ import {
onMount,
ParentComponent,
} from 'solid-js';
import { displayStore, setDisplayStore } from '../stores/display.store';
import background from '../assets/transparent-grid-background.svg?url';
import { displayStore, setDisplayStore } from '../../stores/display.store';
import background from '../../assets/transparent-grid-background.svg?url';
export const DisplayListContainer: ParentComponent = (props) => {
let root: HTMLElement;
@ -75,7 +75,7 @@ export const DisplayListContainer: ParentComponent = (props) => {
createEffect(() => {});
return (
<section ref={root!} class="relative bg-gray-400/30" style={rootStyle()}>
<section ref={root!} class="relative bg-gray-400/30 h-full w-full" style={rootStyle()}>
<ol class="absolute" style={olStyle()}>
{props.children}
</ol>

View File

@ -1,11 +1,12 @@
import { Component, createMemo } from 'solid-js';
import { DisplayInfo } from '../models/display-info.model';
import { displayStore } from '../stores/display.store';
import { ledStripStore } from '../stores/led-strip.store';
import { DisplayInfo } from '../../models/display-info.model';
import { displayStore } from '../../stores/display.store';
import { ledStripStore } from '../../stores/led-strip.store';
import { DisplayInfoPanel } from './display-info-panel';
import { LedStripPart } from './led-strip-part';
import { ScreenView } from './screen-view';
type DisplayViewProps = {
display: DisplayInfo;
};
@ -23,7 +24,6 @@ export const DisplayView: Component<DisplayViewProps> = (props) => {
}));
const ledStripConfigs = createMemo(() => {
console.log('ledStripConfigs', ledStripStore.strips);
return ledStripStore.strips.filter((c) => c.display_id === props.display.id);
});

View File

@ -0,0 +1,207 @@
import { invoke } from '@tauri-apps/api/core';
import { Component, createMemo, For, JSX, splitProps, useContext } from 'solid-js';
import { DisplayInfo } from '../../models/display-info.model';
import { ledStripStore } from '../../stores/led-strip.store';
import { Borders } from '../../constants/border';
import { LedType } from '../../models/led-strip-config';
import { LedStripConfigurationContext } from '../../contexts/led-strip-configuration.context';
import { useLanguage } from '../../i18n/index';
type LedCountControlItemProps = {
displayId: number;
border: Borders;
label: string;
};
const LedCountControlItem: Component<LedCountControlItemProps> = (props) => {
const [stripConfiguration, { setHoveredStripPart }] = useContext(LedStripConfigurationContext);
const { t } = useLanguage();
const config = createMemo(() => {
return ledStripStore.strips.find(
(s) => s.display_id === props.displayId && s.border === props.border
);
});
const handleDecrease = () => {
if (config()) {
invoke('patch_led_strip_len', {
displayId: props.displayId,
border: props.border,
deltaLen: -1,
}).catch((e) => {
console.error(e);
});
}
};
const handleIncrease = () => {
if (config()) {
invoke('patch_led_strip_len', {
displayId: props.displayId,
border: props.border,
deltaLen: 1,
}).catch((e) => {
console.error(e);
});
}
};
const handleInputChange = (e: Event) => {
const target = e.target as HTMLInputElement;
const newValue = parseInt(target.value);
const currentLen = config()?.len || 0;
if (!isNaN(newValue) && newValue >= 0 && newValue <= 1000) {
const deltaLen = newValue - currentLen;
if (deltaLen !== 0) {
invoke('patch_led_strip_len', {
displayId: props.displayId,
border: props.border,
deltaLen: deltaLen,
}).catch((e) => {
console.error(e);
// Reset input value on error
target.value = currentLen.toString();
});
}
} else {
// Reset invalid input
target.value = (config()?.len || 0).toString();
}
};
const handleLedTypeChange = (e: Event) => {
const target = e.target as HTMLSelectElement;
const newType = target.value as LedType;
invoke('patch_led_strip_type', {
displayId: props.displayId,
border: props.border,
ledType: newType,
}).catch((e) => {
console.error(e);
});
};
const onMouseEnter = () => {
setHoveredStripPart({
displayId: props.displayId,
border: props.border,
});
};
const onMouseLeave = () => {
setHoveredStripPart(null);
};
return (
<div
class="card bg-base-100 border border-base-300/50 p-1.5 transition-all duration-200 cursor-pointer"
classList={{
'ring-2 ring-primary bg-primary/20 border-primary':
stripConfiguration.hoveredStripPart?.border === props.border &&
stripConfiguration.hoveredStripPart?.displayId === props.displayId,
}}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
<div class="flex flex-col gap-1">
<div class="text-center">
<span class="text-xs font-medium text-base-content">
{props.label}
</span>
</div>
<div class="flex items-center gap-0.5">
<button
class="btn btn-xs btn-circle btn-outline flex-shrink-0 min-h-0 h-6 w-6"
onClick={handleDecrease}
disabled={!config() || (config()?.len || 0) <= 0}
title={t('ledConfig.decreaseLedCount')}
>
-
</button>
<input
type="number"
class="input input-xs flex-1 text-center min-w-0 text-xs font-medium [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none h-6 px-1"
value={config()?.len || 0}
min="0"
max="1000"
onBlur={handleInputChange}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleInputChange(e);
}
}}
/>
<button
class="btn btn-xs btn-circle btn-outline flex-shrink-0 min-h-0 h-6 w-6"
onClick={handleIncrease}
disabled={!config() || (config()?.len || 0) >= 1000}
title={t('ledConfig.increaseLedCount')}
>
+
</button>
</div>
<div class="mt-1">
<select
class="select select-xs w-full text-xs h-6 min-h-0"
value={config()?.led_type || LedType.WS2812B}
onChange={handleLedTypeChange}
title={t('ledConfig.ledType')}
>
<option value={LedType.WS2812B}>WS2812B</option>
<option value={LedType.SK6812}>SK6812</option>
</select>
</div>
</div>
</div>
);
};
type LedCountControlPanelProps = {
display: DisplayInfo;
} & JSX.HTMLAttributes<HTMLDivElement>;
export const LedCountControlPanel: Component<LedCountControlPanelProps> = (props) => {
const [localProps, rootProps] = splitProps(props, ['display']);
const { t } = useLanguage();
const borders: { border: Borders; label: string }[] = [
{ border: 'Top', label: t('ledConfig.top') },
{ border: 'Bottom', label: t('ledConfig.bottom') },
{ border: 'Left', label: t('ledConfig.left') },
{ border: 'Right', label: t('ledConfig.right') },
];
return (
<div {...rootProps} class={'card bg-base-200 shadow-lg border border-base-300 ' + (rootProps.class || '')}>
<div class="card-body p-3">
<div class="card-title text-sm mb-2 flex items-center justify-between">
<span>{t('ledConfig.ledCountControl')}</span>
<div class="badge badge-info badge-outline text-xs">{t('ledConfig.display')} {localProps.display.id}</div>
</div>
<div class="grid grid-cols-2 sm:grid-cols-4 gap-2">
<For each={borders}>
{(item) => (
<LedCountControlItem
displayId={localProps.display.id}
border={item.border}
label={item.label}
/>
)}
</For>
</div>
<div class="text-xs text-base-content/50 mt-2 p-1.5 bg-base-300/50 rounded">
💡 {t('ledConfig.controlTip')}
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,172 @@
import { createEffect, onCleanup } from 'solid-js';
import { invoke } from '@tauri-apps/api/core';
import { DisplayView } from './display-view';
import { DisplayListContainer } from './display-list-container';
import { displayStore, setDisplayStore } from '../../stores/display.store';
import { LedStripConfigContainer } from '../../models/led-strip-config';
import { setLedStripStore } from '../../stores/led-strip.store';
import { listen } from '@tauri-apps/api/event';
import { LedStripPartsSorter } from './led-strip-parts-sorter';
import { LedCountControlPanel } from './led-count-control-panel';
import { createStore } from 'solid-js/store';
import {
LedStripConfigurationContext,
LedStripConfigurationContextType,
} from '../../contexts/led-strip-configuration.context';
import { useLanguage } from '../../i18n/index';
export const LedStripConfiguration = () => {
const { t } = useLanguage();
createEffect(() => {
invoke<string>('list_display_info').then((displays) => {
const parsedDisplays = JSON.parse(displays);
setDisplayStore({
displays: parsedDisplays,
});
}).catch((error) => {
console.error('Failed to load displays:', error);
});
invoke<LedStripConfigContainer>('read_led_strip_configs').then((configs) => {
setLedStripStore(configs);
}).catch((error) => {
console.error('Failed to load LED strip configs:', error);
});
});
// listen to config_changed event
createEffect(() => {
const unlisten = listen('config_changed', (event) => {
const { strips, mappers } = event.payload as LedStripConfigContainer;
setLedStripStore({
strips,
mappers,
});
});
onCleanup(() => {
unlisten.then((unlisten) => unlisten());
});
});
// listen to led_colors_changed event
createEffect(() => {
const unlisten = listen<Uint8ClampedArray>('led_colors_changed', (event) => {
if (!window.document.hidden) {
const colors = event.payload;
setLedStripStore({
colors,
});
}
});
onCleanup(() => {
unlisten.then((unlisten) => unlisten());
});
});
// listen to led_sorted_colors_changed event
createEffect(() => {
const unlisten = listen<Uint8ClampedArray>('led_sorted_colors_changed', (event) => {
if (!window.document.hidden) {
const sortedColors = event.payload;
setLedStripStore({
sortedColors,
});
}
});
onCleanup(() => {
unlisten.then((unlisten) => unlisten());
});
});
const [ledStripConfiguration, setLedStripConfiguration] = createStore<
LedStripConfigurationContextType[0]
>({
selectedStripPart: null,
hoveredStripPart: null,
});
const ledStripConfigurationContextValue: LedStripConfigurationContextType = [
ledStripConfiguration,
{
setSelectedStripPart: (v) => {
setLedStripConfiguration({
selectedStripPart: v,
});
},
setHoveredStripPart: (v) => {
setLedStripConfiguration({
hoveredStripPart: v,
});
},
},
];
return (
<div class="space-y-4">
<div class="flex items-center justify-between">
<h1 class="text-xl font-bold text-base-content">{t('ledConfig.title')}</h1>
<div class="stats shadow">
<div class="stat py-2 px-4">
<div class="stat-title text-xs">{t('displays.displayCount')}</div>
<div class="stat-value text-primary text-lg">{displayStore.displays.length}</div>
</div>
</div>
</div>
<LedStripConfigurationContext.Provider value={ledStripConfigurationContextValue}>
<div class="space-y-4">
{/* LED Strip Sorter Panel */}
<div class="card bg-base-200 shadow-lg">
<div class="card-body p-3">
<div class="card-title text-sm mb-2">
<span>{t('ledConfig.stripSorting')}</span>
<div class="badge badge-info badge-outline text-xs">{t('ledConfig.realtimePreview')}</div>
</div>
<LedStripPartsSorter />
<div class="text-xs text-base-content/50 mt-2">
💡 {t('ledConfig.sortingTip')}
</div>
</div>
</div>
{/* Display Configuration Panel - Auto height based on content */}
<div class="card bg-base-200 shadow-lg">
<div class="card-body p-3">
<div class="card-title text-sm mb-2">
<span>{t('ledConfig.displayConfiguration')}</span>
<div class="badge badge-secondary badge-outline text-xs">{t('ledConfig.visualEditor')}</div>
</div>
<div class="mb-3">
<DisplayListContainer>
{displayStore.displays.map((display) => (
<DisplayView display={display} />
))}
</DisplayListContainer>
</div>
<div class="text-xs text-base-content/50">
💡 {t('ledConfig.displayTip')}
</div>
</div>
</div>
{/* LED Count Control Panels */}
<div class="flex-shrink-0">
<div class="flex items-center gap-2 mb-2">
<h2 class="text-base font-semibold text-base-content">{t('ledConfig.ledCountControl')}</h2>
<div class="badge badge-info badge-outline text-xs">{t('ledConfig.realtimeAdjustment')}</div>
</div>
<div class="led-control-grid">
{displayStore.displays.map((display) => (
<LedCountControlPanel display={display} />
))}
</div>
</div>
</div>
</LedStripConfigurationContext.Provider>
</div>
);
};

View File

@ -1,4 +1,4 @@
import { invoke } from '@tauri-apps/api';
import { invoke } from '@tauri-apps/api/core';
import {
Component,
createEffect,
@ -12,9 +12,9 @@ import {
} from 'solid-js';
import { useTippy } from 'solid-tippy';
import { followCursor } from 'tippy.js';
import { LedStripConfig } from '../models/led-strip-config';
import { LedStripConfigurationContext } from '../contexts/led-strip-configuration.context';
import { ledStripStore } from '../stores/led-strip.store';
import { LedStripConfig } from '../../models/led-strip-config';
import { LedStripConfigurationContext } from '../../contexts/led-strip-configuration.context';
import { ledStripStore } from '../../stores/led-strip.store';
type LedStripPartProps = {
config?: LedStripConfig | null;
@ -24,12 +24,6 @@ type PixelProps = {
color: string;
};
async function subscribeScreenshotUpdate(displayId: number) {
await invoke('subscribe_encoded_screenshot_updated', {
displayId,
});
}
export const Pixel: Component<PixelProps> = (props) => {
const style = createMemo(() => ({
background: props.color,
@ -40,7 +34,7 @@ export const Pixel: Component<PixelProps> = (props) => {
title={props.color}
>
<div
class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-300"
class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-300/50"
style={style()}
/>
</div>
@ -49,9 +43,8 @@ export const Pixel: Component<PixelProps> = (props) => {
export const LedStripPart: Component<LedStripPartProps> = (props) => {
const [localProps, rootProps] = splitProps(props, ['config']);
const [stripConfiguration] = useContext(LedStripConfigurationContext);
const [stripConfiguration, { setHoveredStripPart }] = useContext(LedStripConfigurationContext);
const [ledSamplePoints, setLedSamplePoints] = createSignal();
const [colors, setColors] = createSignal<string[]>([]);
// update led strip colors from global store
@ -75,29 +68,19 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
return;
}
const offset = mapper.pos * 3;
const offset = mapper.start * 3;
const colors = new Array(localProps.config.len).fill(null).map((_, i) => {
const index = offset + i * 3;
return `rgb(${ledStripStore.colors[index]}, ${ledStripStore.colors[index + 1]}, ${
ledStripStore.colors[index + 2]
})`;
const r = ledStripStore.colors[index] || 0;
const g = ledStripStore.colors[index + 1] || 0;
const b = ledStripStore.colors[index + 2] || 0;
return `rgb(${r}, ${g}, ${b})`;
});
setColors(colors);
});
// get led strip sample points
createEffect(() => {
if (localProps.config) {
invoke('get_led_strips_sample_points', {
config: localProps.config,
}).then((points) => {
setLedSamplePoints(points);
});
}
});
const [anchor, setAnchor] = createSignal<HTMLElement>();
useTippy(anchor, {
@ -133,12 +116,25 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
}
};
const onMouseEnter = () => {
if (localProps.config) {
setHoveredStripPart({
displayId: localProps.config.display_id,
border: localProps.config.border,
});
}
};
const onMouseLeave = () => {
setHoveredStripPart(null);
};
return (
<section
{...rootProps}
ref={setAnchor}
class={
'flex rounded-full flex-nowrap justify-around items-center overflow-hidden ' +
'flex rounded-full flex-nowrap justify-around items-center overflow-hidden bg-gray-800/20 border border-gray-600/30 min-h-[12px] min-w-[12px] m-1 px-0.5 py-0.5 transition-all duration-200 ' +
rootProps.class
}
classList={{
@ -146,8 +142,13 @@ export const LedStripPart: Component<LedStripPartProps> = (props) => {
stripConfiguration.selectedStripPart?.border === localProps.config?.border &&
stripConfiguration.selectedStripPart?.displayId ===
localProps.config?.display_id,
'ring-2 ring-primary bg-primary/20 border-primary':
stripConfiguration.hoveredStripPart?.border === localProps.config?.border &&
stripConfiguration.hoveredStripPart?.displayId === localProps.config?.display_id,
}}
onWheel={onWheel}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
<For each={colors()}>{(item) => <Pixel color={item} />}</For>
</section>

View File

@ -0,0 +1,330 @@
import {
batch,
Component,
createEffect,
createMemo,
createSignal,
For,
Index,
JSX,
Match,
onCleanup,
onMount,
Switch,
untrack,
useContext,
} from 'solid-js';
import { LedStripConfig, LedStripPixelMapper } from '../../models/led-strip-config';
import { ledStripStore } from '../../stores/led-strip.store';
import { invoke } from '@tauri-apps/api/core';
import { LedStripConfigurationContext } from '../../contexts/led-strip-configuration.context';
import background from '../../assets/transparent-grid-background.svg?url';
const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper }> = (
props,
) => {
const [leds, setLeds] = createSignal<Array<string | null>>([]);
const [dragging, setDragging] = createSignal<boolean>(false);
const [dragStart, setDragStart] = createSignal<{ x: number; y: number } | null>(null);
const [dragCurr, setDragCurr] = createSignal<{ x: number; y: number } | null>(null);
const [dragStartIndex, setDragStartIndex] = createSignal<number>(0);
const [cellWidth, setCellWidth] = createSignal<number>(0);
const [stripConfiguration, { setSelectedStripPart, setHoveredStripPart }] = useContext(LedStripConfigurationContext);
const [rootWidth, setRootWidth] = createSignal<number>(0);
let root: HTMLDivElement;
const move = (targetStart: number) => {
if (targetStart === props.mapper.start) {
return;
}
invoke('move_strip_part', {
displayId: props.strip.display_id,
border: props.strip.border,
targetStart,
}).catch((err) => console.error(err));
};
// reset translateX on config updated
createEffect(() => {
const indexDiff = props.mapper.start - dragStartIndex();
const start = untrack(dragStart);
const curr = untrack(dragCurr);
const _dragging = untrack(dragging);
if (start === null || curr === null) {
return;
}
if (_dragging && indexDiff !== 0) {
const compensation = indexDiff * cellWidth();
batch(() => {
setDragStartIndex(props.mapper.start);
setDragStart({
x: start.x + compensation,
y: curr.y,
});
});
} else {
batch(() => {
setDragStartIndex(props.mapper.start);
setDragStart(null);
setDragCurr(null);
});
}
});
const onPointerDown = (ev: PointerEvent) => {
if (ev.button !== 0) {
return;
}
batch(() => {
setDragging(true);
if (dragStart() === null) {
setDragStart({ x: ev.clientX, y: ev.clientY });
}
setDragCurr({ x: ev.clientX, y: ev.clientY });
setDragStartIndex(props.mapper.start);
});
};
const onPointerUp = (ev: PointerEvent) => {
if (ev.button !== 0) {
return;
}
if (dragging() === false) {
return;
}
setDragging(false);
const diff = ev.clientX - dragStart()!.x;
const moved = Math.round(diff / cellWidth());
if (moved === 0) {
return;
}
move(props.mapper.start + moved);
};
const onPointerMove = (ev: PointerEvent) => {
if (dragging() === false) {
return;
}
setSelectedStripPart({
displayId: props.strip.display_id,
border: props.strip.border,
});
if (!(ev.buttons & 1)) {
return;
}
const draggingInfo = dragging();
if (!draggingInfo) {
return;
}
setDragCurr({ x: ev.clientX, y: ev.clientY });
};
const onPointerLeave = () => {
setSelectedStripPart(null);
};
createEffect(() => {
onMount(() => {
window.addEventListener('pointermove', onPointerMove);
window.addEventListener('pointerleave', onPointerLeave);
window.addEventListener('pointerup', onPointerUp);
});
onCleanup(() => {
window.removeEventListener('pointermove', onPointerMove);
window.removeEventListener('pointerleave', onPointerLeave);
window.removeEventListener('pointerup', onPointerUp);
});
});
const reverse = () => {
invoke('reverse_led_strip_part', {
displayId: props.strip.display_id,
border: props.strip.border,
}).catch((err) => console.error(err));
};
const onMouseEnter = () => {
setHoveredStripPart({
displayId: props.strip.display_id,
border: props.strip.border,
});
};
const onMouseLeave = () => {
setHoveredStripPart(null);
};
const setColor = (fullIndex: number, colorsIndex: number, fullLeds: string[]) => {
const colors = ledStripStore.colors;
let c1 = `rgb(${Math.floor(colors[colorsIndex * 3] * 0.8)}, ${Math.floor(
colors[colorsIndex * 3 + 1] * 0.8,
)}, ${Math.floor(colors[colorsIndex * 3 + 2] * 0.8)})`;
let c2 = `rgb(${Math.min(Math.floor(colors[colorsIndex * 3] * 1.2), 255)}, ${Math.min(
Math.floor(colors[colorsIndex * 3 + 1] * 1.2),
255,
)}, ${Math.min(Math.floor(colors[colorsIndex * 3 + 2] * 1.2), 255)})`;
if (fullLeds.length <= fullIndex) {
return;
}
fullLeds[fullIndex] = `linear-gradient(70deg, ${c1} 10%, ${c2})`;
};
// update fullLeds
createEffect(() => {
const { start, end, pos } = props.mapper;
const leds = new Array(Math.abs(start - end)).fill(null);
if (start < end) {
for (let i = 0, j = pos; i < leds.length; i++, j++) {
setColor(i, j, leds);
}
} else {
for (let i = leds.length - 1, j = pos; i >= 0; i--, j++) {
setColor(i, j, leds);
}
}
setLeds(leds);
});
// update rootWidth
createEffect(() => {
let observer: ResizeObserver;
onMount(() => {
observer = new ResizeObserver(() => {
setRootWidth(root.clientWidth);
});
observer.observe(root);
});
onCleanup(() => {
observer?.unobserve(root);
});
});
// update cellWidth
createEffect(() => {
const cellWidth = rootWidth() / ledStripStore.totalLedCount;
setCellWidth(cellWidth);
});
const style = createMemo<JSX.CSSProperties>(() => {
return {
transform: `translateX(${
(dragCurr()?.x ?? 0) -
(dragStart()?.x ?? 0) +
cellWidth() * Math.min(props.mapper.start, props.mapper.end)
}px)`,
width: `${cellWidth() * leds().length}px`,
};
});
return (
<div
class="flex mx-2 select-none cursor-ew-resize focus:cursor-ew-resize transition-colors duration-200"
classList={{
'bg-primary/20 rounded-lg':
stripConfiguration.hoveredStripPart?.border === props.strip.border &&
stripConfiguration.hoveredStripPart?.displayId === props.strip.display_id,
}}
onPointerDown={onPointerDown}
ondblclick={reverse}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
ref={root!}
>
<div
style={style()}
class="rounded-full border border-white flex h-3"
classList={{
'bg-gradient-to-b from-yellow-500/60 to-orange-300/60': dragging(),
'bg-gradient-to-b from-white/50 to-stone-500/40': !dragging(),
}}
>
<For each={leds()}>
{(it) => (
<div
class="flex-auto flex h-full w-full justify-center items-center relative"
title={it ?? ''}
>
<div
class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-100"
classList={{ 'ring-stone-300/50': !it }}
style={{ background: it ?? 'transparent' }}
/>
</div>
)}
</For>
</div>
</div>
);
};
const SorterResult: Component = () => {
const [fullLeds, setFullLeds] = createSignal<string[]>([]);
createEffect(() => {
const colors = ledStripStore.sortedColors;
const fullLeds = new Array(ledStripStore.totalLedCount)
.fill('rgba(255,255,255,0.1)')
.map((_, i) => {
let c1 = `rgb(${Math.floor(colors[i * 3] * 0.8)}, ${Math.floor(
colors[i * 3 + 1] * 0.8,
)}, ${Math.floor(colors[i * 3 + 2] * 0.8)})`;
let c2 = `rgb(${Math.min(Math.floor(colors[i * 3] * 1.2), 255)}, ${Math.min(
Math.floor(colors[i * 3 + 1] * 1.2),
255,
)}, ${Math.min(Math.floor(colors[i * 3 + 2] * 1.2), 255)})`;
return `linear-gradient(70deg, ${c1} 10%, ${c2})`;
});
setFullLeds(fullLeds);
});
return (
<div class="flex h-2 m-2">
<For each={fullLeds()}>
{(it) => (
<div
class="flex-auto flex h-full w-full justify-center items-center relative"
title={it}
>
<div
class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-300"
style={{ background: it }}
/>
</div>
)}
</For>
</div>
);
};
export const LedStripPartsSorter: Component = () => {
return (
<div
class="select-none overflow-hidden"
style={{
'background-image': `url(${background})`,
}}
>
<SorterResult />
<Index each={ledStripStore.strips}>
{(strip, index) => (
<Switch>
<Match when={strip().len > 0}>
<SorterItem strip={strip()} mapper={ledStripStore.mappers[index]} />
</Match>
</Switch>
)}
</Index>
</div>
);
};

View File

@ -0,0 +1,255 @@
import {
Component,
createEffect,
createSignal,
JSX,
onCleanup,
onMount,
splitProps,
} from 'solid-js';
import { invoke } from '@tauri-apps/api/core';
type ScreenViewWebSocketProps = {
displayId: number;
width?: number;
height?: number;
quality?: number;
} & JSX.HTMLAttributes<HTMLDivElement>;
export const ScreenViewWebSocket: Component<ScreenViewWebSocketProps> = (props) => {
const [localProps, rootProps] = splitProps(props, ['displayId', 'width', 'height', 'quality']);
let canvas: HTMLCanvasElement;
let root: HTMLDivElement;
const [ctx, setCtx] = createSignal<CanvasRenderingContext2D | null>(null);
const [drawInfo, setDrawInfo] = createSignal({
drawX: 0,
drawY: 0,
drawWidth: 0,
drawHeight: 0,
});
const [connectionStatus, setConnectionStatus] = createSignal<'connecting' | 'connected' | 'disconnected' | 'error'>('disconnected');
const [frameCount, setFrameCount] = createSignal(0);
const [lastFrameTime, setLastFrameTime] = createSignal(0);
const [fps, setFps] = createSignal(0);
let websocket: WebSocket | null = null;
let reconnectTimeout: number | null = null;
let isMounted = true;
// Performance monitoring
let frameTimestamps: number[] = [];
const connectWebSocket = () => {
if (!isMounted) {
return;
}
const wsUrl = `ws://127.0.0.1:8765`;
setConnectionStatus('connecting');
websocket = new WebSocket(wsUrl);
websocket.binaryType = 'arraybuffer';
websocket.onopen = () => {
setConnectionStatus('connected');
// Send initial configuration
const config = {
display_id: localProps.displayId,
width: localProps.width || 320,
height: localProps.height || 180,
quality: localProps.quality || 50
};
websocket?.send(JSON.stringify(config));
};
websocket.onmessage = (event) => {
if (event.data instanceof ArrayBuffer) {
handleJpegFrame(new Uint8Array(event.data));
}
};
websocket.onclose = (event) => {
setConnectionStatus('disconnected');
websocket = null;
// Auto-reconnect after 2 seconds if component is still mounted
if (isMounted && !reconnectTimeout) {
reconnectTimeout = window.setTimeout(() => {
reconnectTimeout = null;
connectWebSocket();
}, 2000);
}
};
websocket.onerror = (error) => {
setConnectionStatus('error');
};
};
const handleJpegFrame = async (jpegData: Uint8Array) => {
const _ctx = ctx();
if (!_ctx) return;
try {
// Update performance metrics
const now = performance.now();
frameTimestamps.push(now);
// Keep only last 30 frames for FPS calculation
if (frameTimestamps.length > 30) {
frameTimestamps = frameTimestamps.slice(-30);
}
// Calculate FPS
if (frameTimestamps.length >= 2) {
const timeSpan = frameTimestamps[frameTimestamps.length - 1] - frameTimestamps[0];
if (timeSpan > 0) {
const currentFps = Math.round((frameTimestamps.length - 1) * 1000 / timeSpan);
setFps(Math.max(0, currentFps)); // Ensure FPS is never negative
}
}
setFrameCount(prev => prev + 1);
setLastFrameTime(now);
// Create blob from JPEG data
const blob = new Blob([jpegData], { type: 'image/jpeg' });
const imageUrl = URL.createObjectURL(blob);
// Create image element
const img = new Image();
img.onload = () => {
const { drawX, drawY, drawWidth, drawHeight } = drawInfo();
// Clear canvas
_ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw image
_ctx.drawImage(img, drawX, drawY, drawWidth, drawHeight);
// Clean up
URL.revokeObjectURL(imageUrl);
};
img.onerror = () => {
console.error('Failed to load JPEG image');
URL.revokeObjectURL(imageUrl);
};
img.src = imageUrl;
} catch (error) {
console.error('Error handling JPEG frame:', error);
}
};
const resetSize = () => {
// Set canvas size first
canvas.width = root.clientWidth;
canvas.height = root.clientHeight;
// Use a default aspect ratio if canvas dimensions are invalid
const aspectRatio = (canvas.width > 0 && canvas.height > 0)
? canvas.width / canvas.height
: 16 / 9; // Default 16:9 aspect ratio
const drawWidth = Math.round(
Math.min(root.clientWidth, root.clientHeight * aspectRatio),
);
const drawHeight = Math.round(
Math.min(root.clientHeight, root.clientWidth / aspectRatio),
);
const drawX = Math.round((root.clientWidth - drawWidth) / 2);
const drawY = Math.round((root.clientHeight - drawHeight) / 2);
setDrawInfo({
drawX,
drawY,
drawWidth,
drawHeight,
});
};
const disconnect = () => {
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
}
if (websocket) {
websocket.close();
websocket = null;
}
};
// Initialize canvas and resize observer
onMount(() => {
const context = canvas.getContext('2d');
setCtx(context);
// Initial size setup
resetSize();
const resizeObserver = new ResizeObserver(() => {
resetSize();
});
resizeObserver.observe(root);
// Connect WebSocket
connectWebSocket();
onCleanup(() => {
isMounted = false;
disconnect();
resizeObserver?.unobserve(root);
});
});
// Status indicator
const getStatusColor = () => {
switch (connectionStatus()) {
case 'connected': return '#10b981'; // green
case 'connecting': return '#f59e0b'; // yellow
case 'error': return '#ef4444'; // red
default: return '#6b7280'; // gray
}
};
return (
<div
ref={root!}
{...rootProps}
class={'overflow-hidden h-full w-full relative ' + (rootProps.class || '')}
>
<canvas
ref={canvas!}
style={{
display: 'block',
width: '100%',
height: '100%',
'background-color': '#f0f0f0'
}}
/>
{/* Status indicator */}
<div class="absolute top-2 right-2 flex items-center gap-2 bg-black bg-opacity-50 text-white px-2 py-1 rounded text-xs">
<div
class="w-2 h-2 rounded-full"
style={{ 'background-color': getStatusColor() }}
/>
<span>{connectionStatus()}</span>
{connectionStatus() === 'connected' && (
<span>| {fps()} FPS | {frameCount()} frames</span>
)}
</div>
{rootProps.children}
</div>
);
};

View File

@ -0,0 +1,237 @@
import {
Component,
createEffect,
createSignal,
JSX,
onCleanup,
onMount,
splitProps,
} from 'solid-js';
import { ScreenViewWebSocket } from './screen-view-websocket';
type ScreenViewProps = {
displayId: number;
useWebSocket?: boolean;
} & JSX.HTMLAttributes<HTMLDivElement>;
export const ScreenView: Component<ScreenViewProps> = (props) => {
const [localProps, rootProps] = splitProps(props, ['displayId', 'useWebSocket']);
// Use WebSocket by default for better performance
if (localProps.useWebSocket !== false) {
return <ScreenViewWebSocket displayId={localProps.displayId} {...rootProps} />;
}
// Fallback to HTTP polling (legacy mode)
let canvas: HTMLCanvasElement;
let root: HTMLDivElement;
const [ctx, setCtx] = createSignal<CanvasRenderingContext2D | null>(null);
// Cache temporary canvas for scaling
let tempCanvas: HTMLCanvasElement | null = null;
let tempCtx: CanvasRenderingContext2D | null = null;
const [drawInfo, setDrawInfo] = createSignal({
drawX: 0,
drawY: 0,
drawWidth: 0,
drawHeight: 0,
});
const [imageData, setImageData] = createSignal<{
buffer: Uint8ClampedArray;
width: number;
height: number;
} | null>(null);
const [hidden, setHidden] = createSignal(false);
const [isLoading, setIsLoading] = createSignal(false);
let isMounted = true;
// Fetch screenshot data from backend with frame-based rendering
const fetchScreenshot = async () => {
if (isLoading()) {
return; // Skip if already loading - frame-based approach
}
try {
setIsLoading(true);
const timestamp = Date.now();
const response = await fetch(`ambient-light://displays/${localProps.displayId}?width=400&height=225&t=${timestamp}`);
if (!response.ok) {
console.error('Screenshot fetch failed:', response.status);
return;
}
const width = parseInt(response.headers.get('X-Image-Width') || '400');
const height = parseInt(response.headers.get('X-Image-Height') || '225');
const arrayBuffer = await response.arrayBuffer();
const buffer = new Uint8ClampedArray(arrayBuffer);
const expectedSize = width * height * 4;
// Validate buffer size
if (buffer.length !== expectedSize) {
console.error('Invalid buffer size:', buffer.length, 'expected:', expectedSize);
return;
}
setImageData({
buffer,
width,
height
});
// Draw immediately after data is set
setTimeout(() => {
draw(false);
}, 0);
// Frame-based rendering: wait for current frame to complete before scheduling next
const shouldContinue = !hidden() && isMounted;
if (shouldContinue) {
setTimeout(() => {
if (isMounted) {
fetchScreenshot(); // Start next frame only after current one completes
}
}, 500); // Reduced frequency to 500ms for better performance
}
} catch (error) {
console.error('Error fetching screenshot:', error);
// On error, wait longer before retry
const shouldContinueOnError = !hidden() && isMounted;
if (shouldContinueOnError) {
setTimeout(() => {
if (isMounted) {
fetchScreenshot();
}
}, 2000);
}
} finally {
setIsLoading(false);
}
};
const resetSize = () => {
// Set canvas size first
canvas.width = root.clientWidth;
canvas.height = root.clientHeight;
// Use a default aspect ratio if canvas dimensions are invalid
const aspectRatio = (canvas.width > 0 && canvas.height > 0)
? canvas.width / canvas.height
: 16 / 9; // Default 16:9 aspect ratio
const drawWidth = Math.round(
Math.min(root.clientWidth, root.clientHeight * aspectRatio),
);
const drawHeight = Math.round(
Math.min(root.clientHeight, root.clientWidth / aspectRatio),
);
const drawX = Math.round((root.clientWidth - drawWidth) / 2);
const drawY = Math.round((root.clientHeight - drawHeight) / 2);
setDrawInfo({
drawX,
drawY,
drawWidth,
drawHeight,
});
draw(true);
};
const draw = (cached: boolean = false) => {
const { drawX, drawY, drawWidth, drawHeight } = drawInfo();
let _ctx = ctx();
let raw = imageData();
if (_ctx && raw) {
_ctx.clearRect(0, 0, canvas.width, canvas.height);
// Apply transparency effect for cached images if needed
let buffer = raw.buffer;
if (cached) {
buffer = new Uint8ClampedArray(raw.buffer);
for (let i = 3; i < buffer.length; i += 4) {
buffer[i] = Math.floor(buffer[i] * 0.7);
}
}
try {
// Create ImageData and draw directly
const img = new ImageData(buffer, raw.width, raw.height);
// If the image size matches the draw size, use putImageData directly
if (raw.width === drawWidth && raw.height === drawHeight) {
_ctx.putImageData(img, drawX, drawY);
} else {
// Otherwise, use cached temporary canvas for scaling
if (!tempCanvas || tempCanvas.width !== raw.width || tempCanvas.height !== raw.height) {
tempCanvas = document.createElement('canvas');
tempCanvas.width = raw.width;
tempCanvas.height = raw.height;
tempCtx = tempCanvas.getContext('2d');
}
if (tempCtx) {
tempCtx.putImageData(img, 0, 0);
_ctx.drawImage(tempCanvas, drawX, drawY, drawWidth, drawHeight);
}
}
} catch (error) {
console.error('Error in draw():', error);
}
}
};
// Initialize canvas and resize observer
onMount(() => {
const context = canvas.getContext('2d');
setCtx(context);
// Initial size setup
resetSize();
const resizeObserver = new ResizeObserver(() => {
resetSize();
});
resizeObserver.observe(root);
// Start screenshot fetching after context is ready
setTimeout(() => {
fetchScreenshot(); // Initial fetch - will self-schedule subsequent frames
}, 100); // Small delay to ensure context is ready
onCleanup(() => {
isMounted = false; // Stop scheduling new frames
resizeObserver?.unobserve(root);
});
});
// Note: Removed window focus/blur logic as it was causing screenshot loop to stop
// when user interacted with dev tools or other windows
return (
<div
ref={root!}
{...rootProps}
class={'overflow-hidden h-full w-full ' + rootProps.class}
>
<canvas
ref={canvas!}
style={{
display: 'block',
width: '100%',
height: '100%',
'background-color': '#f0f0f0'
}}
/>
{rootProps.children}
</div>
);
};

View File

@ -1,228 +0,0 @@
import {
batch,
Component,
createContext,
createEffect,
createMemo,
createSignal,
For,
Index,
JSX,
on,
untrack,
useContext,
} from 'solid-js';
import { LedStripConfig, LedStripPixelMapper } from '../models/led-strip-config';
import { ledStripStore } from '../stores/led-strip.store';
import { invoke } from '@tauri-apps/api';
import { LedStripConfigurationContext } from '../contexts/led-strip-configuration.context';
import background from '../assets/transparent-grid-background.svg?url';
const SorterItem: Component<{ strip: LedStripConfig; mapper: LedStripPixelMapper }> = (
props,
) => {
const [fullLeds, setFullLeds] = createSignal<Array<string | null>>([]);
const [dragging, setDragging] = createSignal<boolean>(false);
const [dragStart, setDragStart] = createSignal<{ x: number; y: number } | null>(null);
const [dragCurr, setDragCurr] = createSignal<{ x: number; y: number } | null>(null);
const [dragStartIndex, setDragStartIndex] = createSignal<number>(0);
const [cellWidth, setCellWidth] = createSignal<number>(0);
const [, { setSelectedStripPart }] = useContext(LedStripConfigurationContext);
const move = (targetStart: number) => {
if (targetStart === props.mapper.start) {
return;
}
invoke('move_strip_part', {
displayId: props.strip.display_id,
border: props.strip.border,
targetStart,
}).catch((err) => console.error(err));
};
// reset translateX on config updated
createEffect(() => {
const indexDiff = props.mapper.start - dragStartIndex();
untrack(() => {
if (!dragStart() || !dragCurr()) {
return;
}
const compensation = indexDiff * cellWidth();
batch(() => {
setDragStartIndex(props.mapper.start);
setDragStart({
x: dragStart()!.x + compensation,
y: dragCurr()!.y,
});
});
});
});
const onPointerDown = (ev: PointerEvent) => {
if (ev.button !== 0) {
return;
}
setDragging(true);
setDragStart({ x: ev.clientX, y: ev.clientY });
setDragCurr({ x: ev.clientX, y: ev.clientY });
setDragStartIndex(props.mapper.start);
};
const onPointerUp = () => (ev: PointerEvent) => {
if (ev.button !== 0) {
return;
}
setDragging(false);
};
const onPointerMove = (ev: PointerEvent) => {
setSelectedStripPart({
displayId: props.strip.display_id,
border: props.strip.border,
});
if (!(ev.buttons & 1)) {
return;
}
const draggingInfo = dragging();
if (!draggingInfo) {
return;
}
setDragCurr({ x: ev.clientX, y: ev.clientY });
const cellWidth =
(ev.currentTarget as HTMLDivElement).clientWidth / ledStripStore.totalLedCount;
const diff = ev.clientX - dragStart()!.x;
const moved = Math.round(diff / cellWidth);
if (moved === 0) {
return;
}
setCellWidth(cellWidth);
move(props.mapper.start + moved);
};
const onPointerLeave = () => {
setSelectedStripPart(null);
};
const reverse = () => {
invoke('reverse_led_strip_part', {
displayId: props.strip.display_id,
border: props.strip.border,
}).catch((err) => console.error(err));
};
// update fullLeds
createEffect(() => {
const fullLeds = new Array(ledStripStore.totalLedCount).fill(null);
const colors = ledStripStore.colors;
const { start, end, pos } = props.mapper;
const isForward = start < end;
const step = isForward ? 1 : -1;
for (let i = start, j = pos; i !== end; i += step, j++) {
let c1 = `rgb(${Math.floor(colors[j * 3] * 0.8)}, ${Math.floor(
colors[j * 3 + 1] * 0.8,
)}, ${Math.floor(colors[j * 3 + 2] * 0.8)})`;
let c2 = `rgb(${Math.min(Math.floor(colors[j * 3] * 1.2), 255)}, ${Math.min(
Math.floor(colors[j * 3 + 1] * 1.2),
255,
)}, ${Math.min(Math.floor(colors[j * 3 + 2] * 1.2), 255)})`;
fullLeds[i] = `linear-gradient(70deg, ${c1} 10%, ${c2})`;
}
setFullLeds(fullLeds);
});
const style = createMemo<JSX.CSSProperties>(() => {
return {
transform: `translateX(${(dragCurr()?.x ?? 0) - (dragStart()?.x ?? 0)}px)`,
};
});
return (
<div
class="flex h-2 m-2 select-none cursor-ew-resize focus:cursor-ew-resize"
style={style()}
onPointerMove={onPointerMove}
onPointerDown={onPointerDown}
onPointerUp={onPointerUp}
onPointerLeave={onPointerLeave}
ondblclick={reverse}
>
<For each={fullLeds()}>
{(it) => (
<div
class="flex-auto flex h-full w-full justify-center items-center relative"
title={it ?? ''}
>
<div
class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-100"
classList={{ 'ring-stone-300/50': !it }}
style={{ background: it ?? 'transparent' }}
/>
</div>
)}
</For>
</div>
);
};
const SorterResult: Component = () => {
const [fullLeds, setFullLeds] = createSignal<string[]>([]);
createEffect(() => {
const colors = ledStripStore.sortedColors;
const fullLeds = new Array(ledStripStore.totalLedCount)
.fill('rgba(255,255,255,0.1)')
.map((_, i) => {
let c1 = `rgb(${Math.floor(colors[i * 3] * 0.8)}, ${Math.floor(
colors[i * 3 + 1] * 0.8,
)}, ${Math.floor(colors[i * 3 + 2] * 0.8)})`;
let c2 = `rgb(${Math.min(Math.floor(colors[i * 3] * 1.2), 255)}, ${Math.min(
Math.floor(colors[i * 3 + 1] * 1.2),
255,
)}, ${Math.min(Math.floor(colors[i * 3 + 2] * 1.2), 255)})`;
return `linear-gradient(70deg, ${c1} 10%, ${c2})`;
});
setFullLeds(fullLeds);
});
return (
<div class="flex h-2 m-2">
<For each={fullLeds()}>
{(it) => (
<div
class="flex-auto flex h-full w-full justify-center items-center relative"
title={it}
>
<div
class="absolute top-1/2 -translate-y-1/2 h-2.5 w-2.5 rounded-full ring-1 ring-stone-300"
style={{ background: it }}
/>
</div>
)}
</For>
</div>
);
};
export const LedStripPartsSorter: Component = () => {
return (
<div
class="select-none overflow-hidden"
style={{
'background-image': `url(${background})`,
}}
>
<SorterResult />
<Index each={ledStripStore.strips}>
{(strip, index) => (
<SorterItem strip={strip()} mapper={ledStripStore.mappers[index]} />
)}
</Index>
</div>
);
};

View File

@ -0,0 +1,415 @@
import { createSignal, createEffect, For, Show, onCleanup } from 'solid-js';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { useLanguage } from '../../i18n/index';
interface BoardInfo {
fullname: string;
host: string;
address: string;
port: number;
connect_status: 'Connected' | 'Disconnected' | { Connecting: number };
}
interface TestPattern {
name: string;
description: string;
effect_type: string;
}
interface TestEffectConfig {
effect_type: string;
led_count: number;
led_type: string;
speed: number;
}
export const LedStripTest = () => {
const { t } = useLanguage();
const [boards, setBoards] = createSignal<BoardInfo[]>([]);
const [selectedBoard, setSelectedBoard] = createSignal<BoardInfo | null>(null);
const [ledCount, setLedCount] = createSignal(60);
const [ledType, setLedType] = createSignal<'WS2812B' | 'SK6812'>('WS2812B');
const [isRunning, setIsRunning] = createSignal(false);
const [currentPattern, setCurrentPattern] = createSignal<TestPattern | null>(null);
const [animationSpeed, setAnimationSpeed] = createSignal(33); // ~30fps
// Temporary input values for better UX
const [ledCountInput, setLedCountInput] = createSignal('60');
const [animationSpeedInput, setAnimationSpeedInput] = createSignal('33');
// Input handlers for LED count
const handleLedCountInput = (e: Event) => {
const target = e.target as HTMLInputElement;
setLedCountInput(target.value);
};
const handleLedCountBlur = (e: Event) => {
const target = e.target as HTMLInputElement;
const value = parseInt(target.value);
if (!isNaN(value) && value >= 1 && value <= 1000) {
setLedCount(value);
setLedCountInput(value.toString());
} else {
// Reset to current valid value
setLedCountInput(ledCount().toString());
target.value = ledCount().toString();
}
};
const handleLedCountKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter') {
handleLedCountBlur(e);
}
};
// Input handlers for animation speed
const handleAnimationSpeedInput = (e: Event) => {
const target = e.target as HTMLInputElement;
setAnimationSpeedInput(target.value);
};
const handleAnimationSpeedBlur = (e: Event) => {
const target = e.target as HTMLInputElement;
const value = parseInt(target.value);
if (!isNaN(value) && value >= 16 && value <= 200) {
setAnimationSpeed(value);
setAnimationSpeedInput(value.toString());
} else {
// Reset to current valid value
setAnimationSpeedInput(animationSpeed().toString());
target.value = animationSpeed().toString();
}
};
const handleAnimationSpeedKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter') {
handleAnimationSpeedBlur(e);
}
};
// Sync input values with actual values
createEffect(() => {
setLedCountInput(ledCount().toString());
});
createEffect(() => {
setAnimationSpeedInput(animationSpeed().toString());
});
// Load available boards and listen for changes
createEffect(() => {
// Initial load
invoke<BoardInfo[]>('get_boards').then((boardList) => {
setBoards(boardList);
if (boardList.length > 0 && !selectedBoard()) {
setSelectedBoard(boardList[0]);
}
}).catch((error) => {
console.error('Failed to load boards:', error);
});
// Listen for board changes
const unlisten = listen<BoardInfo[]>('boards_changed', (event) => {
const boardList = event.payload;
setBoards(boardList);
// If currently selected board is no longer available, select the first available one
const currentBoard = selectedBoard();
if (currentBoard) {
const stillExists = boardList.find(board =>
board.host === currentBoard.host &&
board.address === currentBoard.address &&
board.port === currentBoard.port
);
if (stillExists) {
// Update to the new board object to reflect any status changes
setSelectedBoard(stillExists);
} else {
// Current board is no longer available, select first available or null
setSelectedBoard(boardList.length > 0 ? boardList[0] : null);
}
} else if (boardList.length > 0) {
// No board was selected, select the first one
setSelectedBoard(boardList[0]);
}
});
// Cleanup listener when effect is disposed
onCleanup(() => {
unlisten.then((unlistenFn) => unlistenFn());
});
});
// Cleanup when component is unmounted
onCleanup(() => {
if (isRunning() && selectedBoard()) {
// Stop the test effect in backend
invoke('stop_led_test_effect', {
boardAddress: `${selectedBoard()!.address}:${selectedBoard()!.port}`,
ledCount: ledCount(),
ledType: ledType()
}).catch((error) => {
console.error('Failed to stop test during cleanup:', error);
});
// Update local state immediately
setIsRunning(false);
setCurrentPattern(null);
}
});
// Test patterns
const testPatterns: TestPattern[] = [
{
name: t('ledTest.flowingRainbow'),
description: t('ledTest.flowingRainbowDesc'),
effect_type: 'FlowingRainbow'
},
{
name: t('ledTest.groupCounting'),
description: t('ledTest.groupCountingDesc'),
effect_type: 'GroupCounting'
},
{
name: t('ledTest.singleScan'),
description: t('ledTest.singleScanDesc'),
effect_type: 'SingleScan'
},
{
name: t('ledTest.breathing'),
description: t('ledTest.breathingDesc'),
effect_type: 'Breathing'
}
];
// Test effect management - now handled by Rust backend
const startTest = async (pattern: TestPattern) => {
if (isRunning()) {
await stopTest();
}
if (!selectedBoard()) {
console.error('No board selected');
return;
}
try {
const effectConfig: TestEffectConfig = {
effect_type: pattern.effect_type,
led_count: ledCount(),
led_type: ledType(),
speed: 1.0 / (animationSpeed() / 50) // Convert animation speed to effect speed
};
// Start the test effect in Rust backend
await invoke('start_led_test_effect', {
boardAddress: `${selectedBoard()!.address}:${selectedBoard()!.port}`,
effectConfig: effectConfig,
updateIntervalMs: animationSpeed()
});
setCurrentPattern(pattern);
setIsRunning(true);
} catch (error) {
console.error('Failed to start test effect:', error);
}
};
const stopTest = async () => {
if (!selectedBoard()) {
setIsRunning(false);
setCurrentPattern(null);
return;
}
try {
// Stop the test effect in Rust backend
await invoke('stop_led_test_effect', {
boardAddress: `${selectedBoard()!.address}:${selectedBoard()!.port}`,
ledCount: ledCount(),
ledType: ledType()
});
// Only update UI state after successful backend call
setIsRunning(false);
setCurrentPattern(null);
} catch (error) {
console.error('Failed to stop test effect:', error);
// Still update UI state even if backend call fails
setIsRunning(false);
setCurrentPattern(null);
}
};
return (
<div class="container mx-auto p-6 space-y-6">
<div class="card bg-base-200 shadow-xl">
<div class="card-body">
<h2 class="card-title text-2xl mb-4">{t('ledTest.title')}</h2>
{/* Hardware Selection */}
<div class="form-control w-full max-w-xs">
<label class="label">
<span class="label-text">{t('ledTest.selectHardwareBoard')}</span>
<span class="label-text-alt">
{boards().length > 0 ? `${boards().length} ${t('ledTest.devicesFound')}` : t('ledTest.searching')}
</span>
</label>
<select
class="select select-bordered w-full max-w-xs"
value={selectedBoard()?.host || ''}
onChange={(e) => {
const board = boards().find(b => b.host === e.target.value);
setSelectedBoard(board || null);
}}
>
<option disabled value="">
{boards().length > 0 ? t('ledTest.chooseBoard') : t('ledTest.noBoardsFound')}
</option>
<For each={boards()}>
{(board) => {
const getStatusIcon = (status: BoardInfo['connect_status']) => {
if (status === 'Connected') return '🟢';
if (typeof status === 'object' && 'Connecting' in status) return '🟡';
return '🔴';
};
const getStatusText = (status: BoardInfo['connect_status']) => {
if (status === 'Connected') return t('ledTest.connected');
if (typeof status === 'object' && 'Connecting' in status) return t('ledTest.connecting');
return t('ledTest.disconnected');
};
return (
<option value={board.host}>
{getStatusIcon(board.connect_status)} {board.host} ({board.address}:{board.port}) - {getStatusText(board.connect_status)}
</option>
);
}}
</For>
</select>
</div>
{/* LED Configuration */}
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
<div class="form-control">
<label class="label">
<span class="label-text">{t('ledTest.ledCount')}</span>
</label>
<input
type="number"
class="input input-bordered w-full text-center text-lg"
value={ledCountInput()}
min="1"
max="1000"
onInput={handleLedCountInput}
onBlur={handleLedCountBlur}
onKeyDown={handleLedCountKeyDown}
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text">{t('ledTest.ledType')}</span>
</label>
<select
class="select select-bordered w-full"
value={ledType()}
onChange={(e) => setLedType(e.target.value as 'WS2812B' | 'SK6812')}
>
<option value="WS2812B">WS2812B</option>
<option value="SK6812">SK6812</option>
</select>
</div>
<div class="form-control">
<label class="label">
<span class="label-text">{t('ledTest.animationSpeed')}</span>
</label>
<input
type="number"
class="input input-bordered w-full text-center"
value={animationSpeedInput()}
min="16"
max="200"
step="1"
onInput={handleAnimationSpeedInput}
onBlur={handleAnimationSpeedBlur}
onKeyDown={handleAnimationSpeedKeyDown}
/>
</div>
</div>
</div>
</div>
{/* Test Patterns */}
<div class="card bg-base-200 shadow-xl">
<div class="card-body">
<h3 class="card-title text-xl mb-4">Test Patterns</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<For each={testPatterns}>
{(pattern) => (
<div class="card bg-base-100 shadow-md">
<div class="card-body">
<h4 class="card-title text-lg">{pattern.name}</h4>
<p class="text-sm opacity-70 mb-4">{pattern.description}</p>
<div class="card-actions justify-end">
<Show
when={currentPattern() === pattern && isRunning()}
fallback={
<button
class="btn btn-primary"
onClick={() => startTest(pattern)}
disabled={!selectedBoard()}
>
{t('ledTest.startTestButton')}
</button>
}
>
<button
class="btn btn-error"
onClick={() => stopTest()}
>
{t('ledTest.stopTest')}
</button>
</Show>
</div>
</div>
</div>
)}
</For>
</div>
<Show when={isRunning()}>
<div class="alert alert-info mt-4">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="stroke-current shrink-0 w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
<span>Test pattern "{currentPattern()?.name}" is running on {selectedBoard()?.host}</span>
</div>
</Show>
<Show when={!selectedBoard()}>
<div class="alert alert-warning mt-4">
<svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.728-.833-2.498 0L3.732 16c-.77.833.192 2.5 1.732 2.5z" />
</svg>
<span>Please select a hardware board to start testing</span>
</div>
</Show>
</div>
</div>
</div>
);
};

View File

@ -1,165 +0,0 @@
import { convertFileSrc } from '@tauri-apps/api/tauri';
import {
Component,
createEffect,
createSignal,
JSX,
onCleanup,
onMount,
splitProps,
} from 'solid-js';
type ScreenViewProps = {
displayId: number;
} & JSX.HTMLAttributes<HTMLDivElement>;
export const ScreenView: Component<ScreenViewProps> = (props) => {
const [localProps, rootProps] = splitProps(props, ['displayId']);
let canvas: HTMLCanvasElement;
let root: HTMLDivElement;
const [ctx, setCtx] = createSignal<CanvasRenderingContext2D | null>(null);
const [drawInfo, setDrawInfo] = createSignal({
drawX: 0,
drawY: 0,
drawWidth: 0,
drawHeight: 0,
});
const [imageData, setImageData] = createSignal<{
buffer: Uint8ClampedArray;
width: number;
height: number;
} | null>(null);
const [hidden, setHidden] = createSignal(false);
const resetSize = () => {
const aspectRatio = canvas.width / canvas.height;
const drawWidth = Math.round(
Math.min(root.clientWidth, root.clientHeight * aspectRatio),
);
const drawHeight = Math.round(
Math.min(root.clientHeight, root.clientWidth / aspectRatio),
);
const drawX = Math.round((root.clientWidth - drawWidth) / 2);
const drawY = Math.round((root.clientHeight - drawHeight) / 2);
setDrawInfo({
drawX,
drawY,
drawWidth,
drawHeight,
});
canvas.width = root.clientWidth;
canvas.height = root.clientHeight;
draw(true);
};
const draw = (cached: boolean = false) => {
const { drawX, drawY } = drawInfo();
let _ctx = ctx();
let raw = imageData();
if (_ctx && raw) {
_ctx.clearRect(0, 0, canvas.width, canvas.height);
if (cached) {
for (let i = 3; i < raw.buffer.length; i += 8) {
raw.buffer[i] = Math.floor(raw.buffer[i] * 0.7);
}
}
const img = new ImageData(raw.buffer, raw.width, raw.height);
_ctx.putImageData(img, drawX, drawY);
}
};
// get screenshot
createEffect(() => {
let stopped = false;
const frame = async () => {
const { drawWidth, drawHeight } = drawInfo();
const url = convertFileSrc(
`displays/${localProps.displayId}?width=${drawWidth}&height=${drawHeight}`,
'ambient-light',
);
await fetch(url, {
mode: 'cors',
})
.then((res) => res.body?.getReader().read())
.then((buffer) => {
if (buffer?.value) {
setImageData({
buffer: new Uint8ClampedArray(buffer?.value),
width: drawWidth,
height: drawHeight,
});
} else {
setImageData(null);
}
draw();
});
};
(async () => {
while (!stopped) {
if (hidden()) {
await new Promise((resolve) => setTimeout(resolve, 1000));
continue;
}
await frame();
}
})();
onCleanup(() => {
stopped = true;
});
});
// resize
createEffect(() => {
let resizeObserver: ResizeObserver;
onMount(() => {
setCtx(canvas.getContext('2d'));
new ResizeObserver(() => {
resetSize();
}).observe(root);
});
onCleanup(() => {
resizeObserver?.unobserve(root);
});
});
// update hidden
createEffect(() => {
const hide = () => {
setHidden(true);
console.log('hide');
};
const show = () => {
setHidden(false);
console.log('show');
};
window.addEventListener('focus', show);
window.addEventListener('blur', hide);
onCleanup(() => {
window.removeEventListener('focus', show);
window.removeEventListener('blur', hide);
});
});
return (
<div
ref={root!}
{...rootProps}
class={'overflow-hidden h-full w-full ' + rootProps.class}
>
<canvas ref={canvas!} />
{rootProps.children}
</div>
);
};

View File

@ -0,0 +1,34 @@
import { Component, JSX } from 'solid-js';
type Props = {
value?: number;
} & JSX.HTMLAttributes<HTMLInputElement>;
export const ColorSlider: Component<Props> = (props) => {
const handleMouseDown = (e: MouseEvent) => {
// 阻止事件冒泡到父元素,避免触发面板拖拽
e.stopPropagation();
};
const handleMouseMove = (e: MouseEvent) => {
// 阻止事件冒泡到父元素
e.stopPropagation();
};
return (
<input
type="range"
{...props}
max={1}
min={0}
step={0.01}
value={props.value}
class={
'range range-primary w-full bg-gradient-to-r ' +
props.class
}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
/>
);
};

View File

@ -0,0 +1,100 @@
import { Component, createSignal } from 'solid-js';
const ColorItem: Component<{
color: string;
position: [number, number];
size?: [number, number];
onClick?: (color: string) => void;
}> = (props) => {
return (
<div
style={{
background: props.color,
'grid-row-start': props.position[0],
'grid-column-start': props.position[1],
'grid-row-end': props.position[0] + (props.size ? props.size[0] : 1),
'grid-column-end': props.position[1] + (props.size ? props.size[1] : 1),
cursor: props.onClick ? 'pointer' : 'default',
}}
onClick={() => {
props.onClick?.(props.color);
}}
title={props.color}
/>
);
};
export const TestColorsBg: Component = () => {
const [singleColor, setSingleColor] = createSignal<string | null>(null);
return (
<>
<section
class="grid grid-cols-[8] grid-rows-[8] h-full w-full"
classList={{
hidden: singleColor() !== null,
}}
>
<ColorItem color="#ff0000" position={[1, 1]} onClick={setSingleColor} />
<ColorItem color="#ffff00" position={[1, 2]} onClick={setSingleColor} />
<ColorItem color="#00ff00" position={[1, 3]} onClick={setSingleColor} />
<ColorItem color="#00ffff" position={[1, 4]} onClick={setSingleColor} />
<ColorItem color="#0000ff" position={[1, 5]} onClick={setSingleColor} />
<ColorItem color="#ff00ff" position={[1, 6]} onClick={setSingleColor} />
<ColorItem color="#ffffff" position={[1, 7]} onClick={setSingleColor} />
<ColorItem color="#000000" position={[1, 8]} onClick={setSingleColor} />
<ColorItem color="#ffff00" position={[2, 1]} onClick={setSingleColor} />
<ColorItem color="#00ff00" position={[3, 1]} onClick={setSingleColor} />
<ColorItem color="#00ffff" position={[4, 1]} onClick={setSingleColor} />
<ColorItem color="#0000ff" position={[5, 1]} onClick={setSingleColor} />
<ColorItem color="#ff00ff" position={[6, 1]} onClick={setSingleColor} />
<ColorItem color="#ffffff" position={[7, 1]} onClick={setSingleColor} />
<ColorItem color="#000000" position={[8, 1]} onClick={setSingleColor} />
<ColorItem color="#ffffff" position={[2, 8]} onClick={setSingleColor} />
<ColorItem color="#ff00ff" position={[3, 8]} onClick={setSingleColor} />
<ColorItem color="#0000ff" position={[4, 8]} onClick={setSingleColor} />
<ColorItem color="#00ffff" position={[5, 8]} onClick={setSingleColor} />
<ColorItem color="#00ff00" position={[6, 8]} onClick={setSingleColor} />
<ColorItem color="#ffff00" position={[7, 8]} onClick={setSingleColor} />
<ColorItem color="#ff0000" position={[8, 8]} onClick={setSingleColor} />
<ColorItem color="#ffffff" position={[8, 2]} onClick={setSingleColor} />
<ColorItem color="#ff00ff" position={[8, 3]} onClick={setSingleColor} />
<ColorItem color="#0000ff" position={[8, 4]} onClick={setSingleColor} />
<ColorItem color="#00ffff" position={[8, 5]} onClick={setSingleColor} />
<ColorItem color="#00ff00" position={[8, 6]} onClick={setSingleColor} />
<ColorItem color="#ffff00" position={[8, 7]} onClick={setSingleColor} />
</section>
<section
class="grid grid-cols-[8] grid-rows-[8] h-full w-full"
classList={{
hidden: singleColor() === null,
}}
>
<ColorItem
color={singleColor()!}
position={[1, 1]}
size={[1, 7]}
onClick={() => setSingleColor(null)}
/>
<ColorItem
color={singleColor()!}
position={[8, 2]}
size={[1, 7]}
onClick={() => setSingleColor(null)}
/>
<ColorItem
color={singleColor()!}
position={[2, 1]}
size={[7, 1]}
onClick={() => setSingleColor(null)}
/>
<ColorItem
color={singleColor()!}
position={[1, 8]}
size={[7, 1]}
onClick={() => setSingleColor(null)}
/>
</section>
</>
);
};

View File

@ -0,0 +1,467 @@
import { listen } from '@tauri-apps/api/event';
import { Component, createEffect, onCleanup, createSignal } from 'solid-js';
import { ColorCalibration, LedStripConfigContainer } from '../../models/led-strip-config';
import { ledStripStore, setLedStripStore } from '../../stores/led-strip.store';
import { ColorSlider } from './color-slider';
import { TestColorsBg } from './test-colors-bg';
import { invoke } from '@tauri-apps/api/core';
import { VsClose } from 'solid-icons/vs';
import { BiRegularReset } from 'solid-icons/bi';
import { BsFullscreen, BsFullscreenExit } from 'solid-icons/bs';
import { getCurrentWindow } from '@tauri-apps/api/window';
import transparentBg from '../../assets/transparent-grid-background.svg?url';
import { useLanguage } from '../../i18n/index';
const Value: Component<{ value: number }> = (props) => {
return (
<div class="badge badge-outline badge-sm font-mono">
{(props.value * 100).toFixed(0)}%
</div>
);
};
export const WhiteBalance = () => {
const { t } = useLanguage();
const [isFullscreen, setIsFullscreen] = createSignal(false);
const [panelPosition, setPanelPosition] = createSignal({ x: 0, y: 0 });
const [isDragging, setIsDragging] = createSignal(false);
const [dragOffset, setDragOffset] = createSignal({ x: 0, y: 0 });
// 自动进入全屏模式
createEffect(() => {
const autoEnterFullscreen = async () => {
try {
const window = getCurrentWindow();
const currentFullscreen = await window.isFullscreen();
if (!currentFullscreen) {
await window.setFullscreen(true);
setIsFullscreen(true);
} else {
setIsFullscreen(true);
}
} catch (error) {
// Silently handle fullscreen error
}
};
autoEnterFullscreen();
});
// 初始化面板位置到屏幕中央
createEffect(() => {
if (isFullscreen()) {
const centerX = window.innerWidth / 2 - 160; // 160是面板宽度的一半
const centerY = window.innerHeight / 2 - 200; // 200是面板高度的一半
setPanelPosition({ x: centerX, y: centerY });
}
});
// 拖拽处理函数
const handleMouseDown = (e: MouseEvent) => {
// 确保只有在标题栏区域点击时才触发拖拽
setIsDragging(true);
const panelRect = (e.currentTarget as HTMLElement).closest('.fixed')?.getBoundingClientRect();
if (panelRect) {
setDragOffset({
x: e.clientX - panelRect.left,
y: e.clientY - panelRect.top
});
}
e.preventDefault();
e.stopPropagation();
};
const handleMouseMove = (e: MouseEvent) => {
if (isDragging()) {
const newX = e.clientX - dragOffset().x;
const newY = e.clientY - dragOffset().y;
// 限制面板在屏幕范围内
const maxX = window.innerWidth - 320; // 320是面板宽度
const maxY = window.innerHeight - 400; // 400是面板高度
setPanelPosition({
x: Math.max(0, Math.min(newX, maxX)),
y: Math.max(0, Math.min(newY, maxY))
});
}
};
const handleMouseUp = () => {
setIsDragging(false);
};
// 添加全局鼠标事件监听
createEffect(() => {
if (isDragging()) {
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
} else {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
}
});
// listen to config_changed event
createEffect(() => {
const unlisten = listen('config_changed', (event) => {
const { strips, mappers, color_calibration } =
event.payload as LedStripConfigContainer;
setLedStripStore({
strips,
mappers,
colorCalibration: color_calibration,
});
});
onCleanup(async () => {
(await unlisten)();
});
});
const updateColorCalibration = (
key: keyof ColorCalibration,
value: number,
) => {
const calibration = { ...ledStripStore.colorCalibration };
calibration[key] = value;
setLedStripStore('colorCalibration', calibration);
invoke('set_color_calibration', { calibration }).catch(() => {
// Silently handle error
});
};
const toggleFullscreen = async () => {
try {
const window = getCurrentWindow();
const currentFullscreen = await window.isFullscreen();
await window.setFullscreen(!currentFullscreen);
setIsFullscreen(!currentFullscreen);
// 退出全屏时重置面板位置
if (currentFullscreen) {
setPanelPosition({ x: 0, y: 0 });
}
} catch (error) {
// Silently handle fullscreen error
}
};
const exit = () => {
// 退出时确保退出全屏模式
if (isFullscreen()) {
toggleFullscreen().then(() => {
window.history.back();
});
} else {
window.history.back();
}
};
const reset = () => {
invoke('set_color_calibration', {
calibration: new ColorCalibration(),
}).catch(() => {
// Silently handle error
});
};
return (
<>
{/* 普通模式 */}
{!isFullscreen() && (
<div class="space-y-6">
<div class="flex items-center justify-between">
<h1 class="text-2xl font-bold text-base-content">{t('whiteBalance.title')}</h1>
<div class="flex gap-2">
<button class="btn btn-outline btn-sm" onClick={toggleFullscreen} title={t('common.fullscreen')}>
<BsFullscreen size={16} />
{t('common.fullscreen')}
</button>
<button class="btn btn-outline btn-sm" onClick={reset} title={t('common.reset')}>
<BiRegularReset size={16} />
{t('common.reset')}
</button>
<button class="btn btn-primary btn-sm" onClick={exit} title={t('whiteBalance.back')}>
<VsClose size={16} />
{t('whiteBalance.back')}
</button>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 颜色测试区域 */}
<div class="card bg-base-200 shadow-lg">
<div class="card-body p-4">
<div class="card-title text-base mb-3">
<span>{t('whiteBalance.colorTest')}</span>
<div class="badge badge-info badge-outline">{t('whiteBalance.clickToTest')}</div>
</div>
<div
class="aspect-square rounded-lg overflow-hidden border border-base-300"
style={{
'background-image': `url(${transparentBg})`,
}}
>
<TestColorsBg />
</div>
<div class="text-xs text-base-content/50 mt-2">
💡 {t('whiteBalance.colorTestTip')}
</div>
</div>
</div>
{/* 白平衡控制面板 */}
<div class="card bg-base-200 shadow-lg">
<div class="card-body p-4">
<div class="card-title text-base mb-3">
<span>{t('whiteBalance.rgbAdjustment')}</span>
<div class="badge badge-secondary badge-outline">{t('whiteBalance.realtimeAdjustment')}</div>
</div>
<div class="space-y-4">
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-red-500">{t('whiteBalance.redChannel')}</span>
<Value value={ledStripStore.colorCalibration.r} />
</label>
<ColorSlider
class="from-cyan-500 to-red-500"
value={ledStripStore.colorCalibration.r}
onInput={(ev) =>
updateColorCalibration(
'r',
(ev.target as HTMLInputElement).valueAsNumber ?? 1,
)
}
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-green-500">{t('whiteBalance.greenChannel')}</span>
<Value value={ledStripStore.colorCalibration.g} />
</label>
<ColorSlider
class="from-pink-500 to-green-500"
value={ledStripStore.colorCalibration.g}
onInput={(ev) =>
updateColorCalibration(
'g',
(ev.target as HTMLInputElement).valueAsNumber ?? 1,
)
}
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-blue-500">{t('whiteBalance.blueChannel')}</span>
<Value value={ledStripStore.colorCalibration.b} />
</label>
<ColorSlider
class="from-yellow-500 to-blue-500"
value={ledStripStore.colorCalibration.b}
onInput={(ev) =>
updateColorCalibration(
'b',
(ev.target as HTMLInputElement).valueAsNumber ?? 1,
)
}
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-amber-500">{t('whiteBalance.whiteChannel')}</span>
<Value value={ledStripStore.colorCalibration.w} />
</label>
<ColorSlider
class="from-amber-100 to-amber-50"
value={ledStripStore.colorCalibration.w}
onInput={(ev) =>
updateColorCalibration(
'w',
(ev.target as HTMLInputElement).valueAsNumber ?? 1,
)
}
/>
</div>
</div>
{/* 使用说明 - 可展开 */}
<div class="collapse collapse-arrow bg-base-100 mt-4">
<input type="checkbox" />
<div class="collapse-title text-sm font-medium text-base-content/80">
💡 {t('whiteBalance.usageInstructions')}
</div>
<div class="collapse-content text-xs text-base-content/70 space-y-3">
<div class="space-y-2">
<p class="font-semibold text-primary">{t('whiteBalance.recommendedMethod')}</p>
<ol class="list-decimal list-inside space-y-1 ml-2">
<li>{t('whiteBalance.fullscreenTip')}</li>
<li>{t('whiteBalance.dragTip')}</li>
<li>{t('whiteBalance.dragPanelTip')}</li>
<li>{t('whiteBalance.compareColorsTip')}</li>
</ol>
</div>
<div class="space-y-2">
<p class="font-semibold text-secondary">{t('whiteBalance.adjustmentTips')}</p>
<ul class="list-disc list-inside space-y-1 ml-2">
<li>{t('whiteBalance.redStrong')}</li>
<li>{t('whiteBalance.greenStrong')}</li>
<li>{t('whiteBalance.blueStrong')}</li>
<li>{t('whiteBalance.whiteYellow')}</li>
<li>{t('whiteBalance.whiteBlue')}</li>
</ul>
</div>
<div class="space-y-2">
<p class="font-semibold text-accent">{t('whiteBalance.comparisonMethod')}</p>
<ul class="list-disc list-inside space-y-1 ml-2">
<li>{t('whiteBalance.whiteComparison')}</li>
<li>{t('whiteBalance.colorComparison')}</li>
<li>{t('whiteBalance.environmentTest')}</li>
<li>{t('whiteBalance.resetNote')}</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)}
{/* 全屏模式 */}
{isFullscreen() && (
<div class="fixed inset-0 w-screen h-screen bg-black z-50">
{/* 全屏颜色测试区域 - 紧贴边缘 */}
<div class="absolute inset-0 w-full h-full">
<TestColorsBg />
</div>
{/* 可拖拽的RGB控制面板 */}
<div
class="fixed w-80 bg-base-200/95 backdrop-blur-sm rounded-lg shadow-xl z-60 select-none"
style={{
left: `${panelPosition().x}px`,
top: `${panelPosition().y}px`,
transform: 'none'
}}
>
<div class="card-body p-4">
<div
class="card-title text-base mb-3 flex justify-between items-center cursor-move"
onMouseDown={handleMouseDown}
>
<div class="flex items-center gap-2">
<span class="text-xs opacity-60"></span>
<span>{t('whiteBalance.rgbAdjustment')}</span>
<div class="badge badge-secondary badge-outline">{t('whiteBalance.draggable')}</div>
</div>
<button class="btn btn-ghost btn-xs cursor-pointer" onClick={toggleFullscreen} title={t('whiteBalance.exitFullscreen')}>
<BsFullscreenExit size={14} />
</button>
</div>
<div class="space-y-4">
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-red-500">{t('whiteBalance.redChannel')}</span>
<Value value={ledStripStore.colorCalibration.r} />
</label>
<ColorSlider
class="from-cyan-500 to-red-500"
value={ledStripStore.colorCalibration.r}
onInput={(ev) =>
updateColorCalibration(
'r',
(ev.target as HTMLInputElement).valueAsNumber ?? 1,
)
}
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-green-500">{t('whiteBalance.greenChannel')}</span>
<Value value={ledStripStore.colorCalibration.g} />
</label>
<ColorSlider
class="from-pink-500 to-green-500"
value={ledStripStore.colorCalibration.g}
onInput={(ev) =>
updateColorCalibration(
'g',
(ev.target as HTMLInputElement).valueAsNumber ?? 1,
)
}
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-blue-500">{t('whiteBalance.blueChannel')}</span>
<Value value={ledStripStore.colorCalibration.b} />
</label>
<ColorSlider
class="from-yellow-500 to-blue-500"
value={ledStripStore.colorCalibration.b}
onInput={(ev) =>
updateColorCalibration(
'b',
(ev.target as HTMLInputElement).valueAsNumber ?? 1,
)
}
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-amber-500">{t('whiteBalance.whiteChannel')}</span>
<Value value={ledStripStore.colorCalibration.w} />
</label>
<ColorSlider
class="from-amber-100 to-amber-50"
value={ledStripStore.colorCalibration.w}
onInput={(ev) =>
updateColorCalibration(
'w',
(ev.target as HTMLInputElement).valueAsNumber ?? 1,
)
}
/>
</div>
<div class="form-control">
<label class="label">
<span class="label-text font-semibold text-base-content/70">{t('whiteBalance.whiteChannel')}</span>
<div class="badge badge-outline badge-sm">{t('whiteBalance.notEnabled')}</div>
</label>
<ColorSlider class="from-yellow-50 to-cyan-50" disabled />
</div>
</div>
<div class="text-xs text-base-content/60 mt-3 p-2 bg-base-300/50 rounded">
💡 {t('whiteBalance.fullscreenComparisonTip')}
</div>
<div class="flex gap-2 mt-4">
<button class="btn btn-outline btn-sm flex-1" onClick={reset} title={t('common.reset')}>
<BiRegularReset size={14} />
{t('common.reset')}
</button>
<button class="btn btn-primary btn-sm flex-1" onClick={exit} title={t('whiteBalance.back')}>
<VsClose size={14} />
{t('whiteBalance.back')}
</button>
</div>
</div>
</div>
</div>
)}
</>
);
};

View File

@ -7,9 +7,14 @@ export type LedStripConfigurationContextType = [
displayId: number;
border: Borders;
} | null;
hoveredStripPart: {
displayId: number;
border: Borders;
} | null;
},
{
setSelectedStripPart: (v: { displayId: number; border: Borders } | null) => void;
setHoveredStripPart: (v: { displayId: number; border: Borders } | null) => void;
},
];
@ -17,8 +22,10 @@ export const LedStripConfigurationContext =
createContext<LedStripConfigurationContextType>([
{
selectedStripPart: null,
hoveredStripPart: null,
},
{
setSelectedStripPart: () => {},
setHoveredStripPart: () => { },
},
]);

79
src/i18n/index.tsx Normal file
View File

@ -0,0 +1,79 @@
import { createSignal, createContext, useContext, ParentComponent, createEffect } from 'solid-js';
import { Language, TranslationDict } from './types';
import { zhCN } from './locales/zh-CN';
import { enUS } from './locales/en-US';
// Available translations
const translations: Record<Language, TranslationDict> = {
'zh-CN': zhCN,
'en-US': enUS,
};
// Create locale signal
const [locale, setLocale] = createSignal<Language>('zh-CN');
// Translation function
const t = (key: string): string => {
const keys = key.split('.');
let value: any = translations[locale()];
for (const k of keys) {
if (value && typeof value === 'object' && k in value) {
value = value[k];
} else {
return key; // Return key if translation not found
}
}
return typeof value === 'string' ? value : key;
};
// Language context for managing language state
interface LanguageContextType {
locale: () => Language;
setLocale: (lang: Language) => void;
t: (key: string) => string;
}
const LanguageContext = createContext<LanguageContextType>();
// Language provider component
export const LanguageProvider: ParentComponent = (props) => {
// Load saved language preference from localStorage
createEffect(() => {
const savedLang = localStorage.getItem('app-language') as Language;
if (savedLang && (savedLang === 'zh-CN' || savedLang === 'en-US')) {
setLocale(savedLang);
}
});
// Save language preference when it changes
createEffect(() => {
localStorage.setItem('app-language', locale());
});
const contextValue: LanguageContextType = {
locale,
setLocale,
t,
};
return (
<LanguageContext.Provider value={contextValue}>
{props.children}
</LanguageContext.Provider>
);
};
// Hook to use language context
export const useLanguage = () => {
const context = useContext(LanguageContext);
if (!context) {
throw new Error('useLanguage must be used within a LanguageProvider');
}
return context;
};
// Export types and utilities
export type { Language, TranslationDict };
export { translations };

234
src/i18n/locales/en-US.ts Normal file
View File

@ -0,0 +1,234 @@
import { TranslationDict } from '../types';
export const enUS: TranslationDict = {
nav: {
title: 'Ambient Light Control',
info: 'System Info',
displays: 'Display Info',
ledConfiguration: 'LED Configuration',
whiteBalance: 'White Balance',
ledTest: 'LED Test',
},
common: {
version: 'Version',
primary: 'Primary',
save: 'Save',
cancel: 'Cancel',
reset: 'Reset',
close: 'Close',
fullscreen: 'Fullscreen',
exitFullscreen: 'Exit Fullscreen',
loading: 'Loading...',
error: 'Error',
success: 'Success',
warning: 'Warning',
confirm: 'Confirm',
delete: 'Delete',
edit: 'Edit',
add: 'Add',
remove: 'Remove',
enable: 'Enable',
disable: 'Disable',
start: 'Start',
stop: 'Stop',
test: 'Test',
apply: 'Apply',
refresh: 'Refresh',
realtime: 'Real-time',
},
info: {
title: 'System Information',
boardInfo: 'Device Information',
systemInfo: 'System Information',
deviceName: 'Device Name',
ipAddress: 'IP Address',
macAddress: 'MAC Address',
firmwareVersion: 'Firmware Version',
hardwareVersion: 'Hardware Version',
uptime: 'Uptime',
status: 'Status',
connected: 'Connected',
disconnected: 'Disconnected',
lastSeen: 'Last Seen',
port: 'Port',
latency: 'Latency',
hostname: 'Hostname',
deviceCount: 'Device Count',
noDevicesFound: 'No Devices Found',
checkConnection: 'Please check device connection status',
// Device status
timeout: 'Timeout',
connecting: 'Connecting',
},
displays: {
title: 'Display Status',
count: 'Display Count',
noDisplays: 'No displays detected',
checkConnection: 'Please check display connection',
displayInfo: 'Display Information',
resolution: 'Resolution',
refreshRate: 'Refresh Rate',
colorDepth: 'Color Depth',
isPrimary: 'Primary Display',
position: 'Position',
size: 'Size',
scaleFactor: 'Scale Factor',
lastModified: 'Last Modified',
displayCount: 'Display Count',
noDisplaysFound: 'No displays detected',
brightnessSettings: 'Brightness Settings',
currentBrightness: 'Current Brightness',
maxBrightness: 'Max Brightness',
minBrightness: 'Min Brightness',
contrastSettings: 'Contrast Settings',
currentContrast: 'Current Contrast',
maxContrast: 'Max Contrast',
minContrast: 'Min Contrast',
modeSettings: 'Mode Settings',
currentMode: 'Current Mode',
maxMode: 'Max Mode',
minMode: 'Min Mode',
// Display info panel specific
id: 'ID',
scale: 'Scale',
},
ledConfig: {
title: 'LED Strip Configuration',
displaySelection: 'Display Selection',
ledStripConfig: 'LED Strip Configuration',
ledCount: 'LED Count',
ledType: 'LED Type',
position: 'Position',
top: 'Top',
bottom: 'Bottom',
left: 'Left',
right: 'Right',
preview: 'Preview',
configuration: 'Configuration',
sorter: 'Sorter',
moveUp: 'Move Up',
moveDown: 'Move Down',
reverse: 'Reverse',
rgb: 'RGB',
rgbw: 'RGBW',
segments: 'Segments',
totalLeds: 'Total LEDs',
saveConfig: 'Save Configuration',
loadConfig: 'Load Configuration',
stripSorting: 'LED Strip Sorting',
realtimePreview: 'Real-time Preview',
sortingTip: 'Tip: Drag LED strip segments to adjust order, double-click to reverse direction',
displayConfiguration: 'Display Configuration',
visualEditor: 'Visual Editor',
displayTip: 'Tip: Hover over displays for detailed information, use control panel below to adjust LED count',
ledCountControl: 'LED Count Control',
realtimeAdjustment: 'Real-time Adjustment',
decreaseLedCount: 'Decrease LED Count',
increaseLedCount: 'Increase LED Count',
display: 'Display',
controlTip: 'Tip: Click +/- buttons or input values directly to adjust LED count (Range: 0-1000)',
},
whiteBalance: {
title: 'White Balance Adjustment',
colorCalibration: 'Color Calibration',
redChannel: 'Red (R)',
greenChannel: 'Green (G)',
blueChannel: 'Blue (B)',
whiteChannel: 'White (W)',
brightness: 'Brightness',
temperature: 'Temperature',
resetToDefault: 'Reset to Default',
fullscreenMode: 'Fullscreen Mode',
normalMode: 'Normal Mode',
instructions: 'Instructions',
helpText: 'Adjust RGB values to match screen colors with actual LED strip colors',
compareColors: 'Compare Colors',
adjustValues: 'Adjust Values',
dragToMove: 'Drag to Move Panel',
back: 'Back',
colorTest: 'Color Test',
clickToTest: 'Click to Test',
colorTestTip: 'Tip: Click color blocks for single color test, click again to return to multi-color mode',
rgbAdjustment: 'RGB Adjustment',
realtimeAdjustment: 'Real-time Adjustment',
usageInstructions: 'White Balance Adjustment Instructions',
recommendedMethod: '🎯 Recommended Method:',
adjustmentTips: '🔧 Adjustment Tips:',
comparisonMethod: '📋 Comparison Method:',
fullscreenTip: 'Click "Fullscreen" button above to enter fullscreen mode',
dragTip: 'Color strips will be displayed at screen edges in fullscreen mode',
redStrong: 'Red too strong: Lower R value to reduce red component in LEDs',
greenStrong: 'Green too strong: Lower G value to reduce green component in LEDs',
blueStrong: 'Blue too strong: Lower B value to reduce blue component in LEDs',
whiteYellow: 'White appears yellow: Increase B value, decrease R/G values',
whiteBlue: 'White appears blue: Decrease B value, increase R/G values',
whiteComparison: 'Focus on white areas, ensure LED white light matches screen white',
colorComparison: 'Check color areas, ensure LED color saturation is appropriate',
environmentTest: 'Test under different ambient lighting to ensure stable results',
resetNote: 'Click "Reset" button to restore default values after adjustment',
fullscreenComparisonTip: 'Compare screen edge colors with LED strips, adjust RGB sliders to match colors',
draggable: 'Draggable',
exitFullscreen: 'Exit Fullscreen',
notEnabled: 'Not Enabled',
// Missing white balance instructions
dragPanelTip: 'Drag the RGB control panel to a suitable position',
compareColorsTip: 'Compare LED strip colors with screen edge colors',
},
ledTest: {
title: 'LED Strip Test',
testEffects: 'Test Effects',
staticColor: 'Static Color',
rainbow: 'Rainbow',
breathing: 'Breathing',
wave: 'Wave',
chase: 'Chase',
twinkle: 'Twinkle',
fire: 'Fire',
speed: 'Speed',
brightness: 'Brightness',
color: 'Color',
startTest: 'Start Test',
stopTest: 'Stop Test',
testRunning: 'Test Running',
testStopped: 'Test Stopped',
selectEffect: 'Select Effect',
effectSettings: 'Effect Settings',
flowingRainbow: 'Flowing Rainbow',
flowingRainbowDesc: 'Rainbow flowing light for testing LED strip direction',
groupCounting: 'Group Counting',
groupCountingDesc: 'Different colors for every ten LEDs to quickly count LED quantity',
singleScan: 'Single Scan',
singleScanDesc: 'Light up each LED individually for precise position testing',
breathingDesc: 'Breathing effect for the entire LED strip to test overall brightness',
// LED test form labels
ledCount: 'LED Count',
ledType: 'LED Type',
animationSpeed: 'Animation Speed (ms)',
startTestButton: 'Start Test',
// Hardware selection
selectHardwareBoard: 'Select Hardware Board',
devicesFound: 'device(s) found',
searching: 'Searching...',
chooseBoard: 'Choose a board',
noBoardsFound: 'No boards found',
connected: 'Connected',
connecting: 'Connecting',
disconnected: 'Disconnected',
},
errors: {
failedToLoad: 'Failed to load',
failedToSave: 'Failed to save',
failedToConnect: 'Failed to connect',
invalidConfiguration: 'Invalid configuration',
deviceNotFound: 'Device not found',
networkError: 'Network error',
unknownError: 'Unknown error',
},
};

234
src/i18n/locales/zh-CN.ts Normal file
View File

@ -0,0 +1,234 @@
import { TranslationDict } from '../types';
export const zhCN: TranslationDict = {
nav: {
title: '环境光控制',
info: '基本信息',
displays: '显示器信息',
ledConfiguration: '灯条配置',
whiteBalance: '白平衡',
ledTest: '灯带测试',
},
common: {
version: '版本',
primary: '主要',
save: '保存',
cancel: '取消',
reset: '重置',
close: '关闭',
fullscreen: '全屏',
exitFullscreen: '退出全屏',
loading: '加载中...',
error: '错误',
success: '成功',
warning: '警告',
confirm: '确认',
delete: '删除',
edit: '编辑',
add: '添加',
remove: '移除',
enable: '启用',
disable: '禁用',
start: '开始',
stop: '停止',
test: '测试',
apply: '应用',
refresh: '刷新',
realtime: '实时',
},
info: {
title: '基本信息',
boardInfo: '设备信息',
systemInfo: '系统信息',
deviceName: '设备名称',
ipAddress: 'IP地址',
macAddress: 'MAC地址',
firmwareVersion: '固件版本',
hardwareVersion: '硬件版本',
uptime: '运行时间',
status: '状态',
connected: '已连接',
disconnected: '已断开',
lastSeen: '最后连接',
port: '端口',
latency: '延迟',
hostname: '主机名',
deviceCount: '设备总数',
noDevicesFound: '未发现设备',
checkConnection: '请检查设备连接状态',
// Device status
timeout: '超时',
connecting: '连接中',
},
displays: {
title: '显示器状态',
count: '显示器数量',
noDisplays: '未检测到显示器',
checkConnection: '请检查显示器连接状态',
displayInfo: '显示器信息',
resolution: '分辨率',
refreshRate: '刷新率',
colorDepth: '色深',
isPrimary: '主显示器',
position: '位置',
size: '尺寸',
scaleFactor: '缩放比例',
lastModified: '最后修改',
displayCount: '显示器数量',
noDisplaysFound: '未检测到显示器',
brightnessSettings: '亮度设置',
currentBrightness: '当前亮度',
maxBrightness: '最大亮度',
minBrightness: '最小亮度',
contrastSettings: '对比度设置',
currentContrast: '当前对比度',
maxContrast: '最大对比度',
minContrast: '最小对比度',
modeSettings: '模式设置',
currentMode: '当前模式',
maxMode: '最大模式',
minMode: '最小模式',
// Display info panel specific
id: 'ID',
scale: '缩放',
},
ledConfig: {
title: '灯条配置',
displaySelection: '显示器选择',
ledStripConfig: '灯条配置',
ledCount: '灯珠数量',
ledType: '灯珠类型',
position: '位置',
top: '顶部',
bottom: '底部',
left: '左侧',
right: '右侧',
preview: '预览',
configuration: '配置',
sorter: '排序器',
moveUp: '上移',
moveDown: '下移',
reverse: '反转',
rgb: 'RGB',
rgbw: 'RGBW',
segments: '段数',
totalLeds: '总灯珠数',
saveConfig: '保存配置',
loadConfig: '加载配置',
stripSorting: '灯条排序',
realtimePreview: '实时预览',
sortingTip: '提示:拖拽灯条段落来调整顺序,双击可反转方向',
displayConfiguration: '显示器配置',
visualEditor: '可视化编辑',
displayTip: '提示悬停显示器查看详细信息使用下方控制面板调整LED数量',
ledCountControl: 'LED数量控制',
realtimeAdjustment: '实时调整',
decreaseLedCount: '减少LED数量',
increaseLedCount: '增加LED数量',
display: '显示器',
controlTip: '提示:点击 +/- 按钮或直接输入数值来调整LED数量范围0-1000',
},
whiteBalance: {
title: '白平衡调节',
colorCalibration: '颜色校准',
redChannel: '红色 (R)',
greenChannel: '绿色 (G)',
blueChannel: '蓝色 (B)',
whiteChannel: '白色 (W)',
brightness: '亮度',
temperature: '色温',
resetToDefault: '重置为默认值',
fullscreenMode: '全屏模式',
normalMode: '普通模式',
instructions: '使用说明',
helpText: '调整RGB值以匹配屏幕颜色与LED灯条的实际颜色',
compareColors: '比较颜色',
adjustValues: '调整数值',
dragToMove: '拖拽移动面板',
back: '返回',
colorTest: '颜色测试',
clickToTest: '点击测试',
colorTestTip: '提示:点击颜色块进行单色测试,再次点击返回多色模式',
rgbAdjustment: 'RGB调节',
realtimeAdjustment: '实时调节',
usageInstructions: '白平衡调节使用说明',
recommendedMethod: '🎯 推荐使用方法:',
adjustmentTips: '🔧 调节技巧:',
comparisonMethod: '📋 对比方法:',
fullscreenTip: '点击上方"全屏"按钮进入全屏模式',
dragTip: '全屏模式下屏幕边缘会显示彩色条带',
redStrong: '红色偏强降低R值LED会减少红色成分',
greenStrong: '绿色偏强降低G值LED会减少绿色成分',
blueStrong: '蓝色偏强降低B值LED会减少蓝色成分',
whiteYellow: '白色发黄适当提高B值降低R/G值',
whiteBlue: '白色发蓝适当降低B值提高R/G值',
whiteComparison: '重点观察白色区域确保LED白光与屏幕白色一致',
colorComparison: '检查彩色区域确保LED颜色饱和度合适',
environmentTest: '在不同环境光下测试,确保效果稳定',
resetNote: '调节完成后可点击"重置"按钮恢复默认值',
fullscreenComparisonTip: '对比屏幕边缘颜色与LED灯条调节RGB滑块使颜色一致',
draggable: '可拖拽',
exitFullscreen: '退出全屏',
notEnabled: '暂未启用',
// Missing white balance instructions
dragPanelTip: '将RGB控制面板拖拽到合适位置',
compareColorsTip: '对比LED灯条颜色与屏幕边缘颜色',
},
ledTest: {
title: 'LED灯带测试',
testEffects: '测试效果',
staticColor: '静态颜色',
rainbow: '彩虹',
breathing: '呼吸',
wave: '波浪',
chase: '追逐',
twinkle: '闪烁',
fire: '火焰',
speed: '速度',
brightness: '亮度',
color: '颜色',
startTest: '开始测试',
stopTest: '停止测试',
testRunning: '测试运行中',
testStopped: '测试已停止',
selectEffect: '选择效果',
effectSettings: '效果设置',
flowingRainbow: '流光效果',
flowingRainbowDesc: '彩虹色流光,用于测试灯带方向',
groupCounting: '十个一组计数',
groupCountingDesc: '每十个LED一组不同颜色用于快速计算灯珠数量',
singleScan: '单色扫描',
singleScanDesc: '单个LED依次点亮用于精确测试每个LED位置',
breathingDesc: '整条灯带呼吸效果,用于测试整体亮度',
// LED test form labels
ledCount: 'LED数量',
ledType: 'LED类型',
animationSpeed: '动画速度 (ms)',
startTestButton: '开始测试',
// Hardware selection
selectHardwareBoard: '选择硬件板',
devicesFound: '个设备',
searching: '搜索中...',
chooseBoard: '选择设备',
noBoardsFound: '未找到设备',
connected: '已连接',
connecting: '连接中',
disconnected: '已断开',
},
errors: {
failedToLoad: '加载失败',
failedToSave: '保存失败',
failedToConnect: '连接失败',
invalidConfiguration: '配置无效',
deviceNotFound: '设备未找到',
networkError: '网络错误',
unknownError: '未知错误',
},
};

242
src/i18n/types.ts Normal file
View File

@ -0,0 +1,242 @@
export type Language = 'zh-CN' | 'en-US';
export interface TranslationDict {
// Navigation
nav: {
title: string;
info: string;
displays: string;
ledConfiguration: string;
whiteBalance: string;
ledTest: string;
};
// Common UI elements
common: {
version: string;
primary: string;
save: string;
cancel: string;
reset: string;
close: string;
fullscreen: string;
exitFullscreen: string;
loading: string;
error: string;
success: string;
warning: string;
confirm: string;
delete: string;
edit: string;
add: string;
remove: string;
enable: string;
disable: string;
start: string;
stop: string;
test: string;
apply: string;
refresh: string;
realtime: string;
};
// Info page
info: {
title: string;
boardInfo: string;
systemInfo: string;
deviceName: string;
ipAddress: string;
macAddress: string;
firmwareVersion: string;
hardwareVersion: string;
uptime: string;
status: string;
connected: string;
disconnected: string;
lastSeen: string;
port: string;
latency: string;
hostname: string;
deviceCount: string;
noDevicesFound: string;
checkConnection: string;
// Device status
timeout: string;
connecting: string;
};
// Display page
displays: {
title: string;
count: string;
noDisplays: string;
checkConnection: string;
displayInfo: string;
resolution: string;
refreshRate: string;
colorDepth: string;
isPrimary: string;
position: string;
size: string;
scaleFactor: string;
lastModified: string;
displayCount: string;
noDisplaysFound: string;
brightnessSettings: string;
currentBrightness: string;
maxBrightness: string;
minBrightness: string;
contrastSettings: string;
currentContrast: string;
maxContrast: string;
minContrast: string;
modeSettings: string;
currentMode: string;
maxMode: string;
minMode: string;
// Display info panel specific
id: string;
scale: string;
};
// LED Strip Configuration
ledConfig: {
title: string;
displaySelection: string;
ledStripConfig: string;
ledCount: string;
ledType: string;
position: string;
top: string;
bottom: string;
left: string;
right: string;
preview: string;
configuration: string;
sorter: string;
moveUp: string;
moveDown: string;
reverse: string;
rgb: string;
rgbw: string;
segments: string;
totalLeds: string;
saveConfig: string;
loadConfig: string;
stripSorting: string;
realtimePreview: string;
sortingTip: string;
displayConfiguration: string;
visualEditor: string;
displayTip: string;
ledCountControl: string;
realtimeAdjustment: string;
decreaseLedCount: string;
increaseLedCount: string;
display: string;
controlTip: string;
};
// White Balance
whiteBalance: {
title: string;
colorCalibration: string;
redChannel: string;
greenChannel: string;
blueChannel: string;
whiteChannel: string;
brightness: string;
temperature: string;
resetToDefault: string;
fullscreenMode: string;
normalMode: string;
instructions: string;
helpText: string;
compareColors: string;
adjustValues: string;
dragToMove: string;
back: string;
colorTest: string;
clickToTest: string;
colorTestTip: string;
rgbAdjustment: string;
realtimeAdjustment: string;
usageInstructions: string;
recommendedMethod: string;
adjustmentTips: string;
comparisonMethod: string;
fullscreenTip: string;
dragTip: string;
redStrong: string;
greenStrong: string;
blueStrong: string;
whiteYellow: string;
whiteBlue: string;
whiteComparison: string;
colorComparison: string;
environmentTest: string;
resetNote: string;
fullscreenComparisonTip: string;
draggable: string;
exitFullscreen: string;
notEnabled: string;
// Missing white balance instructions
dragPanelTip: string;
compareColorsTip: string;
};
// LED Test
ledTest: {
title: string;
testEffects: string;
staticColor: string;
rainbow: string;
breathing: string;
wave: string;
chase: string;
twinkle: string;
fire: string;
speed: string;
brightness: string;
color: string;
startTest: string;
stopTest: string;
testRunning: string;
testStopped: string;
selectEffect: string;
effectSettings: string;
flowingRainbow: string;
flowingRainbowDesc: string;
groupCounting: string;
groupCountingDesc: string;
singleScan: string;
singleScanDesc: string;
breathingDesc: string;
// LED test form labels
ledCount: string;
ledType: string;
animationSpeed: string;
startTestButton: string;
// Hardware selection
selectHardwareBoard: string;
devicesFound: string;
searching: string;
chooseBoard: string;
noBoardsFound: string;
connected: string;
connecting: string;
disconnected: string;
};
// Error messages
errors: {
failedToLoad: string;
failedToSave: string;
failedToConnect: string;
invalidConfiguration: string;
deviceNotFound: string;
networkError: string;
unknownError: string;
};
}

View File

@ -3,5 +3,16 @@ import { render } from "solid-js/web";
import "./styles.css";
import App from "./App";
import { Router } from '@solidjs/router';
import { LanguageProvider } from './i18n/index';
render(() => <App />, document.getElementById("root") as HTMLElement);
render(
() => (
<LanguageProvider>
<Router>
<App />
</Router>
</LanguageProvider>
),
document.getElementById('root') as HTMLElement,
);

View File

@ -0,0 +1,9 @@
export type BoardInfo = {
fullname: string;
host: string;
address: string;
port: number;
ttl: number;
connect_status: 'Connected' | 'Disconnected' | { Connecting: number };
checked_at: Date;
};

View File

@ -0,0 +1,16 @@
export type DisplayState = {
brightness: number;
max_brightness: number;
min_brightness: number;
contrast: number;
max_contrast: number;
min_contrast: number;
mode: number;
max_mode: number;
min_mode: number;
last_modified_at: Date;
};
export type RawDisplayState = DisplayState & {
last_modified_at: { secs_since_epoch: number };
};

View File

@ -1,14 +1,27 @@
import { Borders } from '../constants/border';
export enum LedType {
WS2812B = 'WS2812B',
SK6812 = 'SK6812',
}
export type LedStripPixelMapper = {
start: number;
end: number;
pos: number;
};
export class ColorCalibration {
r: number = 1;
g: number = 1;
b: number = 1;
w: number = 1;
}
export type LedStripConfigContainer = {
strips: LedStripConfig[];
mappers: LedStripPixelMapper[];
color_calibration: ColorCalibration;
};
export class LedStripConfig {
@ -16,5 +29,6 @@ export class LedStripConfig {
public readonly display_id: number,
public readonly border: Borders,
public len: number,
public led_type: LedType = LedType.WS2812B,
) {}
}

View File

@ -1,12 +1,26 @@
import { createStore } from 'solid-js/store';
import { LedStripConfig, LedStripPixelMapper } from '../models/led-strip-config';
import {
ColorCalibration,
LedStripConfig,
LedStripPixelMapper,
} from '../models/led-strip-config';
export const [ledStripStore, setLedStripStore] = createStore({
strips: new Array<LedStripConfig>(),
mappers: new Array<LedStripPixelMapper>(),
colorCalibration: new ColorCalibration(),
colors: new Uint8ClampedArray(),
sortedColors: new Uint8ClampedArray(),
get totalLedCount() {
return Math.max(0, ...ledStripStore.mappers.map((m) => Math.max(m.start, m.end)));
return Math.max(
0,
...ledStripStore.mappers.map((m) => {
if (m.start === m.end) {
return 0;
} else {
return Math.max(m.start, m.end);
}
}),
);
},
});

View File

@ -1,3 +1,24 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@import "tailwindcss";
@config "../tailwind.config.js";
/* Custom responsive styles for small windows */
@media (max-width: 640px) {
.container {
max-width: 100%;
padding-left: 0.5rem;
padding-right: 0.5rem;
}
}
/* Ensure LED control panels are responsive */
.led-control-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 0.75rem;
}
@media (max-width: 600px) {
.led-control-grid {
grid-template-columns: 1fr;
}
}

View File

@ -1,9 +1,20 @@
import daisyui from 'daisyui';
/** @type {import('tailwindcss').Config} */
module.exports = {
mode: 'jit',
export default {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
theme: {
extend: {},
},
plugins: [],
plugins: [daisyui],
daisyui: {
themes: ["dark", "light"],
darkTheme: "dark",
base: true,
styled: true,
utils: true,
prefix: "",
logs: true,
themeRoot: ":root",
},
};

View File

@ -6,8 +6,14 @@ const mobile =
process.env.TAURI_PLATFORM === "ios";
// https://vitejs.dev/config/
export default defineConfig(async () => ({
plugins: [solidPlugin()],
export default defineConfig(async () => {
const tailwindcss = (await import("@tailwindcss/vite")).default;
return {
plugins: [
solidPlugin(),
tailwindcss(),
],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
// prevent vite from obscuring rust errors
@ -28,4 +34,5 @@ export default defineConfig(async () => ({
// produce sourcemaps for debug builds
sourcemap: !!process.env.TAURI_DEBUG,
},
}));
};
});