mirror of
https://github.com/wled/WLED.git
synced 2026-06-23 21:31:29 +00:00
Compare commits
212 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f5adaaa44e | |||
| 78c1051cbb | |||
| 121250c0a0 | |||
| 2302863386 | |||
| 7560811480 | |||
| 252007d37f | |||
| 6e76a69417 | |||
| 24e2e3c195 | |||
| f1c58ee75f | |||
| c8fc1c89b6 | |||
| 12f6fbc005 | |||
| c819814904 | |||
| 0ef5ee74d4 | |||
| 51862e3572 | |||
| aaf51927a6 | |||
| 72a43c6431 | |||
| 7c6828d443 | |||
| f8f46736ec | |||
| e4f8534cf0 | |||
| 79ecffe0f3 | |||
| 1fb636d8ea | |||
| e04c855e6c | |||
| 6a627a86b7 | |||
| 746df24011 | |||
| da64f71ce2 | |||
| 8972b6bfe2 | |||
| 8241468fe2 | |||
| e9b740a915 | |||
| 548bb6ffd5 | |||
| a5f28d0fcb | |||
| fb8f8f0b08 | |||
| 53fdf9a89c | |||
| a1316034c1 | |||
| 75df4affa8 | |||
| 820c841376 | |||
| 34d50710b3 | |||
| d0d62d9493 | |||
| 89b2bc2992 | |||
| 472fca7486 | |||
| 42844e4fa8 | |||
| 4a6ff64519 | |||
| f6a43f4dfa | |||
| b7d2c3cd85 | |||
| 20c021d9b8 | |||
| 9c93cb8cf0 | |||
| ad5043f7e0 | |||
| 5ac282f8b9 | |||
| e4351c8979 | |||
| e019d36221 | |||
| 6a16593be5 | |||
| 3bcb0c902e | |||
| 78ecd3805e | |||
| 4c7fa0303b | |||
| 75b679814b | |||
| d8cb20a9e7 | |||
| 710f897a1d | |||
| abb4124ab4 | |||
| 3c7fbabd23 | |||
| bda74bafb8 | |||
| 9cf3a7d184 | |||
| 5cef850c47 | |||
| 74763040ad | |||
| 7a635c88d6 | |||
| dc5a7350d2 | |||
| 81f251c125 | |||
| ff9067f10b | |||
| 144c0f9dd6 | |||
| a721264205 | |||
| f28cbea2c2 | |||
| 3b256eed1e | |||
| 610c80a0ae | |||
| aa6cd883c2 | |||
| 7006285856 | |||
| 7e490fcd28 | |||
| 6f030e540f | |||
| a63a307c6e | |||
| b57d51ef19 | |||
| 34722aa371 | |||
| 19c178d0f9 | |||
| 3244d0f593 | |||
| 64f3aa96dd | |||
| f816b5fa98 | |||
| e4cd730654 | |||
| c7fa496fda | |||
| 40442551ef | |||
| cfa93c9778 | |||
| c35358c005 | |||
| 2ab9659332 | |||
| 3bfdb736e3 | |||
| 53d6c4b059 | |||
| 5beafe0a7d | |||
| 7f44396f7f | |||
| 5e1ae99767 | |||
| 1da5dc7d18 | |||
| 05498f2ae4 | |||
| 9ae1ef506c | |||
| cd1c5ca6bd | |||
| b07cd45642 | |||
| 278a1fb6c1 | |||
| 0e1da4f004 | |||
| 5f5f468983 | |||
| c604b99a4c | |||
| 5f28406f42 | |||
| bc229b8cb6 | |||
| 5790309371 | |||
| 210b4d8f54 | |||
| 19292675d8 | |||
| ac1a4dfbfd | |||
| 7fa15761ae | |||
| 35d267109f | |||
| 3bfbbab807 | |||
| b97b46ae12 | |||
| 26d2cc971a | |||
| 3972b6e8fb | |||
| 3116e88cdc | |||
| 1c2f70598a | |||
| 6f65b46b14 | |||
| 1c8dd8ecd2 | |||
| 55c4288cb6 | |||
| 231fb5a7ca | |||
| 536b40c6f1 | |||
| d3a8da212c | |||
| 522927ea94 | |||
| 4178d05c6a | |||
| 2d1315f9dc | |||
| 822e07d9f5 | |||
| 439d4a0e98 | |||
| 1f102ca832 | |||
| 43e86d0f4d | |||
| 29e9c73274 | |||
| 6240ee69fc | |||
| 14bd5d615b | |||
| e0441c8876 | |||
| 1ee42f0206 | |||
| d1ed547a7c | |||
| f830ea498c | |||
| ce31d802d5 | |||
| f09c449ad5 | |||
| 6bebb8b4a8 | |||
| e3bc32a823 | |||
| 6b70c6ae91 | |||
| b9138b4300 | |||
| 7a157a8c91 | |||
| 7387baace4 | |||
| 80e75139c6 | |||
| e9ced6ddf1 | |||
| 6d1d494cf5 | |||
| 65daf26aee | |||
| 591f65fcee | |||
| 8b6d4134bd | |||
| 2102bb12f0 | |||
| 747bc2bacd | |||
| 4d63b3c8a0 | |||
| 147384074d | |||
| 129137d96c | |||
| 0120b1ab79 | |||
| c64b1e3e5d | |||
| 0c08c27df4 | |||
| 2676ac771d | |||
| 680ef26f4d | |||
| eb4bd6fbb1 | |||
| e78b4a245d | |||
| 73ae3de5b8 | |||
| a6b107e8df | |||
| 6b953d96eb | |||
| 3d33bae2b8 | |||
| f2df029f26 | |||
| 761eb99e53 | |||
| 2434a9624e | |||
| 03d0522cf1 | |||
| 642c99a617 | |||
| 76c25da58e | |||
| b51e7b65f9 | |||
| 78166090bc | |||
| 6d788a27b6 | |||
| 32cda7d793 | |||
| c180a3fe6f | |||
| 1ca55e42af | |||
| ba677d1a32 | |||
| 354da8fdc0 | |||
| 2c4ed4249d | |||
| 39bf31d3a1 | |||
| 50ef8db595 | |||
| d4f365e7e5 | |||
| f19d29cd64 | |||
| 1031e70d70 | |||
| c9f47d4b5c | |||
| 857e73ab25 | |||
| 4e072962c0 | |||
| 81af160be6 | |||
| a64334c32e | |||
| 8d39dac654 | |||
| e867fcab1a | |||
| 9683896a21 | |||
| ca1d6614b2 | |||
| 96f423438b | |||
| df94a8d5af | |||
| d9cc751db4 | |||
| 99c3f68f80 | |||
| be900737d2 | |||
| af8db57f02 | |||
| 1773f61ded | |||
| 51a14ede8b | |||
| 788c09972e | |||
| ba21ab55f8 | |||
| 1585cab3ba | |||
| 6ca8ed65e8 | |||
| 6a2b7995e9 | |||
| 247a7a51d7 | |||
| 379343278d | |||
| 0b965ea431 | |||
| d6cd65e108 |
@@ -0,0 +1,82 @@
|
||||
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
|
||||
#
|
||||
# CodeRabbit configuration — references existing guideline files to avoid
|
||||
# duplicating conventions. See:
|
||||
# .github/copilot-instructions.md — project overview & general rules
|
||||
# docs/cpp.instructions.md — C++ coding conventions
|
||||
# docs/web.instructions.md — Web UI coding conventions
|
||||
# docs/cicd.instructions.md — GitHub Actions / CI-CD conventions
|
||||
#
|
||||
# NOTE: This file must be committed (tracked by git) for CodeRabbit to read
|
||||
# it from the repository. If it is listed in .gitignore, CodeRabbit will
|
||||
# not see it and these settings will have no effect.
|
||||
|
||||
language: en-US
|
||||
|
||||
reviews:
|
||||
path_instructions:
|
||||
- path: "**/*.{cpp,h,hpp,ino}"
|
||||
instructions: >
|
||||
Follow the C++ coding conventions documented in docs/cpp.instructions.md
|
||||
and the general project guidelines in .github/copilot-instructions.md.
|
||||
|
||||
Key rules: 2-space indentation (no tabs), camelCase functions/variables,
|
||||
PascalCase classes, UPPER_CASE macros. No C++ exceptions — use return codes and debug macros.
|
||||
|
||||
Hot-path optimization guidelines (attributes, uint_fast types, caching,
|
||||
unsigned range checks) apply from pixel set/get operations and strip.show() downward —
|
||||
NOT to effect functions in FX.cpp, which have diverse contributor styles.
|
||||
|
||||
- path: "wled00/data/**"
|
||||
instructions: >
|
||||
Follow the web UI conventions documented in docs/web.instructions.md.
|
||||
|
||||
Key rules: indent HTML and JavaScript with tabs, CSS with tabs.
|
||||
Files here are built into wled00/html_*.h and wled00/js_*.h by tools/cdata.js — never
|
||||
edit those generated headers directly.
|
||||
|
||||
- path: "wled00/html_*.h"
|
||||
instructions: >
|
||||
These files are auto-generated from wled00/data/ by tools/cdata.js.
|
||||
They must never be manually edited or committed. Flag any PR that
|
||||
includes changes to these files.
|
||||
|
||||
- path: "wled00/js_*.h"
|
||||
instructions: >
|
||||
These files are auto-generated from wled00/data/ by tools/cdata.js.
|
||||
They must never be manually edited or committed. Flag any PR that
|
||||
includes changes to these files.
|
||||
|
||||
- path: "usermods/**"
|
||||
instructions: >
|
||||
Usermods are community add-ons.
|
||||
Each usermod lives in its own directory under usermods/ and is implemented
|
||||
as a .cpp file with a dedicated library.json file to manage dependencies.
|
||||
Follow the same C++ conventions as the core firmware (docs/cpp.instructions.md).
|
||||
|
||||
- path: ".github/workflows/*.{yml,yaml}"
|
||||
instructions: >
|
||||
Follow the CI/CD conventions documented in docs/cicd.instructions.md.
|
||||
|
||||
Key rules: 2-space indentation, descriptive name: on every workflow/job/step.
|
||||
Third-party actions must be pinned to a specific version tag — branch pins
|
||||
such as @main or @master are not allowed. Declare explicit permissions: blocks
|
||||
scoped to least privilege. Never interpolate github.event.* values directly
|
||||
into run: steps — pass them through an env: variable to prevent script
|
||||
injection. Do not use pull_request_target unless fully justified.
|
||||
|
||||
- path: "**/*.instructions.md"
|
||||
instructions: |
|
||||
This file contains both AI-facing rules and human-only reference sections.
|
||||
Human-only sections are enclosed in `<!-- HUMAN_ONLY_START -->` /
|
||||
`<!-- HUMAN_ONLY_END -->` HTML comment markers and should not be used as
|
||||
actionable review criteria.
|
||||
|
||||
When this file is modified in a PR, perform the following alignment check:
|
||||
1. For each `<!-- HUMAN_ONLY_START --> ... <!-- HUMAN_ONLY_END -->` block,
|
||||
verify that its examples and guidance are consistent with (and do not
|
||||
contradict) the AI-facing rules stated in the same file.
|
||||
2. Flag any HUMAN_ONLY section whose content has drifted from the surrounding
|
||||
AI-facing rules due to edits introduced in this PR.
|
||||
3. If new AI-facing rules were added without updating a related HUMAN_ONLY
|
||||
reference section, note this as a suggestion (not a required fix).
|
||||
@@ -63,6 +63,8 @@ body:
|
||||
- ESP32-S2
|
||||
- ESP32-C3
|
||||
- Other
|
||||
- ESP32-C6 (experimental)
|
||||
- ESP32-C5 (experimental)
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
---
|
||||
applyTo: "**"
|
||||
---
|
||||
# Agent-Mode Build & Test Instructions
|
||||
|
||||
Detailed build workflow, timeouts, and troubleshooting for making code changes in agent mode. Always reference these instructions first when running builds or validating changes.
|
||||
|
||||
## Build Timing and Timeouts
|
||||
|
||||
Use these timeout values when running builds:
|
||||
|
||||
| Command | Typical Time | Minimum Timeout | Notes |
|
||||
|---|---|---|---|
|
||||
| `npm run build` | ~3 s | 30 s | Web UI → `wled00/html_*.h` `wled00/js_*.h` headers |
|
||||
| `npm test` | ~40 s | 2 min | Validates build system |
|
||||
| `npm run dev` | continuous | — | Watch mode, auto-rebuilds on changes |
|
||||
| `pio run -e <env>` | 15–20 min | 30 min | First build downloads toolchains; subsequent builds are faster |
|
||||
|
||||
**NEVER cancel long-running builds.** PlatformIO downloads and compilation require patience.
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Code Style Summary
|
||||
- **C++** files in `wled00/` and `usermods/`: 2-space indentation (no tabs), camelCase functions/variables, PascalCase classes, UPPER_CASE macros. No C++ exceptions — use return codes and debug macros.
|
||||
- **Web UI** files in `wled00/data`: indent HTML and JavaScript with tabs, CSS with tabs.
|
||||
- **CI/CD workflows** in `.github/workflows`: 2-space indentation, descriptive `name:` on every workflow/job/step. Third-party actions must be pinned to a specific version tag — branch pins such as `@main` or `@master` are not allowed. SHA pinning recommended.
|
||||
|
||||
### Web UI Changes
|
||||
|
||||
1. Edit files in `wled00/data/`
|
||||
2. Run `npm run build` to regenerate `wled00/html_*.h` `wled00/js_*.h` headers
|
||||
3. Test with local HTTP server (see Manual Testing below)
|
||||
4. Run `npm test` to validate
|
||||
|
||||
### Firmware Changes
|
||||
|
||||
1. Edit files in `wled00/` (but **never** `html_*.h` and `js_*.h` files)
|
||||
2. Ensure web UI is built first: `npm run build`
|
||||
3. Build firmware: `pio run -e esp32dev` (set timeout ≥ 30 min)
|
||||
4. Flash to device: `pio run -e [target] --target upload`
|
||||
|
||||
### Combined Web + Firmware Changes
|
||||
|
||||
1. Always build web UI first
|
||||
2. Test web interface manually
|
||||
3. Then build and test firmware
|
||||
|
||||
|
||||
## Before Finishing Work - Testing
|
||||
|
||||
**You MUST complete ALL of these before marking work as done:**
|
||||
|
||||
1. **Run tests**: `npm test` — must pass
|
||||
2. **Build firmware**: `pio run -e esp32dev` — must succeed after source code changes, **never skip this step**.
|
||||
- Set timeout to 30+ minutes, **never cancel**
|
||||
- Choose `esp32dev` as a common, representative environment
|
||||
- If the build fails, fix the issue before proceeding
|
||||
3. **For web UI changes**: manually test the interface (see below)
|
||||
|
||||
If any step fails, fix the issue. **Do NOT mark work complete with failing builds or tests.**
|
||||
|
||||
## Manual Web UI Testing
|
||||
|
||||
Start a local server:
|
||||
|
||||
```sh
|
||||
cd wled00/data && python3 -m http.server 8080
|
||||
# Open http://localhost:8080/index.htm
|
||||
```
|
||||
|
||||
Test these scenarios after every web UI change:
|
||||
|
||||
- **Load**: `index.htm` loads without JavaScript errors (check browser console)
|
||||
- **Navigation**: switching between main page and settings pages works
|
||||
- **Color controls**: color picker and brightness controls function correctly
|
||||
- **Effects**: effect selection and parameter changes work
|
||||
- **Settings**: form submission and validation work
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Build Issues
|
||||
|
||||
| Problem | Solution |
|
||||
|---|---|
|
||||
| Missing `html_*.h` | Run `npm ci; npm run build` |
|
||||
| Web UI looks broken | Check browser console for JS errors |
|
||||
| PlatformIO network errors | Retry — downloads can be flaky |
|
||||
| Node.js version mismatch | Ensure Node.js 20+ (check `.nvmrc`) |
|
||||
|
||||
### Recovery Steps
|
||||
|
||||
- **Force web UI rebuild**: `npm run build -- -f`
|
||||
- **Clear generated files**: `rm -f wled00/html_*.h wled00/js_*.h` then `npm run build`
|
||||
- **Clean PlatformIO build artifacts**: `pio run --target clean`
|
||||
- **Reinstall Node deps**: `rm -rf node_modules && npm ci`
|
||||
|
||||
## CI/CD Validation
|
||||
|
||||
The GitHub Actions CI workflow will:
|
||||
1. Install Node.js and Python dependencies
|
||||
2. Run `npm test`
|
||||
3. Build web UI (automatic via PlatformIO)
|
||||
4. Compile firmware for **all** `default_envs` targets
|
||||
|
||||
**To ensure CI success, always validate locally:**
|
||||
- Run `npm test` and ensure it passes
|
||||
- Run `pio run -e esp32dev` (or another common firmware environment, see next section) and ensure it completes successfully
|
||||
- If either fails locally, it WILL fail in CI
|
||||
|
||||
Match this workflow in local development to catch failures before pushing.
|
||||
|
||||
## Important Reminders
|
||||
|
||||
- Always **commit source code**
|
||||
- **Never edit or commit** `wled00/html_*.h` and `wled00/js_*.h` — auto-generated from `wled00/data/`
|
||||
- Web UI rebuild is part of the PlatformIO firmware compilation pipeline
|
||||
- Common environments: `nodemcuv2`, `esp32dev`, `esp8266_2m`, `esp32c3dev`, `esp32s3dev_8MB_opi`
|
||||
- List all PlatformIO targets: `pio run --list-targets`
|
||||
+101
-138
@@ -4,169 +4,132 @@ WLED is a fast and feature-rich implementation of an ESP32 and ESP8266 webserver
|
||||
|
||||
Always reference these instructions first and fallback to search or bash commands only when you encounter unexpected information that does not match the info here.
|
||||
|
||||
## Working Effectively
|
||||
> **Note for AI review tools**: sections enclosed in
|
||||
> `<!-- HUMAN_ONLY_START -->` / `<!-- HUMAN_ONLY_END -->` HTML comments contain
|
||||
> contributor reference material. Do **not** use that content as actionable review
|
||||
> criteria — treat it as background context only.
|
||||
|
||||
### Initial Setup
|
||||
- Install Node.js 20+ (specified in `.nvmrc`): Check your version with `node --version`
|
||||
- Install dependencies: `npm ci` (takes ~5 seconds)
|
||||
- Install PlatformIO for hardware builds: `pip install -r requirements.txt` (takes ~60 seconds)
|
||||
## Setup
|
||||
|
||||
### Build and Test Workflow
|
||||
- **ALWAYS build web UI first**: `npm run build` -- takes 3 seconds. NEVER CANCEL.
|
||||
- **Run tests**: `npm test` -- takes 40 seconds. NEVER CANCEL. Set timeout to 2+ minutes.
|
||||
- **Development mode**: `npm run dev` -- monitors file changes and auto-rebuilds web UI
|
||||
- **Hardware firmware build**: `pio run -e [environment]` -- takes 15+ minutes. NEVER CANCEL. Set timeout to 30+ minutes.
|
||||
- Node.js 20+ (see `.nvmrc`)
|
||||
- Install dependencies: `npm ci`
|
||||
- PlatformIO (required only for firmware compilation): `pip install -r requirements.txt`
|
||||
|
||||
### Build Process Details
|
||||
The build has two main phases:
|
||||
1. **Web UI Generation** (`npm run build`):
|
||||
- Processes files in `wled00/data/` (HTML, CSS, JS)
|
||||
- Minifies and compresses web content
|
||||
- Generates `wled00/html_*.h` files with embedded web content
|
||||
- **CRITICAL**: Must be done before any hardware build
|
||||
## Build and Test
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
|
||||
2. **Hardware Compilation** (`pio run`):
|
||||
- Compiles C++ firmware for various ESP32/ESP8266 targets
|
||||
- Common environments: `nodemcuv2`, `esp32dev`, `esp8266_2m`
|
||||
- List all targets: `pio run --list-targets`
|
||||
| Command | Purpose | Typical Time |
|
||||
|---|---|---|
|
||||
| `npm run build` | Build web UI → generates `wled00/html_*.h` and `wled00/js_*.h` headers | ~3 s |
|
||||
| `npm test` | Run test suite | ~40 s |
|
||||
| `npm run dev` | Watch mode — auto-rebuilds web UI on file changes | — |
|
||||
| `pio run -e <env>` | Build firmware for a hardware target | 15–20 min |
|
||||
|
||||
## Before Finishing Work
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
**CRITICAL: You MUST complete ALL of these steps before marking your work as complete:**
|
||||
- **Always run `npm run build` before any `pio run`** (and run `npm ci` first on fresh clones or when lockfile/dependencies change).
|
||||
- The web UI build generates required `wled00/html_*.h` and `wled00/js_*.h` headers for firmware compilation.
|
||||
- **Build firmware to validate code changes**: `pio run -e esp32dev` — must succeed, never skip this step.
|
||||
- Common firmware environments: `nodemcuv2`, `esp32dev`, `esp8266_2m`, `esp32c3dev`, `esp32s3dev_8MB_opi`
|
||||
|
||||
1. **Run the test suite**: `npm test` -- Set timeout to 2+ minutes. NEVER CANCEL.
|
||||
- All tests MUST pass
|
||||
- If tests fail, fix the issue before proceeding
|
||||
For detailed build timeouts, development workflows, troubleshooting, and validation steps, see [agent-build.instructions.md](agent-build.instructions.md).
|
||||
|
||||
2. **Build at least one hardware environment**: `pio run -e esp32dev` -- Set timeout to 30+ minutes. NEVER CANCEL.
|
||||
- Choose `esp32dev` as it's a common, representative environment
|
||||
- See "Hardware Compilation" section above for the full list of common environments
|
||||
- The build MUST complete successfully without errors
|
||||
- If the build fails, fix the issue before proceeding
|
||||
- **DO NOT skip this step** - it validates that firmware compiles with your changes
|
||||
### Usermod Guidelines
|
||||
|
||||
3. **For web UI changes only**: Manually test the interface
|
||||
- See "Manual Testing Scenarios" section below
|
||||
- Verify the UI loads and functions correctly
|
||||
- New custom effects can be added into the user_fx usermod. Read the [user_fx documentation](https://github.com/wled/WLED/blob/main/usermods/user_fx/README.md) for guidance.
|
||||
- Other usermods may be based on the [EXAMPLE usermod](https://github.com/wled/WLED/tree/main/usermods/EXAMPLE). Never edit the example, always create a copy!
|
||||
- New usermod IDs can be added into [wled00/const.h](https://github.com/wled/WLED/blob/main/wled00/const.h#L160).
|
||||
- To activate a usermod, a custom build configuration should be used. Add the usermod name to `custom_usermods`.
|
||||
|
||||
**If any of these validation steps fail, you MUST fix the issues before finishing. Do NOT mark work as complete with failing builds or tests.**
|
||||
## Project Structure Overview
|
||||
|
||||
## Validation and Testing
|
||||
### Project Branch / Release Structure
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
|
||||
### Web UI Testing
|
||||
- **ALWAYS validate web UI changes manually**:
|
||||
- Start local server: `cd wled00/data && python3 -m http.server 8080`
|
||||
- Open `http://localhost:8080/index.htm` in browser
|
||||
- Test basic functionality: color picker, effects, settings pages
|
||||
- **Check for JavaScript errors** in browser console
|
||||
```text
|
||||
main # Main development trunk (daily/nightly) 17.0.0-dev
|
||||
├── V5 # special branch: code rework for esp-idf 5.5.x (unstable)
|
||||
├── V5-C6 # special branch: integration of new MCU types: esp32-c5, esp32-c6, esp32-p4 (unstable)
|
||||
16_x # current beta, preparations for next release 16.0.0
|
||||
0_15_x # maintenance (bugfixes only) for current release 0.15.4
|
||||
(tag) v0.14.4 # previous version 0.14.4 (no maintenance)
|
||||
(tag) v0.13.3 # old version 0.13.3 (no maintenance)
|
||||
(tag) v0. ... . ... # historical versions 0.12.x and before
|
||||
```
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
### Code Validation
|
||||
- **No automated linting configured** - follow existing code style in files you edit
|
||||
- **Code style**: Use tabs for web files (.html/.css/.js), spaces (2 per level) for C++ files
|
||||
- **C++ formatting available**: `clang-format` is installed but not in CI
|
||||
- **Always run tests before finishing**: `npm test`
|
||||
- **MANDATORY: Always run a hardware build before finishing** (see "Before Finishing Work" section below)
|
||||
|
||||
### Manual Testing Scenarios
|
||||
After making changes to web UI, always test:
|
||||
- **Load main interface**: Verify index.htm loads without errors
|
||||
- **Navigation**: Test switching between main page and settings pages
|
||||
- **Color controls**: Verify color picker and brightness controls work
|
||||
- **Effects**: Test effect selection and parameter changes
|
||||
- **Settings**: Test form submission and validation
|
||||
|
||||
## Common Tasks
|
||||
- ``main``: development trunk (daily/nightly)
|
||||
- ``V5`` and ``V5-C6``: code rework for esp-idf 5.5.x (unstable) - branched from ``main``.
|
||||
- ``0_15_x``: bugfixing / maintenance for release 0.15.x
|
||||
|
||||
### Repository Structure
|
||||
```
|
||||
wled00/ # Main firmware source (C++)
|
||||
├── data/ # Web interface files
|
||||
│ ├── index.htm # Main UI
|
||||
|
||||
tl;dr:
|
||||
* Firmware source: `wled00/` (C++). Web UI source: `wled00/data/`. Build targets: `platformio.ini`.
|
||||
* Auto-generated headers: `wled00/html_*.h` and `wled00/js_*.h` — **never edit or commit**.
|
||||
* ArduinoJSON + AsyncJSON: `wled00/src/dependencies/json` (included via `wled.h`). CI/CD: `.github/workflows/`.
|
||||
* Usermods: `usermods/` (C++, with individual library.json).
|
||||
* Contributor docs: `docs/` (coding guidelines, etc).
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
Detailed overview:
|
||||
|
||||
```text
|
||||
wled00/ # Main firmware source (C++) "WLED core"
|
||||
├── data/ # Web interface files
|
||||
│ ├── index.htm # Main UI
|
||||
│ ├── settings*.htm # Settings pages
|
||||
│ └── *.js/*.css # Frontend resources
|
||||
├── *.cpp/*.h # Firmware source files
|
||||
└── html_*.h # Generated embedded web files (DO NOT EDIT)
|
||||
tools/ # Build tools (Node.js)
|
||||
│ └── *.js/*.css # Frontend resources
|
||||
├── *.cpp/*.h # Firmware source files
|
||||
├── html_*.h # Auto-generated embedded web files (DO NOT EDIT, DO NOT COMMIT)
|
||||
├── src/ # Modules used by the WLED core (C++)
|
||||
│ ├── fonts/ # Font libraries for scrolling text effect
|
||||
└ └── dependencies/ # Utility functions - some of them have their own licensing terms
|
||||
lib/ # Project specific custom libraries. PlatformIO will compile them to separate static libraries and link them
|
||||
platformio.ini # Hardware build configuration
|
||||
|
||||
platformio_override.sample.ini # examples for custom build configurations - entries must be copied into platformio_override.ini to use them.
|
||||
# platformio_override.ini is _not_ stored in the WLED repository!
|
||||
usermods/ # User-contributed addons to the WLED core, maintained by individual contributors (C++, with individual library.json)
|
||||
package.json # Node.js dependencies and scripts, release identification
|
||||
pio-scripts/ # Build tools (PlatformIO)
|
||||
tools/ # Build tools (Node.js), partition files, and generic utilities
|
||||
├── cdata.js # Web UI build script
|
||||
└── cdata-test.js # Test suite
|
||||
platformio.ini # Hardware build configuration
|
||||
package.json # Node.js dependencies and scripts
|
||||
docs/ # Contributor docs, coding guidelines
|
||||
.github/workflows/ # CI/CD pipelines
|
||||
```
|
||||
|
||||
### Key Files and Their Purpose
|
||||
- `wled00/data/index.htm` - Main web interface
|
||||
- `wled00/data/settings*.htm` - Configuration pages
|
||||
- `tools/cdata.js` - Converts web files to C++ headers
|
||||
- `wled00/wled.h` - Main firmware configuration
|
||||
- `platformio.ini` - Hardware build targets and settings
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
## General Guidelines
|
||||
|
||||
### Development Workflow
|
||||
1. **For web UI changes**:
|
||||
- Edit files in `wled00/data/`
|
||||
- Run `npm run build` to regenerate headers
|
||||
- Test with local HTTP server
|
||||
- Run `npm test` to validate build system
|
||||
- **Repository language is English.** Suggest translations for non-English content.
|
||||
- **Use VS Code with PlatformIO extension** for best development experience.
|
||||
- **Never edit or commit** `wled00/html_*.h` and `wled00/js_*.h` — auto-generated from `wled00/data/`.
|
||||
- If updating Web UI files in `wled00/data/`, **make use of common functions in `wled00/data/common.js` whenever possible**.
|
||||
- **When unsure, say so.** Gather more information rather than guessing.
|
||||
- **Acknowledge good patterns** when you see them. Summarize good practices as part of your review - positive feedback always helps.
|
||||
- **Provide references** when making analyses or recommendations. Base them on the correct branch or PR.
|
||||
- **Highlight user-visible breaking changes and ripple effects**. Ask for confirmation that these were introduced intentionally.
|
||||
- **Unused / dead code must be justified or removed**. This helps to keep the codebase clean, maintainable and readable.
|
||||
- **C++ formatting available**: `clang-format` is installed but not in CI
|
||||
- No automated linting is configured — match existing code style in files you edit.
|
||||
|
||||
2. **For firmware changes**:
|
||||
- Edit files in `wled00/` (but NOT `html_*.h` files)
|
||||
- Ensure web UI is built first (`npm run build`)
|
||||
- Build firmware: `pio run -e [target]`
|
||||
- Flash to device: `pio run -e [target] --target upload`
|
||||
Refer to `docs/cpp.instructions.md` and `docs/web.instructions.md` for language-specific conventions, and `docs/cicd.instructions.md` for GitHub Actions workflows.
|
||||
|
||||
3. **For both web and firmware**:
|
||||
- Always build web UI first
|
||||
- Test web interface manually
|
||||
- Build and test firmware if making firmware changes
|
||||
### Attribution for AI-generated code
|
||||
Using AI-generated code can hide the source of the inspiration / knowledge / sources it used.
|
||||
- Document attribution of inspiration / knowledge / sources used in the code, e.g. link to GitHub repositories or other websites describing the principles / algorithms used.
|
||||
- When a larger block of code is generated by an AI tool, mark it with an `// AI: below section was generated by an AI` comment (see C++ guidelines).
|
||||
- Every non-trivial AI-generated function should have a brief comment describing what it does. Explain parameters when their names alone are not self-explanatory.
|
||||
- AI-generated code must be well documented with meaningful comments that explain intent, assumptions, and non-obvious logic. Do not rephrase source code; explain concepts and reasoning.
|
||||
|
||||
## Build Timing and Timeouts
|
||||
### Pull Request Expectations
|
||||
|
||||
**IMPORTANT: Use these timeout values when running builds:**
|
||||
- **No force-push on open PRs.** Once a pull request is open and being reviewed, do not force-push (`git push --force`) to the branch. Force-pushing rewrites history that reviewers may have already commented on, making it impossible to track incremental changes. Use regular commits or `git merge` to incorporate feedback; the branch will be squash-merged when it is accepted.
|
||||
- **Document your changes in the PR.** Every pull request should include a clear description of *what* changed and *why*. If the change affects user-visible behavior, describe the expected impact. Link to related issues where applicable. Provide screenshots to showcase new features.
|
||||
|
||||
- **Web UI build** (`npm run build`): 3 seconds typical - Set timeout to 30 seconds minimum
|
||||
- **Test suite** (`npm test`): 40 seconds typical - Set timeout to 120 seconds (2 minutes) minimum
|
||||
- **Hardware builds** (`pio run -e [target]`): 15-20 minutes typical for first build - Set timeout to 1800 seconds (30 minutes) minimum
|
||||
- Subsequent builds are faster due to caching
|
||||
- First builds download toolchains and dependencies which takes significant time
|
||||
- **NEVER CANCEL long-running builds** - PlatformIO downloads and compilation require patience
|
||||
### Supporting Reviews and Discussions
|
||||
- **For "is it worth doing?" debates** about proposed reliability, safety, or data-integrity mechanisms (CRC checks, backups, power-loss protection): suggest a software **FMEA** (Failure Mode and Effects Analysis).
|
||||
Clarify the main feared events, enumerate failure modes, assess each mitigation's effectiveness per failure mode, note common-cause failures, and rate credibility for the typical WLED use case.
|
||||
|
||||
**When validating your changes before finishing, you MUST wait for the hardware build to complete successfully. Set the timeout appropriately and be patient.**
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
- **Build fails with missing html_*.h**: Run `npm run build` first
|
||||
- **Web UI looks broken**: Check browser console for JavaScript errors
|
||||
- **PlatformIO network errors**: Try again, downloads can be flaky
|
||||
- **Node.js version issues**: Ensure Node.js 20+ is installed (check `.nvmrc`)
|
||||
|
||||
### When Things Go Wrong
|
||||
- **Clear generated files**: `rm -f wled00/html_*.h` then rebuild
|
||||
- **Force web UI rebuild**: `npm run build -- --force` or `npm run build -- -f`
|
||||
- **Clean PlatformIO cache**: `pio run --target clean`
|
||||
- **Reinstall dependencies**: `rm -rf node_modules && npm install`
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **DO NOT edit `wled00/html_*.h` files** - they are auto-generated
|
||||
- **Always commit both source files AND generated html_*.h files**
|
||||
- **Web UI must be built before firmware compilation**
|
||||
- **Test web interface manually after any web UI changes**
|
||||
- **Use VS Code with PlatformIO extension for best development experience**
|
||||
- **Hardware builds require appropriate ESP32/ESP8266 development board**
|
||||
|
||||
## CI/CD Pipeline
|
||||
|
||||
**The GitHub Actions CI workflow will:**
|
||||
1. Installs Node.js and Python dependencies
|
||||
2. Runs `npm test` to validate build system (MUST pass)
|
||||
3. Builds web UI with `npm run build` (automatically run by PlatformIO)
|
||||
4. Compiles firmware for ALL hardware targets listed in `default_envs` (MUST succeed for all)
|
||||
5. Uploads build artifacts
|
||||
|
||||
**To ensure CI success, you MUST locally:**
|
||||
- Run `npm test` and ensure it passes
|
||||
- Run `pio run -e esp32dev` (or another common environment from "Hardware Compilation" section) and ensure it completes successfully
|
||||
- If either fails locally, it WILL fail in CI
|
||||
|
||||
**Match this workflow in your local development to ensure CI success. Do not mark work complete until you have validated builds locally.**
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
sinceTag: v0.15.0
|
||||
output: CHANGELOG_NIGHTLY.md
|
||||
# Exclude issues that were closed without resolution from changelog
|
||||
excludeLabels: 'stale,wontfix,duplicate,invalid,question,use-as-is,not_planned'
|
||||
excludeLabels: 'stale,wontfix,duplicate,invalid,external,question,use-as-is,not_planned'
|
||||
- name: Update Nightly Release
|
||||
uses: andelf/nightly-release@main
|
||||
env:
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
sinceTag: v0.15.0
|
||||
maxIssues: 500
|
||||
# Exclude issues that were closed without resolution from changelog
|
||||
excludeLabels: 'stale,wontfix,duplicate,invalid,question,use-as-is,not_planned'
|
||||
excludeLabels: 'stale,wontfix,duplicate,invalid,external,question,use-as-is,not_planned'
|
||||
- name: Create draft release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
|
||||
@@ -10,6 +10,10 @@
|
||||
compile_commands.json
|
||||
__pycache__/
|
||||
|
||||
/.dummy
|
||||
/dependencies.lock
|
||||
/managed_components
|
||||
|
||||
esp01-update.sh
|
||||
platformio_override.ini
|
||||
replace_fs.py
|
||||
@@ -25,3 +29,4 @@ wled-update.sh
|
||||
/wled00/Release
|
||||
/wled00/wled00.ino.cpp
|
||||
/wled00/html_*.h
|
||||
/wled00/js_*.h
|
||||
|
||||
+160
-43
@@ -1,74 +1,189 @@
|
||||
## Thank you for making WLED better!
|
||||
# Thank you for making WLED better!
|
||||
|
||||
Here are a few suggestions to make it easier for you to contribute!
|
||||
WLED is a community-driven project, and every contribution matters! We appreciate your time and effort.
|
||||
|
||||
Our maintainers are here for two things: **helping you** improve your code, and **keeping WLED** lean, efficient, and maintainable.
|
||||
We'll work with you to refine your contribution, but we'll also push back if something might create technical debt or add features without clear value. Don't take it personally - we're just protecting WLED's architecture while helping your contribution succeed!
|
||||
|
||||
## Getting Started
|
||||
|
||||
Here are a few suggestions to make it easier for you to contribute:
|
||||
|
||||
### Important Developer Infos
|
||||
* [Project Structure, Files and Directories](.github/copilot-instructions.md#project-structure-overview) (in our AI instructions)
|
||||
* [Instructions for creating usermods](.github/copilot-instructions.md#usermod-guidelines) (in our AI instructions)
|
||||
* KB: [Compiling WLED](https://kno.wled.ge/advanced/compiling-wled/) - slightly outdated but still helpful :-)
|
||||
* Arduino IDE is not supported any more. Use VSCode with the PlatformIO extension.
|
||||
* [Compiling in VSCode/Platformio](https://github.com/wled/WLED-Docs/issues/161) - modern way without command line or platformio.ini changes.
|
||||
* If you add a new feature, consider making a PR to [``wled-docs``](https://github.com/wled/WLED-Docs) for updating our official documentation.
|
||||
|
||||
### PR from a branch in your own fork
|
||||
Start your pull request (PR) in a branch of your own fork. Don't make a PR directly from your main branch.
|
||||
This lets you update your PR if needed, while you can work on other tasks in 'main' or in other branches.
|
||||
|
||||
<img width="295" height="134" alt="image: fork and edit" src="https://github.com/user-attachments/assets/f0dc7567-edcb-4409-a530-cd621ae9661f" />
|
||||
|
||||
Tip: When viewing a file in `wled/WLED`, click on the "pen" icon and start making changes.
|
||||
When you chose to 'Commit changes', GitHub will automatically create a PR from your fork.
|
||||
> [!TIP]
|
||||
> **The easiest way to start your first PR**
|
||||
> When viewing a file in `wled/WLED`, click on the "pen" icon and start making changes.
|
||||
> When you choose to 'Commit changes', GitHub will automatically create a PR from your fork.
|
||||
>
|
||||
> <img width="295" height="134" alt="image: fork and edit" src="https://github.com/user-attachments/assets/f0dc7567-edcb-4409-a530-cd621ae9661f" />
|
||||
|
||||
### Target branch for pull requests
|
||||
|
||||
Please make all PRs against the `main` branch.
|
||||
|
||||
### Describe your PR
|
||||
### Describing your PR
|
||||
|
||||
Please add a description of your proposed code changes. It does not need to be an exhaustive essay, however a PR with no description or just a few words might not get accepted, simply because very basic information is missing.
|
||||
Please add a description of your proposed code changes.
|
||||
A PR with no description or just a few words might not get accepted, simply because very basic information is missing.
|
||||
No need to write an essay!
|
||||
|
||||
A good description helps us to review and understand your proposed changes. For example, you could say a few words about
|
||||
* what you try to achieve (new feature, fixing a bug, refactoring, security enhancements, etc.)
|
||||
* how your code works (short technical summary - focus on important aspects that might not be obvious when reading the code)
|
||||
* testing you performed, known limitations, open ends you possibly could not solve.
|
||||
* any areas where you like to get help from an experienced maintainer (yes WLED has become big 😉)
|
||||
* What you try to achieve (new feature, fixing a bug, refactoring, security enhancements, etc.)
|
||||
* How your code works (short technical summary - focus on important aspects that might not be obvious when reading the code)
|
||||
* Testing you performed, known limitations, anything you couldn't quite solve.
|
||||
* Let us know if you'd like guidance from a maintainer (WLED is a big project 😉)
|
||||
|
||||
### Testing Your Changes
|
||||
|
||||
Before submitting:
|
||||
|
||||
- ✅ Does it compile?
|
||||
- ✅ Does your feature/fix actually work?
|
||||
- ✅ Did you break anything else?
|
||||
- ✅ Tested on actual hardware if possible?
|
||||
|
||||
Mention your testing in the PR description (e.g., "Tested on ESP32 + WS2812B").
|
||||
|
||||
## During Review
|
||||
|
||||
We're all volunteers, so reviews can take some time (longer during busy times).
|
||||
Don't worry - we haven't forgotten you! Feel free to ping after a week if there's no activity.
|
||||
|
||||
### Updating your code
|
||||
While the PR is open - and under review by maintainers - you may be asked to modify your PR source code.
|
||||
You can simply update your own branch, and push changes in response to reviewer recommendations.
|
||||
Github will pick up the changes so your PR stays up-to-date.
|
||||
While the PR is open, you can keep updating your branch - just push more commits! GitHub will automatically update your PR.
|
||||
|
||||
You don't need to provide us with a single-commit 'squashed' PR; you can simply add commits while your pull request (PR) is open.
|
||||
You don't need to squash commits or clean up history - we'll handle that when merging.
|
||||
|
||||
> [!CAUTION]
|
||||
> [!CAUTION]
|
||||
> Do not use "force-push" while your PR is open!
|
||||
> It has many subtle and unexpected consequences on our github reposistory.
|
||||
> For example, we regularly lost review comments when the PR author force-pushes code changes. So, pretty please, do not force-push.
|
||||
> It has many subtle and unexpected consequences on our GitHub repository.
|
||||
> For example, we regularly lose review comments when the PR author force-pushes code changes. Our review bot (coderabbit) may become unable to properly track changes, it gets confused or stops responding to questions.
|
||||
> So, pretty please, do not force-push.
|
||||
|
||||
> [!TIP]
|
||||
> use [cherry-picking](https://docs.github.com/en/desktop/managing-commits/cherry-picking-a-commit-in-github-desktop) to copy commits from one branch to another.
|
||||
> Use [cherry-picking](https://docs.github.com/en/desktop/managing-commits/cherry-picking-a-commit-in-github-desktop) to copy commits from one branch to another.
|
||||
|
||||
You can find a collection of very useful tips and tricks here: https://github.com/wled-dev/WLED/wiki/How-to-properly-submit-a-PR
|
||||
|
||||
### Responding to Reviews
|
||||
|
||||
When we ask for changes:
|
||||
|
||||
- **Add new commits** - please don't amend or force-push
|
||||
- **Reply in the PR** - let us know when you've addressed comments
|
||||
- **Ask questions** - if something's unclear, just ask!
|
||||
- **Be patient** - we're all volunteers here 😊
|
||||
|
||||
You can reference feedback in commit messages:
|
||||
> ```text
|
||||
> Fix naming per @Aircoookie's suggestion
|
||||
> ```
|
||||
|
||||
### Dealing with Merge Conflicts
|
||||
|
||||
Got conflicts with `main`? No worries - here's how to fix them:
|
||||
|
||||
**Using GitHub Desktop** (easier for beginners):
|
||||
|
||||
1. Click **Fetch origin**, then **Pull origin**
|
||||
2. If conflicts exist, GitHub Desktop will warn you - click **View conflicts**
|
||||
3. Open the conflicted files in your editor (VS Code, etc.)
|
||||
4. Remove the conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) and keep the correct code
|
||||
5. Save the files
|
||||
6. Back in GitHub Desktop, commit the merge (it'll suggest a message)
|
||||
7. Click **Push origin**
|
||||
|
||||
**Using command line**:
|
||||
|
||||
```bash
|
||||
git fetch origin
|
||||
git merge origin/main
|
||||
# Fix conflicts in your editor
|
||||
git add .
|
||||
git commit
|
||||
git push
|
||||
```
|
||||
|
||||
Either way works fine - pick what you're comfortable with! Merging is simpler than rebasing and keeps everything connected.
|
||||
|
||||
#### When you MUST rebase (really rare!)
|
||||
|
||||
Sometimes you might hit merge conflicts with `main` that are harder to solve. Here's what to try:
|
||||
|
||||
1. **Merge instead of rebase** (safest option):
|
||||
```bash
|
||||
git fetch origin
|
||||
git merge origin/main
|
||||
git push
|
||||
```
|
||||
Keeps review comments attached and CI results visible!
|
||||
|
||||
2. **Use cherry-picking** to copy commits between branches without rewriting history - [here's how](https://docs.github.com/en/desktop/managing-commits/cherry-picking-a-commit-in-github-desktop).
|
||||
|
||||
3. **If all else fails, use `--force-with-lease`** (not plain `--force`):
|
||||
```bash
|
||||
git rebase origin/main
|
||||
git push --force-with-lease
|
||||
```
|
||||
Then **leave a comment** explaining why you had to force-push, and be ready to re-address some feedback.
|
||||
|
||||
### Additional Resources
|
||||
Want to know more? Check out:
|
||||
- 📚 [GitHub Desktop documentation](https://docs.github.com/en/desktop) - if you prefer GUI tools
|
||||
- 🎓 [How to properly submit a PR](https://github.com/wled-dev/WLED/wiki/How-to-properly-submit-a-PR) - detailed tips and tricks
|
||||
|
||||
|
||||
## After Approval
|
||||
Once approved, a maintainer will merge your PR (possibly squashing commits).
|
||||
Your contribution will be in the next WLED release - thank you! 🎉
|
||||
|
||||
|
||||
## Coding Guidelines
|
||||
|
||||
### Source Code from an AI agent or bot
|
||||
> [!IMPORTANT]
|
||||
> Its OK if you took help from an AI for writing your source code.
|
||||
> It's OK if you took help from an AI for writing your source code.
|
||||
>
|
||||
> However, we expect a few things from you as the person making a contribution to WLED:
|
||||
* Make sure you really understand the code suggested by the AI, and don't just accept it because it "seems to work".
|
||||
> AI tools can be very helpful, but as the contributor, **you're responsible for the code**.
|
||||
|
||||
* Make sure you really understand the AI-generated code, don't just accept it because it "seems to work".
|
||||
* Don't let the AI change existing code without double-checking by you as the contributor. Often, the result will not be complete. For example, previous source code comments may be lost.
|
||||
* Remember that AI are still "Often-Wrong" ;-)
|
||||
* If you don't feel very confident using English, you can use AI for translating code comments and descriptions into English. AI bots are very good at understanding language. However, always check if the results is correct. The translation might still have wrong technical terms, or errors in some details.
|
||||
* Remember that AI is still "Often-Wrong" ;-)
|
||||
* If you don't feel confident using English, you can use AI for translating code comments and descriptions into English. AI bots are very good at understanding language. However, always check if the results are correct. The translation might still have wrong technical terms, or errors in some details.
|
||||
|
||||
#### best practice with AI:
|
||||
* As the person who contributes source code to WLED, make sure you understand exactly what the AI generated code does
|
||||
* best practice: add a comment like ``'// below section of my code was generated by an AI``, when larger parts of your source code were not written by you personally.
|
||||
* always review translations and code comments for correctness
|
||||
* always review AI generated source code
|
||||
* If the AI has rewritten existing code, check that the change is necessary and that nothing has been lost or broken. Also check that previous code comments are still intact.
|
||||
#### Best Practice with AI
|
||||
|
||||
AI tools are powerful but "often wrong" - your judgment is essential! 😊
|
||||
|
||||
- ✅ **Understand the code** - As the person contributing to WLED, make sure you understand exactly what the AI-generated source code does
|
||||
- ✅ **Review carefully** - AI can lose comments, introduce bugs, or make unnecessary changes
|
||||
- ✅ **Be transparent** - Add a comment like `// This section was AI-generated` for larger chunks
|
||||
- ✅ **Use AI for translation** - AI is great for translating comments to English (but verify technical terms!)
|
||||
|
||||
### Code style
|
||||
|
||||
When in doubt, it is easiest to replicate the code style you find in the files you want to edit :)
|
||||
Below are the guidelines we use in the WLED repository.
|
||||
Don't stress too much about style! When in doubt, just match the style in the files you're editing. 😊
|
||||
|
||||
Our review bot (coderabbit) has learned lots of detailed guides and hints - it will suggest them automatically when you submit a PR for review.
|
||||
If you are curious, these are the detailed guides:
|
||||
* [C++ Coding](docs/cpp.instructions.md)
|
||||
* [WebUi: HTML, JS, CSS](docs/web.instructions.md)
|
||||
|
||||
Below are the main rules used in the WLED repository:
|
||||
|
||||
#### Indentation
|
||||
|
||||
We use tabs for Indentation in Web files (.html/.css/.js) and spaces (2 per indentation level) for all other files.
|
||||
We use tabs for indentation in Web files (.html/.css/.js) and spaces (2 per indentation level) for all other files.
|
||||
You are all set if you have enabled `Editor: Detect Indentation` in VS Code.
|
||||
|
||||
#### Blocks
|
||||
@@ -86,7 +201,7 @@ if (a == b) {
|
||||
if (a == b) doStuff(a);
|
||||
```
|
||||
|
||||
Acceptable - however the first variant is usually easier to read:
|
||||
Also acceptable (though the first style is usually easier to read):
|
||||
```cpp
|
||||
if (a == b)
|
||||
{
|
||||
@@ -117,20 +232,22 @@ if( a==b ){
|
||||
#### Comments
|
||||
|
||||
Comments should have a space between the delimiting characters (e.g. `//`) and the comment text.
|
||||
Note: This is a recent change, the majority of the codebase still has comments without spaces.
|
||||
We're gradually adopting this style - don't worry if you see older code without spaces!
|
||||
|
||||
Good:
|
||||
```
|
||||
// This is a comment.
|
||||
|
||||
/* This is a CSS inline comment */
|
||||
```cpp
|
||||
// This is a short inline comment.
|
||||
|
||||
/*
|
||||
* This is a comment
|
||||
* This is a longer comment
|
||||
* wrapping over multiple lines,
|
||||
* used in WLED for file headers and function explanations
|
||||
*/
|
||||
|
||||
```
|
||||
```css
|
||||
/* This is a CSS inline comment */
|
||||
```
|
||||
```html
|
||||
<!-- This is an HTML comment -->
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
---
|
||||
applyTo: ".github/workflows/*.yml,.github/workflows/*.yaml"
|
||||
---
|
||||
# CI/CD Conventions — GitHub Actions Workflows
|
||||
|
||||
> **Note for AI review tools**: sections enclosed in
|
||||
> `<!-- HUMAN_ONLY_START -->` / `<!-- HUMAN_ONLY_END -->` HTML comments contain
|
||||
> contributor reference material. Do **not** use that content as actionable review
|
||||
> criteria — treat it as background context only.
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
## YAML Style
|
||||
|
||||
- Indent with **2 spaces** (no tabs)
|
||||
- Every workflow, job, and step must have a `name:` field that clearly describes its purpose
|
||||
- Group related steps logically; separate unrelated groups with a blank line
|
||||
- Comments (`#`) are encouraged for non-obvious decisions (e.g., why `fail-fast: false` is set, what a cron expression means)
|
||||
|
||||
## Workflow Structure
|
||||
|
||||
### Triggers
|
||||
|
||||
- Declare `on:` triggers explicitly; avoid bare `on: push` without branch filters on long-running or expensive jobs
|
||||
- Prefer `workflow_call` for shared build logic (see `build.yml`) to avoid duplicating steps across workflows
|
||||
- Document scheduled triggers (`cron:`) with a human-readable comment:
|
||||
|
||||
```yaml
|
||||
schedule:
|
||||
- cron: '0 2 * * *' # run at 2 AM UTC daily
|
||||
```
|
||||
|
||||
### Jobs
|
||||
|
||||
- Express all inter-job dependencies with `needs:` — never rely on implicit ordering
|
||||
- Use job `outputs:` + step `id:` to pass structured data between jobs (see `get_default_envs` in `build.yml`)
|
||||
- Set `fail-fast: false` on matrix builds so that a single failing environment does not cancel others
|
||||
|
||||
### Runners
|
||||
|
||||
- Pin to a specific Ubuntu version (`ubuntu-22.04`, `ubuntu-24.04`) rather than `ubuntu-latest` for reproducible builds
|
||||
- Only use `ubuntu-latest` in jobs where exact environment reproducibility is not required (e.g., trivial download/publish steps)
|
||||
|
||||
### Tool and Language Versions
|
||||
|
||||
- Pin tool versions explicitly:
|
||||
```yaml
|
||||
python-version: '3.12'
|
||||
```
|
||||
- Do not rely on the runner's pre-installed tool versions — always install via a versioned setup action
|
||||
|
||||
### Caching
|
||||
|
||||
- Always cache package managers and build tool directories when the job installs dependencies:
|
||||
```yaml
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pip-
|
||||
```
|
||||
- Include the environment name or a relevant identifier in cache keys when building multiple targets
|
||||
|
||||
### Artifacts
|
||||
|
||||
- Name artifacts with enough context to be unambiguous (e.g., `firmware-${{ matrix.environment }}`)
|
||||
- Avoid uploading artifacts that will never be consumed downstream
|
||||
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
---
|
||||
|
||||
## Security
|
||||
|
||||
Important: Several current workflows still violate parts of the baseline below - migration is in progress.
|
||||
|
||||
### Permissions — Least Privilege
|
||||
|
||||
Declare explicit `permissions:` blocks. The default token permissions are broad; scope them to the minimum required:
|
||||
|
||||
```yaml
|
||||
permissions:
|
||||
contents: read # for checkout
|
||||
```
|
||||
|
||||
For jobs that publish releases or write to the repository:
|
||||
|
||||
```yaml
|
||||
permissions:
|
||||
contents: write # create/update releases
|
||||
```
|
||||
|
||||
A common safe baseline for build-only jobs:
|
||||
|
||||
```yaml
|
||||
permissions:
|
||||
contents: read
|
||||
```
|
||||
|
||||
### Supply Chain — Action Pinning
|
||||
|
||||
**Third-party actions** (anything outside the `actions/` and `github/` namespaces) should be pinned to a specific release tag. Branch pins (`@main`, `@master`) are **not allowed** — they can be updated by the action author at any time without notice:
|
||||
|
||||
```yaml
|
||||
# ✅ Acceptable — specific version tag. SHA pinning recommended for more security, as @v2 is still a mutable tag.
|
||||
uses: softprops/action-gh-release@v2
|
||||
|
||||
# ❌ Not acceptable — mutable branch reference
|
||||
uses: andelf/nightly-release@main
|
||||
```
|
||||
|
||||
SHA pinning (e.g., `uses: someorg/some-action@abc1234`) is the most secure option for third-party actions; it is recommended when auditing supply-chain risk is a priority. At minimum, always use a specific version tag.
|
||||
|
||||
**First-party actions** (`actions/checkout`, `actions/cache`, `actions/upload-artifact`, etc.) pinned to a major version tag (e.g., `@v4`) are acceptable because GitHub maintains and audits these.
|
||||
|
||||
When adding a new third-party action:
|
||||
1. Check that the action's repository is actively maintained
|
||||
2. Review the action's source before adding it
|
||||
3. Prefer well-known, widely-used actions over obscure ones
|
||||
|
||||
### Credentials and Secrets
|
||||
|
||||
- Use `${{ secrets.GITHUB_TOKEN }}` for operations within the same repository — it is automatically scoped and rotated
|
||||
- Never commit secrets, tokens, or passwords into workflow files or any tracked file
|
||||
- Never print secrets in `run:` steps, even with `echo` — GitHub masks known secrets but derived values are not automatically masked
|
||||
- Scope secrets to the narrowest step that needs them using `env:` at the step level, not at the workflow level:
|
||||
|
||||
```yaml
|
||||
# ✅ Scoped to the step that needs it
|
||||
- name: Create release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# ❌ Unnecessarily broad
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
```
|
||||
|
||||
- Personal Access Tokens (PATs, stored as repository secrets) should have the minimum required scopes and should be rotated periodically
|
||||
|
||||
### Script Injection
|
||||
|
||||
`${{ }}` expressions are evaluated before the shell script runs. If an expression comes from untrusted input (PR titles, issue bodies, branch names from forks), it can inject arbitrary shell commands.
|
||||
|
||||
**Never** interpolate `github.event.*` values directly into a `run:` step:
|
||||
|
||||
```yaml
|
||||
# ❌ Injection risk — PR title is attacker-controlled
|
||||
- run: echo "${{ github.event.pull_request.title }}"
|
||||
|
||||
# ✅ Safe — value passed through an environment variable
|
||||
- env:
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
run: echo "$PR_TITLE"
|
||||
```
|
||||
|
||||
This rule applies to any value that originates outside the repository (issue bodies, labels, comments, commit messages from forks).
|
||||
|
||||
### Pull Request Workflows
|
||||
|
||||
- Workflows triggered by `pull_request` from a fork run with **read-only** token permissions and no access to repository secrets — this is intentional and correct
|
||||
- Do not use `pull_request_target` unless you fully understand the security implications; it runs in the context of the base branch and *does* have secret access, making it a common attack surface
|
||||
@@ -0,0 +1,524 @@
|
||||
---
|
||||
applyTo: "**/*.cpp,**/*.h,**/*.hpp,**/*.ino"
|
||||
---
|
||||
# C++ Coding Conventions
|
||||
|
||||
> **Note for AI review tools**: sections enclosed in
|
||||
> `<!-- HUMAN_ONLY_START -->` / `<!-- HUMAN_ONLY_END -->` HTML comments contain
|
||||
> contributor reference material. Do **not** use that content as actionable review
|
||||
> criteria — treat it as background context only.
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
<!-- hiding this reference, to avoid cyclic "include" loops -->
|
||||
See also: [CONTRIBUTING.md](../CONTRIBUTING.md) for general style guidelines that apply to all contributors.
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
## Formatting
|
||||
|
||||
- Indent with **2 spaces** (no tabs in C++ files)
|
||||
- Opening braces on the same line is preferred (K&R style). Brace on a separate line (Allman style) is acceptable
|
||||
- Single-statement `if` bodies may omit braces: `if (a == b) doStuff(a);`
|
||||
- Space between keyword and parenthesis: `if (...)`, `for (...)`. No space between function name and parenthesis: `doStuff(a)`
|
||||
- No enforced line-length limit; wrap when a line exceeds your editor width
|
||||
|
||||
## Naming
|
||||
|
||||
- **camelCase** for functions and variables: `setValuesFromMainSeg()`, `effectCurrent`
|
||||
- **PascalCase** for classes and structs: `PinManagerClass`, `BusConfig`
|
||||
- **UPPER_CASE** for macros and constants: `WLED_MAX_USERMODS`, `DEFAULT_CLIENT_SSID`
|
||||
|
||||
## General
|
||||
|
||||
- Follow the existing style in the file you are editing
|
||||
- If possible, use `static` for local (C-style) variables and functions (keeps the global namespace clean)
|
||||
- Avoid unexplained "magic numbers". Prefer named constants (`constexpr`) or C-style `#define` constants for repeated numbers that have the same meaning
|
||||
- Include `"wled.h"` as the primary project header where needed
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
## Header Guards
|
||||
|
||||
Most headers use `#ifndef` / `#define` guards. Some newer headers add `#pragma once` before the guard:
|
||||
|
||||
```cpp
|
||||
#ifndef WLED_EXAMPLE_H
|
||||
#define WLED_EXAMPLE_H
|
||||
// ...
|
||||
#endif // WLED_EXAMPLE_H
|
||||
```
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
## Comments
|
||||
|
||||
- `//` for inline comments, `/* ... */` for block comments. Always put a space after `//`
|
||||
- **AI attribution:** When a larger block of code is generated by an AI tool, mark it with an `// AI:` comment so reviewers know to scrutinize it:
|
||||
|
||||
```cpp
|
||||
// AI: below section was generated by an AI
|
||||
void calculateCRC(const uint8_t* data, size_t len) {
|
||||
...
|
||||
}
|
||||
// AI: end of AI-generated section
|
||||
```
|
||||
|
||||
Single-line AI-assisted edits do not need the marker — use it when the AI produced a contiguous block that a human did not write line-by-line.
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
<!-- hidden from AI for now, as it created too many "please add a description" review findings in my first tests -->
|
||||
- **Function & feature comments:** Every non-trivial function should have a brief comment above it describing what it does. Include a note about each parameter when the names alone are not self-explanatory:
|
||||
|
||||
```cpp
|
||||
/* *****
|
||||
* Apply gamma correction to a single color channel.
|
||||
* @param value raw 8-bit channel value (0–255)
|
||||
* @param gamma gamma exponent (typically 2.8)
|
||||
* @return corrected 8-bit value
|
||||
***** */
|
||||
uint8_t gammaCorrect(uint8_t value, float gamma);
|
||||
```
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
Short accessor-style functions (getters/setters, one-liners) may skip this if their purpose is obvious from the name.
|
||||
|
||||
## Preprocessor & Feature Flags
|
||||
|
||||
- Prefer compile-time feature flags (`#ifdef` / `#ifndef`) over runtime checks where possible
|
||||
- Platform differentiation: `ARDUINO_ARCH_ESP32` vs `ESP8266`
|
||||
- PSRAM availability: `BOARD_HAS_PSRAM`
|
||||
|
||||
## Error Handling
|
||||
|
||||
- `DEBUG_PRINTF()` / `DEBUG_PRINTLN()` for developer diagnostics (compiled out unless `-D WLED_DEBUG`)
|
||||
- Don't rely on C++ exceptions — use return codes (`-1` / `false` for errors) and global flags (e.g. `errorFlag = ERR_LOW_MEM`). Some builds don't support C++ exceptions.
|
||||
|
||||
## Strings
|
||||
|
||||
- Use `const char*` for temporary/parsed strings
|
||||
- Avoid `String` (Arduino heap-allocated string) in hot paths; acceptable in config/setup code
|
||||
- Use `F("string")` for string constants (major RAM win on ESP8266; mostly overload/type compatibility on ESP32)
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
|
||||
On **ESP8266** this explicitly stores the string in flash (PROGMEM), saving precious RAM — every byte counts on that platform.
|
||||
On **ESP32**, `PROGMEM` is a no-op and string literals already reside in flash/rodata, so `F()` yields little RAM benefit but remains harmless (it satisfies `__FlashStringHelper*` overloads that some APIs expect).
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
```cpp
|
||||
DEBUG_PRINTLN(F("WS client connected.")); // string stays in flash, not RAM
|
||||
DEBUG_PRINTF_P(PSTR("initE: Ignoring attempt for invalid ethernetType (%d)\n"), ethernetType); // format string stays in flash
|
||||
```
|
||||
|
||||
## Memory
|
||||
|
||||
- **PSRAM-aware allocation**: use `d_malloc()` (prefer DRAM), `p_malloc()` (prefer PSRAM) from `fcn_declare.h`
|
||||
- **Avoid Variable Length Arrays (VLAs)**: FreeRTOS task stacks are typically 2–8 KB. A runtime-sized VLA can silently exhaust the stack. Use fixed-size arrays or heap allocation (`d_malloc` / `p_malloc`). Any VLA must be explicitly justified in source or PR.
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
GCC/Clang support VLAs as an extension (they are not part of the C++ standard), so they look like a legitimate feature — but they are allocated on the stack at runtime. On ESP32/ESP8266, a VLA whose size depends on a runtime parameter (segment dimensions, pixel counts, etc.) can silently exhaust the stack and cause the program to behave in unexpected ways or crash.
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
- **Larger buffers** (LED data, JSON documents) should use PSRAM when available and technically feasible
|
||||
- **Hot-path**: some data should stay in DRAM or IRAM for performance reasons
|
||||
- Memory efficiency matters, but is less critical on boards with PSRAM
|
||||
|
||||
Heap fragmentation is a concern:
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
- Fragmentation can lead to crashes, even when the overall amount of available heap is still good. The C++ runtime doesn't do any "garbage collection".
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
- Avoid frequent `d_malloc` and `d_free` inside a function, especially for small sizes.
|
||||
- Avoid frequent creation / destruction of objects.
|
||||
- Allocate buffers early, and try to re-use them.
|
||||
- Instead of incrementally appending to a `String`, reserve the expected max buffer upfront by using the `reserve()` method.
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
|
||||
```cpp
|
||||
String result;
|
||||
result.reserve(65); // pre-allocate to avoid realloc fragmentation
|
||||
```
|
||||
|
||||
```cpp
|
||||
// prefer DRAM; falls back gracefully and enforces MIN_HEAP_SIZE guard
|
||||
_ledsDirty = (byte*) d_malloc(getBitArrayBytes(_len));
|
||||
```
|
||||
|
||||
```cpp
|
||||
_mode.reserve(_modeCount); // allocate memory to prevent initial fragmentation - does not increase size()
|
||||
_modeData.reserve(_modeCount); // allocate memory to prevent initial fragmentation - does not increase size()
|
||||
```
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
## `const` and `constexpr`
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
`const` is a promise to the compiler that a value (or object) will not change - a function declared with a `const char* message` parameter is not allowed to modify the content of `message`.
|
||||
This pattern enables optimizations and makes intent clear to reviewers.
|
||||
|
||||
`constexpr` allows to define constants that are *guaranteed* to be evaluated by the compiler (zero run-time costs).
|
||||
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
- For function parameters that are read-only, prefer `const &` or `const`.
|
||||
|
||||
### `const` locals
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
* Adding `const` to a local variable that is only assigned once is optional, but *not* strictly necessary.
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
* In hot-path code, `const` on cached locals may help the compiler keep values in registers.
|
||||
```cpp
|
||||
const uint_fast16_t cols = vWidth();
|
||||
const uint_fast16_t rows = vHeight();
|
||||
```
|
||||
|
||||
### `const` references to avoid copies
|
||||
- Pass objects by `const &` (or `&`) instead of copying them implicitly.
|
||||
- Use `const &` (or `&`) inside loops - This avoids constructing temporary objects on every access.
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
```cpp
|
||||
const auto &m = _mappings[i]; // reference, not a copy (bus_manager.cpp)
|
||||
Segment& sourcesegment = strip.getSegment(sourceid); // alias — avoids creating a temporary Segment instance
|
||||
```
|
||||
|
||||
For function parameters that are read-only, prefer `const &`:
|
||||
```cpp
|
||||
BusManager::add(const BusConfig &bc, bool placeholder) {
|
||||
```
|
||||
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
- Class **Data Members:** Avoid reference data members (`T&` or `const T&`) in a class.
|
||||
A reference member can outlive the object it refers to, causing **dangling reference** bugs that are hard to diagnose. Prefer value storage or use a pointer and document the expected lifetime.
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
<!-- hidden from AI for now - codebase is not compliant to this rule (slowly migrating) -->
|
||||
### `constexpr` over `#define`
|
||||
|
||||
- Prefer `constexpr` for compile-time constants. Unlike `#define`, `constexpr` respects scope and type safety, keeping the global namespace clean.
|
||||
|
||||
```cpp
|
||||
// Prefer:
|
||||
constexpr uint32_t TWO_CHANNEL_MASK = 0x00FF00FF;
|
||||
constexpr int WLED_MAX_BUSSES = WLED_MAX_DIGITAL_CHANNELS + WLED_MAX_ANALOG_CHANNELS;
|
||||
|
||||
// Avoid (when possible):
|
||||
#define TWO_CHANNEL_MASK 0x00FF00FF
|
||||
```
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
### `static_assert` over `#error`
|
||||
|
||||
- Use `static_assert` instead of the C-style `#if … #error … #endif` pattern when validating compile-time constants. It provides a clear message and works with `constexpr` values.
|
||||
- `#define` and `#if ... #else ... #endif` is still needed for conditional-compilation guards and build-flag-overridable values.
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
```cpp
|
||||
// Prefer:
|
||||
constexpr int WLED_MAX_BUSSES = WLED_MAX_DIGITAL_CHANNELS + WLED_MAX_ANALOG_CHANNELS;
|
||||
static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
|
||||
// Avoid:
|
||||
#if (WLED_MAX_BUSSES > 32)
|
||||
#error "WLED_MAX_BUSSES exceeds hard limit"
|
||||
#endif
|
||||
```
|
||||
|
||||
```cpp
|
||||
// using static_assert() to validate enumerated types (zero cost at runtime)
|
||||
static_assert(0u == static_cast<uint8_t>(PinOwner::None),
|
||||
"PinOwner::None must be zero, so default array initialization works as expected");
|
||||
```
|
||||
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
### `static` and `const` class methods
|
||||
|
||||
#### `const` member functions
|
||||
|
||||
Marking a member function `const` tells the compiler that it does not modify the object's state:
|
||||
|
||||
```cpp
|
||||
uint16_t length() const { return _len; }
|
||||
bool isActive() const { return _active; }
|
||||
```
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
Benefits for GCC/Xtensa/RISC-V:
|
||||
- The compiler knows the method cannot write to `this`, so it is free to **keep member values in registers** across the call and avoid reload barriers.
|
||||
- `const` methods can be called on `const` objects and `const` references — essential when passing large objects as `const &` to avoid copying.
|
||||
- `const` allows the compiler to **eliminate redundant loads**: if a caller already has a member value cached, the compiler can prove the `const` call cannot invalidate it.
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
Declare getter, query, or inspection methods `const`. If you need to mark a member `mutable` to work around this (e.g. for a cache or counter), document the reason.
|
||||
|
||||
#### `static` member functions
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
A `static` member function has no implicit `this` pointer. This has two distinct advantages:
|
||||
|
||||
1. **Smaller code, faster calls**: no `this` is passed in a register. On Xtensa and RISC-V, this removes one register argument from every call site and prevents the compiler from emitting `this`-preservation code around inlined blocks.
|
||||
2. **Better inlining**: GCC can inline a `static` method with more certainty because it cannot be overridden by a derived class (no virtual dispatch ambiguity) and has no aliasing concern through `this`.
|
||||
|
||||
Use `static` for any method that does not need access to instance members:
|
||||
|
||||
```cpp
|
||||
// Factory / utility — no instance needed:
|
||||
static BusConfig fromJson(JsonObject obj);
|
||||
|
||||
// Pure computation helpers:
|
||||
static uint8_t gamma8(uint8_t val);
|
||||
static uint32_t colorBalance(uint32_t color, uint8_t r, uint8_t g, uint8_t b);
|
||||
```
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
`static` communicates intent clearly: a reviewer immediately knows the method is stateless and safe to call without a fully constructed object.
|
||||
|
||||
> **Rule of thumb**: if a method does not read or write any member variable, make it `static`. If it only reads member variables, make it `const`. Note: `static` methods cannot also be `const`-qualified because there is no implicit `this` pointer to be const — just use `static`. Both qualifiers reduce coupling and improve generated code on all ESP32 targets.
|
||||
|
||||
---
|
||||
|
||||
## Hot-Path Optimization
|
||||
|
||||
The hot path is the per-frame pixel pipeline: **Segment → Strip → BusManager → Bus(Digital,HUB75,Network) or PolyBus → LED driver, plus ``WS2812FX::show()`` and below**.
|
||||
Speed is the priority here. The patterns below are taken from existing hot-path code (`FX_fcn.cpp`, `FX_2Dfcn.cpp`, `bus_manager.cpp`, `colors.cpp`) and should be followed when modifying these files.
|
||||
|
||||
Note: `FX.cpp` (effect functions) is written by many contributors and has diverse styles — that is acceptable.
|
||||
|
||||
### Function Attributes
|
||||
|
||||
Stack the appropriate attributes on hot-path functions. Defined in `const.h`:
|
||||
|
||||
| Attribute | Meaning | When to use |
|
||||
|---|---|---|
|
||||
| `__attribute__((hot))` | Branch-prediction hint | hot-path functions with complex logic |
|
||||
| `IRAM_ATTR` | Place in fast IRAM (ESP32) | Critical per-pixel functions (e.g. `BusDigital::setPixelColor`) |
|
||||
| `IRAM_ATTR_YN` | IRAM on ESP32, no-op on ESP8266 | Hot functions that ESP8266 can't fit in IRAM |
|
||||
| `WLED_O2_ATTR` | Force `-O2` optimization | Most hot-path functions |
|
||||
| `WLED_O3_ATTR` | Force `-O3,fast-math` | Innermost color math (e.g. `color_blend`) |
|
||||
| `[[gnu::hot]] inline` | Modern C++ attribute + inline | Header-defined accessors (e.g. `progress()`, `currentBri()`) |
|
||||
|
||||
Note: `WLED_O3_ATTR` sometimes causes performance loss compared to `WLED_O2_ATTR`. Choose optimization levels based on test results.
|
||||
|
||||
Example signature:
|
||||
|
||||
```cpp
|
||||
void IRAM_ATTR_YN WLED_O2_ATTR __attribute__((hot)) Segment::setPixelColor(unsigned i, uint32_t c)
|
||||
```
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
### Cache Members to Locals Before Loops
|
||||
|
||||
Copy class members and virtual-call results to local variables before entering a loop:
|
||||
|
||||
```cpp
|
||||
uint_fast8_t count = numBusses; // avoid repeated member access
|
||||
for (uint_fast8_t i = 0; i < count; i++) {
|
||||
Bus* const b = busses[i]; // const pointer hints to compiler
|
||||
uint_fast16_t bstart = b->getStart();
|
||||
uint_fast16_t blen = b->getLength();
|
||||
...
|
||||
}
|
||||
```
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
### Unsigned Range Check
|
||||
|
||||
Replace two-comparison range tests with a single unsigned subtraction:
|
||||
|
||||
```cpp
|
||||
// Instead of: if (pix >= bstart && pix < bstart + blen)
|
||||
if ((uint_fast16_t)(pix - bstart) < blen) // also catches negative pix via unsigned underflow
|
||||
```
|
||||
|
||||
### Early Returns
|
||||
|
||||
Guard every hot-path function with the cheapest necessary checks first:
|
||||
|
||||
```cpp
|
||||
if (!isActive()) return; // inactive segment
|
||||
if (unsigned(i) >= vLength()) return; // bounds check (catches negative i too)
|
||||
```
|
||||
|
||||
### Avoid Nested Calls — Fast Path / Complex Path
|
||||
|
||||
Avoid calling non-inline functions or making complex decisions inside per-pixel hot-path code. When a function has both a common simple case and a rare complex case, split it into two variants and choose once per frame rather than per pixel.
|
||||
|
||||
General rules:
|
||||
- Keep fast-path functions free of non-inline calls, multi-way branches, and complex switch-case decisions.
|
||||
- Hoist per-frame decisions (e.g. simple vs. complex segment) out of the per-pixel loop.
|
||||
- Code duplication between fast/slow variants is acceptable to keep the fast path lean.
|
||||
|
||||
### Function Pointers to Eliminate Repeated Decisions
|
||||
|
||||
When the same decision (e.g. "which drawing routine?") would be evaluated for every pixel, assign the chosen variant to a function pointer once and let the inner loop call through the pointer. This removes the branch entirely — the calling code (e.g. the GIF decoder loop) only ever invokes one function per frame, with no per-pixel decision.
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
`image_loader.cpp` demonstrates the pattern: `calculateScaling()` picks the best drawing callback once per frame based on segment dimensions and GIF size, then passes it to the decoder via `setDrawPixelCallback()`:
|
||||
|
||||
```cpp
|
||||
// calculateScaling() — called once per frame
|
||||
if ((perPixelX < 2) && (perPixelY < 2))
|
||||
decoder.setDrawPixelCallback(drawPixelCallbackDownScale2D); // downscale-only variant
|
||||
else
|
||||
decoder.setDrawPixelCallback(drawPixelCallback2D); // full-scaling variant
|
||||
```
|
||||
|
||||
Each callback is a small, single-purpose function with no internal branching — the decoder's per-pixel loop never re-evaluates which strategy to use.
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
### Template Specialization (Advanced)
|
||||
|
||||
Templates can eliminate runtime decisions by generating separate code paths at compile time. For example, a pixel setter could be templated on color order or channel count so the compiler removes dead branches and produces tight, specialized machine code:
|
||||
|
||||
```cpp
|
||||
template<bool hasWhite>
|
||||
void setChannel(uint8_t* out, uint32_t col) {
|
||||
out[0] = R(col); out[1] = G(col); out[2] = B(col);
|
||||
if constexpr (hasWhite) out[3] = W(col); // compiled out when hasWhite==false
|
||||
}
|
||||
```
|
||||
|
||||
Use sparingly — each instantiation duplicates code in flash. On ESP8266 and small-flash ESP32 boards this can exhaust IRAM/flash. Prefer templates only when the hot path is measurably faster and the number of instantiations is small (2–4).
|
||||
|
||||
### RAII Lock-Free Synchronization (Advanced)
|
||||
|
||||
Where contention is rare and the critical section is short, consider replacing mutex-based locking with lock-free techniques using `std::atomic` and RAII scoped guards. A scoped guard sets a flag on construction and clears it on destruction, guaranteeing cleanup even on early return:
|
||||
|
||||
```cpp
|
||||
struct ScopedBusyFlag {
|
||||
std::atomic<bool>& flag;
|
||||
bool acquired;
|
||||
ScopedBusyFlag(std::atomic<bool>& f) : flag(f), acquired(false) {
|
||||
bool expected = false;
|
||||
acquired = flag.compare_exchange_strong(expected, true);
|
||||
}
|
||||
~ScopedBusyFlag() { if (acquired) flag.store(false); }
|
||||
explicit operator bool() const { return acquired; }
|
||||
};
|
||||
|
||||
// Usage
|
||||
static std::atomic<bool> busySending{false};
|
||||
ScopedBusyFlag guard(busySending);
|
||||
if (!guard) return; // another task is already sending
|
||||
// ... do work — flag auto-clears when guard goes out of scope
|
||||
```
|
||||
|
||||
This avoids FreeRTOS semaphore overhead and the risk of forgetting to return a semaphore. There are no current examples of this pattern in the codebase — consult with maintainers before introducing it in new code, to ensure it aligns with the project's synchronization conventions.
|
||||
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
### Pre-Compute Outside Loops
|
||||
|
||||
Move invariant calculations before the loop. Pre-compute reciprocals to replace division with multiplication.
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
```cpp
|
||||
const uint_fast16_t cols = virtualWidth();
|
||||
const uint_fast16_t rows = virtualHeight();
|
||||
uint_fast8_t fadeRate = (255U - rate) >> 1;
|
||||
float mappedRate_r = 1.0f / (float(fadeRate) + 1.1f); // reciprocal — avoid division inside loop
|
||||
```
|
||||
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
### Parallel Channel Processing
|
||||
|
||||
Process R+B and W+G channels simultaneously using the two-channel mask pattern:
|
||||
|
||||
```cpp
|
||||
constexpr uint32_t TWO_CHANNEL_MASK = 0x00FF00FF;
|
||||
uint32_t rb = (((c1 & TWO_CHANNEL_MASK) * amount) >> 8) & TWO_CHANNEL_MASK;
|
||||
uint32_t wg = (((c1 >> 8) & TWO_CHANNEL_MASK) * amount) & ~TWO_CHANNEL_MASK;
|
||||
return rb | wg;
|
||||
```
|
||||
|
||||
### Bit Shifts Over Division (mainly for RISC-V boards)
|
||||
|
||||
ESP32 and ESP32-S3 (Xtensa core) have a fast "integer divide" instruction, so manual shifts rarely help.
|
||||
On RISC-V targets (ESP32-C3/C6/P4) and ESP8266, prefer explicit bit-shifts for power-of-two arithmetic — the compiler does **not** always convert divisions to shifts.
|
||||
Always use unsigned operands for right shifts; signed right-shift is implementation-defined.
|
||||
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
On RISC-V-based boards (ESP32-C3, ESP32-C6, ESP32-C5) explicit shifts can be beneficial.
|
||||
```cpp
|
||||
position >> 3 // instead of position / 8
|
||||
(255U - rate) >> 1 // instead of (255 - rate) / 2
|
||||
i & 0x0007 // instead of i % 8
|
||||
```
|
||||
|
||||
**Important**: The bit-shifted expression should be unsigned. On some MCUs, "signed right-shift" is implemented by an "arithmetic shift right" that duplicates the sign bit: ``0b1010 >> 1 = 0b1101``.
|
||||
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
### Static Caching for Expensive Computations
|
||||
|
||||
Cache results in static locals when the input rarely changes between calls:
|
||||
|
||||
```cpp
|
||||
static uint16_t lastKelvin = 0;
|
||||
static byte correctionRGB[4] = {255,255,255,0};
|
||||
if (lastKelvin != kelvin) {
|
||||
colorKtoRGB(kelvin, correctionRGB); // expensive — only recalculate when input changes
|
||||
lastKelvin = kelvin;
|
||||
}
|
||||
```
|
||||
|
||||
### Inlining Strategy
|
||||
|
||||
- Move frequently-called small functions to headers for inlining (e.g. `Segment::setPixelColorRaw` is in `FX.h`)
|
||||
- Use `static inline` for file-local helpers
|
||||
|
||||
### Math & Trigonometric Functions
|
||||
|
||||
- WLED uses a custom `fastled_slim` library. The old FastLED trig aliases (`sin8`, `cos8`, `sin16`, `cos16`) **no longer exist and cause a compile error** — use `sin8_t()`, `cos8_t()`, `sin16_t()`, `cos16_t()` instead. For float approximations use `sin_approx()` / `cos_approx()` instead of `sinf()` / `cosf()`. Replace FastLED noise aliases (`inoise8`, `inoise16`) with `perlin8`, `perlin16`.
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
|
||||
| ❌ Do not use (compile error) | ✅ Use instead | Source |
|
||||
|---|---|---|
|
||||
| `sin8()`, `cos8()` | `sin8_t()`, `cos8_t()` | `fastled_slim.h` → `wled_math.cpp` |
|
||||
| `sin16()`, `cos16()` | `sin16_t()`, `cos16_t()` | `fastled_slim.h` → `wled_math.cpp` |
|
||||
| `sinf()`, `cosf()` | `sin_approx()`, `cos_approx()` | `wled_math.cpp` |
|
||||
| `atan2f()`, `atan2()` | `atan2_t()` | `wled_math.cpp` |
|
||||
| `sqrt()` on integers | `sqrt32_bw()` | `fcn_declare.h` → `wled_math.cpp` |
|
||||
| `sqrtf()` on floats | `sqrtf()` (acceptable) | — no WLED replacement |
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
---
|
||||
|
||||
## `delay()` vs `yield()` in ESP32 Tasks
|
||||
<!-- HUMAN_ONLY_START -->
|
||||
* On ESP32, `delay(ms)` calls `vTaskDelay(ms / portTICK_PERIOD_MS)`, which **suspends only the calling task**. The FreeRTOS scheduler immediately runs all other ready tasks.
|
||||
* The Arduino `loop()` function runs inside `loopTask`. Calling `delay()` there does *not* block the network stack, audio FFT, LED DMA, nor any other FreeRTOS task.
|
||||
* This differs from ESP8266, where `delay()` stalls the entire system unless `yield()` was called inside.
|
||||
<!-- HUMAN_ONLY_END -->
|
||||
|
||||
- On ESP32, `delay()` is generally allowed, as it helps to efficiently manage CPU usage of all tasks.
|
||||
- On ESP8266, only use `delay()` and `yield()` in the main `loop()` context. If not sure, protect with `if (can_yield()) ...`.
|
||||
- Do *not* use `delay()` in effects (FX.cpp) or in the hot pixel path.
|
||||
- `delay()` on the bus-level is allowed, it might be needed to achieve exact timing in LED drivers.
|
||||
|
||||
### IDLE Watchdog and Custom Tasks on ESP32
|
||||
|
||||
- In arduino-esp32, `yield()` calls `vTaskDelay(0)`, which only switches to tasks at equal or higher priority — the IDLE task (priority 0) is never reached.
|
||||
- **Do not use `yield()` to pace ESP32 tasks or assume it feeds any watchdog**.
|
||||
- **Custom `xTaskCreate()` tasks must call `delay(1)` in their loop, not `yield()`.** Without a real blocking call, the IDLE task is starved. The IDLE watchdog panic is the first visible symptom — but the damage starts earlier: deleted task memory leaks, software timers stop firing, light sleep is disabled, and Wi-Fi/BT idle hooks don't run. Structure custom tasks like this:
|
||||
```cpp
|
||||
// WRONG — IDLE task is never scheduled; yield() does not feed the idle task watchdog.
|
||||
void myTask(void*) {
|
||||
for (;;) {
|
||||
doWork();
|
||||
yield();
|
||||
}
|
||||
}
|
||||
|
||||
// CORRECT — delay(1) suspends the task for ≥1 ms, IDLE task runs, IDLE watchdog is fed
|
||||
void myTask(void*) {
|
||||
for (;;) {
|
||||
doWork();
|
||||
delay(1); // DO NOT REMOVE — lets IDLE(0) run and feeds its watchdog
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Prefer blocking FreeRTOS primitives (`xQueueReceive`, `ulTaskNotifyTake`, `vTaskDelayUntil`) over `delay(1)` polling where precise timing or event-driven behaviour is needed.
|
||||
- **Watchdog note.** WLED disables the Task Watchdog by default (`WLED_WATCHDOG_TIMEOUT 0` in `wled.h`). When enabled, `esp_task_wdt_reset()` is called at the end of each `loop()` iteration. Long blocking operations inside `loop()` — such as OTA downloads or slow file I/O — must call `esp_task_wdt_reset()` periodically, or be restructured so the main loop is not blocked for longer than the configured timeout.
|
||||
|
||||
## Caveats and Pitfalls
|
||||
|
||||
- **LittleFS filenames**: File paths passed to `file.open()` must not exceed 255 bytes (`LFS_NAME_MAX`). Validate constructed paths (e.g., `/ledmap_` + segment name + `.json`) stay within this limit (assume standard configurations, like WLED_MAX_SEGNAME_LEN = 64).
|
||||
|
||||
- **Float-to-unsigned conversion is undefined behavior when the value is out of range.** Converting a negative `float` directly to an unsigned integer type (`uint8_t`, `uint16_t`, …) is UB per the C++ standard — the Xtensa (ESP32) toolchain may silently wrap, but RISC-V (ESP32-C3/C5/C6/P4) can produce different results due to clamping. Cast through a signed integer first:
|
||||
```cpp
|
||||
// Undefined behavior — avoid:
|
||||
uint8_t angle = 40.74f * atan2f(dy, dx); // negative float → uint8_t is UB
|
||||
|
||||
// Correct — cast through int first:
|
||||
// atan2f returns [-π..+π], scaled ≈ [-128..+128] as int; uint8_t wraps negative ints via 2's complement (e.g. -1 → 255)
|
||||
uint8_t angle = int(40.74f * atan2f(dy, dx)); // float→int (defined), int→uint8_t (defined)
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
applyTo: "wled00/data/**"
|
||||
---
|
||||
# Web UI Coding Conventions
|
||||
|
||||
## Formatting
|
||||
|
||||
- Indent **HTML and JavaScript** with **tabs**
|
||||
- Indent **CSS** with **tabs**
|
||||
|
||||
## JavaScript Style
|
||||
|
||||
- **camelCase** for functions and variables: `gId()`, `selectedFx`, `currentPreset`
|
||||
- Abbreviated helpers are common: `d` for `document`, `gId()` for `getElementById()`
|
||||
|
||||
## Key Files
|
||||
|
||||
- `index.htm` — main interface
|
||||
- `index.js` — functions that manage / update the main interface
|
||||
- `settings*.htm` — configuration pages
|
||||
- `*.css` — stylesheets (inlined during build)
|
||||
- `common.js` — helper functions
|
||||
|
||||
**Reuse shared helpers from `common.js` whenever possible** instead of duplicating utilities in page-local scripts.
|
||||
|
||||
## Build Integration
|
||||
|
||||
Files in this directory are processed by `tools/cdata.js` into generated headers
|
||||
(`wled00/html_*.h`, `wled00/js_*.h`).
|
||||
Run `npm run build` after any change. **Never edit generated headers directly.**
|
||||
Generated
+33
-31
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"name": "wled",
|
||||
"version": "0.16.0-alpha",
|
||||
"version": "17.0.0-dev",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wled",
|
||||
"version": "0.16.0-alpha",
|
||||
"version": "17.0.0-dev",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"clean-css": "^5.3.3",
|
||||
"html-minifier-terser": "^7.2.0",
|
||||
"nodemon": "^3.1.9",
|
||||
"nodemon": "^3.1.14",
|
||||
"web-resource-inliner": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
@@ -111,10 +111,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"license": "MIT"
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
|
||||
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/binary-extensions": {
|
||||
"version": "2.3.0",
|
||||
@@ -129,13 +132,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "1.1.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
|
||||
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
|
||||
"version": "5.0.5",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",
|
||||
"integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0",
|
||||
"concat-map": "0.0.1"
|
||||
"balanced-match": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/braces": {
|
||||
@@ -211,12 +216,6 @@
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/concat-map": {
|
||||
"version": "0.0.1",
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz",
|
||||
@@ -524,15 +523,18 @@
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
|
||||
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
|
||||
"license": "ISC",
|
||||
"version": "10.2.4",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.4.tgz",
|
||||
"integrity": "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^1.1.7"
|
||||
"brace-expansion": "^5.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
"node": "18 || 20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
@@ -552,15 +554,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nodemon": {
|
||||
"version": "3.1.9",
|
||||
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.9.tgz",
|
||||
"integrity": "sha512-hdr1oIb2p6ZSxu3PB2JWWYS7ZQ0qvaZsc3hK8DR8f02kRzc8rjYmxAIvdz+aYC+8F2IjNaB7HMcSDg8nQpJxyg==",
|
||||
"version": "3.1.14",
|
||||
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz",
|
||||
"integrity": "sha512-jakjZi93UtB3jHMWsXL68FXSAosbLfY0In5gtKq3niLSkrWznrVBzXFNOEMJUfc9+Ke7SHWoAZsiMkNP3vq6Jw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chokidar": "^3.5.2",
|
||||
"debug": "^4",
|
||||
"ignore-by-default": "^1.0.1",
|
||||
"minimatch": "^3.1.2",
|
||||
"minimatch": "^10.2.1",
|
||||
"pstree.remy": "^1.1.8",
|
||||
"semver": "^7.5.3",
|
||||
"simple-update-notifier": "^2.0.0",
|
||||
@@ -609,9 +611,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/picomatch": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
|
||||
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
|
||||
"integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wled",
|
||||
"version": "0.16.0-alpha",
|
||||
"version": "17.0.0-dev",
|
||||
"description": "Tools for WLED project",
|
||||
"main": "tools/cdata.js",
|
||||
"directories": {
|
||||
@@ -26,7 +26,7 @@
|
||||
"clean-css": "^5.3.3",
|
||||
"html-minifier-terser": "^7.2.0",
|
||||
"web-resource-inliner": "^7.0.0",
|
||||
"nodemon": "^3.1.9"
|
||||
"nodemon": "^3.1.14"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Add a section to the linker script to store our dynamic arrays
|
||||
# This is implemented as a pio post-script to ensure that we can
|
||||
# place our linker script at the correct point in the command arguments.
|
||||
Import("env")
|
||||
from pathlib import Path
|
||||
|
||||
platform = env.get("PIOPLATFORM")
|
||||
script_file = Path(f"tools/dynarray_{platform}.ld")
|
||||
if script_file.is_file():
|
||||
linker_script = f"-T{script_file}"
|
||||
if platform == "espressif32":
|
||||
# For ESP32, the script must be added at the right point in the list
|
||||
linkflags = env.get("LINKFLAGS", [])
|
||||
idx = linkflags.index("memory.ld")
|
||||
linkflags.insert(idx+1, linker_script)
|
||||
env.Replace(LINKFLAGS=linkflags)
|
||||
else:
|
||||
# For other platforms, put it in last
|
||||
env.Append(LINKFLAGS=[linker_script])
|
||||
+121
-18
@@ -1,6 +1,8 @@
|
||||
Import('env')
|
||||
from collections import deque
|
||||
from pathlib import Path # For OS-agnostic path manipulation
|
||||
import re
|
||||
from urllib.parse import urlparse
|
||||
from click import secho
|
||||
from SCons.Script import Exit
|
||||
from platformio.builder.tools.piolib import LibBuilderBase
|
||||
@@ -25,25 +27,117 @@ def find_usermod(mod: str) -> Path:
|
||||
return mp
|
||||
raise RuntimeError(f"Couldn't locate module {mod} in usermods directory!")
|
||||
|
||||
def is_wled_module(dep: LibBuilderBase) -> bool:
|
||||
"""Returns true if the specified library is a wled module
|
||||
# Names of external/registry deps listed in custom_usermods.
|
||||
# Populated during parsing below; read by is_wled_module() at configure time.
|
||||
_custom_usermod_names: set[str] = set()
|
||||
|
||||
# Matches any RFC-valid URL scheme (http, https, git, git+https, symlink, file, hg+ssh, etc.)
|
||||
_URL_SCHEME_RE = re.compile(r'^[a-zA-Z][a-zA-Z0-9+.-]*://')
|
||||
# SSH git URL: user@host:path (e.g. git@github.com:user/repo.git#tag)
|
||||
_SSH_URL_RE = re.compile(r'^[^@\s]+@[^@:\s]+:[^:\s]')
|
||||
# Explicit custom name: "LibName = <spec>" (PlatformIO [<name>=]<spec> form)
|
||||
_NAME_EQ_RE = re.compile(r'^([A-Za-z0-9_.-]+)\s*=\s*(\S.*)')
|
||||
|
||||
|
||||
def _is_external_entry(line: str) -> bool:
|
||||
"""Return True if line is a lib_deps-style external/registry entry."""
|
||||
if _NAME_EQ_RE.match(line): # "LibName = <spec>"
|
||||
return True
|
||||
if _URL_SCHEME_RE.match(line): # https://, git://, symlink://, etc.
|
||||
return True
|
||||
if _SSH_URL_RE.match(line): # git@github.com:user/repo.git
|
||||
return True
|
||||
if '@' in line: # "owner/Name @ ^1.0.0"
|
||||
return True
|
||||
if re.match(r'^[^/\s]+/[^/\s]+$', line): # "owner/Name"
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _predict_dep_name(entry: str) -> str | None:
|
||||
"""Predict the library name PlatformIO will assign to this dep (best-effort).
|
||||
|
||||
Accuracy relies on the library's manifest "name" matching the repo/package
|
||||
name in the spec. This holds for well-authored libraries; the libArchive
|
||||
check (which requires library.json) provides an early-failure safety net.
|
||||
"""
|
||||
return usermod_dir in Path(dep.src_dir).parents or str(dep.name).startswith("wled-")
|
||||
entry = entry.strip()
|
||||
# "LibName = <spec>" — name is given explicitly; always use it
|
||||
m = _NAME_EQ_RE.match(entry)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
# URL scheme: extract name from path
|
||||
if _URL_SCHEME_RE.match(entry):
|
||||
parsed = urlparse(entry)
|
||||
if parsed.netloc in ('github.com', 'gitlab.com', 'bitbucket.com'):
|
||||
parts = [p for p in parsed.path.split('/') if p]
|
||||
if len(parts) >= 2:
|
||||
name = parts[1]
|
||||
else:
|
||||
name = Path(parsed.path.rstrip('/')).name.strip()
|
||||
if name.endswith('.git'):
|
||||
name = name[:-4]
|
||||
return name or None
|
||||
# SSH git URL: git@github.com:user/repo.git#tag → repo
|
||||
if _SSH_URL_RE.match(entry):
|
||||
path_part = entry.split(':', 1)[1].split('#')[0].rstrip('/')
|
||||
name = Path(path_part).name
|
||||
return (name[:-4] if name.endswith('.git') else name) or None
|
||||
# Versioned registry: "owner/Name @ version" → Name
|
||||
if '@' in entry:
|
||||
name_part = entry.split('@')[0].strip()
|
||||
return name_part.split('/')[-1].strip() if '/' in name_part else name_part
|
||||
# Plain registry: "owner/Name" → Name
|
||||
if re.match(r'^[^/\s]+/[^/\s]+$', entry):
|
||||
return entry.split('/')[-1].strip()
|
||||
return None
|
||||
|
||||
## Script starts here
|
||||
# Process usermod option
|
||||
usermods = env.GetProjectOption("custom_usermods","")
|
||||
|
||||
# Handle "all usermods" case
|
||||
if usermods == '*':
|
||||
usermods = [f.name for f in usermod_dir.iterdir() if f.is_dir() and f.joinpath('library.json').exists()]
|
||||
else:
|
||||
usermods = usermods.split()
|
||||
def is_wled_module(dep: LibBuilderBase) -> bool:
|
||||
"""Returns true if the specified library is a wled module."""
|
||||
return (
|
||||
usermod_dir in Path(dep.src_dir).parents
|
||||
or str(dep.name).startswith("wled-")
|
||||
or dep.name in _custom_usermod_names
|
||||
)
|
||||
|
||||
if usermods:
|
||||
# Inject usermods in to project lib_deps
|
||||
symlinks = [f"symlink://{find_usermod(mod).resolve()}" for mod in usermods]
|
||||
env.GetProjectConfig().set("env:" + env['PIOENV'], 'lib_deps', env.GetProjectOption('lib_deps') + symlinks)
|
||||
|
||||
## Script starts here — parse custom_usermods
|
||||
raw_usermods = env.GetProjectOption("custom_usermods", "")
|
||||
usermods_libdeps: list[str] = []
|
||||
|
||||
for line in raw_usermods.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#') or line.startswith(';'):
|
||||
continue
|
||||
|
||||
if _is_external_entry(line):
|
||||
# External URL or registry entry: pass through to lib_deps unchanged.
|
||||
predicted = _predict_dep_name(line)
|
||||
if predicted:
|
||||
_custom_usermod_names.add(predicted)
|
||||
else:
|
||||
secho(
|
||||
f"WARNING: Cannot determine library name for custom_usermods entry "
|
||||
f"{line!r}. If it is not recognised as a WLED module at build time, "
|
||||
f"ensure its library.json 'name' matches the repo name.",
|
||||
fg="yellow", err=True)
|
||||
usermods_libdeps.append(line)
|
||||
else:
|
||||
# Bare name(s): split on whitespace for backwards compatibility.
|
||||
for token in line.split():
|
||||
if token == '*':
|
||||
for mod_path in sorted(usermod_dir.iterdir()):
|
||||
if mod_path.is_dir() and (mod_path / 'library.json').exists():
|
||||
_custom_usermod_names.add(mod_path.name)
|
||||
usermods_libdeps.append(f"symlink://{mod_path.resolve()}")
|
||||
else:
|
||||
resolved = find_usermod(token)
|
||||
_custom_usermod_names.add(resolved.name)
|
||||
usermods_libdeps.append(f"symlink://{resolved.resolve()}")
|
||||
|
||||
if usermods_libdeps:
|
||||
env.GetProjectConfig().set("env:" + env['PIOENV'], 'lib_deps', env.GetProjectOption('lib_deps') + usermods_libdeps)
|
||||
|
||||
# Utility function for assembling usermod include paths
|
||||
def cached_add_includes(dep, dep_cache: set, includes: deque):
|
||||
@@ -86,6 +180,14 @@ def wrapped_ConfigureProjectLibBuilder(xenv):
|
||||
# Add WLED's own dependencies
|
||||
for dir in extra_include_dirs:
|
||||
dep.env.PrependUnique(CPPPATH=str(dir))
|
||||
# Ensure debug info is emitted for this module's source files.
|
||||
# validate_modules.py uses `nm --defined-only -l` on the final ELF to check
|
||||
# that each module has at least one symbol placed in the binary. The -l flag
|
||||
# reads DWARF debug sections to map placed symbols back to their original source
|
||||
# files; without -g those sections are absent and the check cannot attribute any
|
||||
# symbol to a specific module. We scope this to usermods only — the main WLED
|
||||
# build and other libraries are unaffected.
|
||||
dep.env.AppendUnique(CCFLAGS=["-g"])
|
||||
# Enforce that libArchive is not set; we must link them directly to the executable
|
||||
if dep.lib_archive:
|
||||
broken_usermods.append(dep)
|
||||
@@ -93,9 +195,10 @@ def wrapped_ConfigureProjectLibBuilder(xenv):
|
||||
if broken_usermods:
|
||||
broken_usermods = [usermod.name for usermod in broken_usermods]
|
||||
secho(
|
||||
f"ERROR: libArchive=false is missing on usermod(s) {' '.join(broken_usermods)} -- modules will not compile in correctly",
|
||||
fg="red",
|
||||
err=True)
|
||||
f"ERROR: libArchive=false is missing on usermod(s) {' '.join(broken_usermods)} -- "
|
||||
f"modules will not compile in correctly. Add '\"build\": {{\"libArchive\": false}}' "
|
||||
f"to their library.json.",
|
||||
fg="red", err=True)
|
||||
Exit(1)
|
||||
|
||||
# Save the depbuilders list for later validation
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path # For OS-agnostic path manipulation
|
||||
from typing import Iterable
|
||||
from click import secho
|
||||
from SCons.Script import Action, Exit
|
||||
from platformio.builder.tools.piolib import LibBuilderBase
|
||||
|
||||
|
||||
def is_wled_module(env, dep: LibBuilderBase) -> bool:
|
||||
"""Returns true if the specified library is a wled module
|
||||
"""
|
||||
usermod_dir = Path(env["PROJECT_DIR"]).resolve() / "usermods"
|
||||
return usermod_dir in Path(dep.src_dir).parents or str(dep.name).startswith("wled-")
|
||||
Import("env")
|
||||
|
||||
|
||||
def read_lines(p: Path):
|
||||
@@ -19,29 +13,80 @@ def read_lines(p: Path):
|
||||
return f.readlines()
|
||||
|
||||
|
||||
def check_map_file_objects(map_file: list[str], dirs: Iterable[str]) -> set[str]:
|
||||
""" Identify which dirs contributed to the final build
|
||||
def _get_nm_path(env) -> str:
|
||||
""" Derive the nm tool path from the build environment """
|
||||
if "NM" in env:
|
||||
return env.subst("$NM")
|
||||
# Derive from the C compiler: xtensa-esp32-elf-gcc → xtensa-esp32-elf-nm
|
||||
cc = env.subst("$CC")
|
||||
nm = re.sub(r'(gcc|g\+\+)$', 'nm', os.path.basename(cc))
|
||||
return os.path.join(os.path.dirname(cc), nm)
|
||||
|
||||
Returns the (sub)set of dirs that are found in the output ELF
|
||||
|
||||
def check_elf_modules(elf_path: Path, env, module_lib_builders) -> set[str]:
|
||||
""" Check which modules have at least one defined symbol placed in the ELF.
|
||||
|
||||
The map file is not a reliable source for this: with LTO, original object
|
||||
file paths are replaced by temporary ltrans.o partitions in all output
|
||||
sections, making per-module attribution impossible from the map alone.
|
||||
Instead we invoke nm --defined-only -l on the ELF, which uses DWARF debug
|
||||
info to attribute each placed symbol to its original source file.
|
||||
|
||||
Requires usermod libraries to be compiled with -g so that DWARF sections
|
||||
are present in the ELF. load_usermods.py injects -g for all WLED modules
|
||||
via dep.env.AppendUnique(CCFLAGS=["-g"]).
|
||||
|
||||
Returns the set of build_dir basenames for confirmed modules.
|
||||
"""
|
||||
# Pattern to match symbols in object directories
|
||||
# Join directories into alternation
|
||||
usermod_dir_regex = "|".join([re.escape(dir) for dir in dirs])
|
||||
# Matches nonzero address, any size, and any path in a matching directory
|
||||
object_path_regex = re.compile(r"0x0*[1-9a-f][0-9a-f]*\s+0x[0-9a-f]+\s+\S+[/\\](" + usermod_dir_regex + r")[/\\]\S+\.o")
|
||||
nm_path = _get_nm_path(env)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[nm_path, "--defined-only", "-l", str(elf_path)],
|
||||
capture_output=True, text=True, errors="ignore", timeout=120,
|
||||
)
|
||||
nm_output = result.stdout
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
|
||||
secho(f"WARNING: nm failed ({e}); skipping per-module validation", fg="yellow", err=True)
|
||||
return {Path(b.build_dir).name for b in module_lib_builders} # conservative pass
|
||||
|
||||
# Match placed symbols against builders as we parse nm output, exiting early
|
||||
# once all builders are accounted for.
|
||||
# nm --defined-only still includes debugging symbols (type 'N') such as the
|
||||
# per-CU markers GCC emits in .debug_info (e.g. "usermod_example_cpp_6734d48d").
|
||||
# These live at address 0x00000000 in their debug section — not in any load
|
||||
# segment — so filtering them out leaves only genuinely placed symbols.
|
||||
# nm -l appends a tab-separated "file:lineno" location to each symbol line.
|
||||
remaining = {Path(str(b.src_dir)): Path(b.build_dir).name for b in module_lib_builders}
|
||||
found = set()
|
||||
for line in map_file:
|
||||
matches = object_path_regex.findall(line)
|
||||
for m in matches:
|
||||
found.add(m)
|
||||
|
||||
for line in nm_output.splitlines():
|
||||
if not remaining:
|
||||
break # all builders matched
|
||||
addr, _, _ = line.partition(' ')
|
||||
if not addr.lstrip('0'):
|
||||
continue # zero address — skip debug-section marker
|
||||
if '\t' not in line:
|
||||
continue
|
||||
loc = line.rsplit('\t', 1)[1]
|
||||
# Strip trailing :lineno (e.g. "/path/to/foo.cpp:42" → "/path/to/foo.cpp")
|
||||
src_path = Path(loc.rsplit(':', 1)[0])
|
||||
# Path.is_relative_to() handles OS-specific separators correctly without
|
||||
# any regex, avoiding Windows path escaping issues.
|
||||
for src_dir in list(remaining):
|
||||
if src_path.is_relative_to(src_dir):
|
||||
found.add(remaining.pop(src_dir))
|
||||
break
|
||||
|
||||
return found
|
||||
|
||||
|
||||
DYNARRAY_SECTION = ".dtors" if env.get("PIOPLATFORM") == "espressif8266" else ".dynarray"
|
||||
USERMODS_SECTION = f"{DYNARRAY_SECTION}.usermods.1"
|
||||
|
||||
def count_usermod_objects(map_file: list[str]) -> int:
|
||||
""" Returns the number of usermod objects in the usermod list """
|
||||
# Count the number of entries in the usermods table section
|
||||
return len([x for x in map_file if ".dtors.tbl.usermods.1" in x])
|
||||
return len([x for x in map_file if USERMODS_SECTION in x])
|
||||
|
||||
|
||||
def validate_map_file(source, target, env):
|
||||
@@ -65,16 +110,17 @@ def validate_map_file(source, target, env):
|
||||
usermod_object_count = count_usermod_objects(map_file_contents)
|
||||
secho(f"INFO: {usermod_object_count} usermod object entries")
|
||||
|
||||
confirmed_modules = check_map_file_objects(map_file_contents, modules.keys())
|
||||
elf_path = build_dir / env.subst("${PROGNAME}.elf")
|
||||
confirmed_modules = check_elf_modules(elf_path, env, module_lib_builders)
|
||||
|
||||
missing_modules = [modname for mdir, modname in modules.items() if mdir not in confirmed_modules]
|
||||
if missing_modules:
|
||||
secho(
|
||||
f"ERROR: No object files from {missing_modules} found in linked output!",
|
||||
f"ERROR: No symbols from {missing_modules} found in linked output!",
|
||||
fg="red",
|
||||
err=True)
|
||||
Exit(1)
|
||||
return None
|
||||
|
||||
Import("env")
|
||||
env.Append(LINKFLAGS=[env.subst("-Wl,--Map=${BUILD_DIR}/${PROGNAME}.map")])
|
||||
env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", Action(validate_map_file, cmdstr='Checking linked optional modules (usermods) in map file'))
|
||||
|
||||
+23
-5
@@ -29,6 +29,7 @@ default_envs = nodemcuv2
|
||||
esp32S3_wroom2
|
||||
esp32s3dev_16MB_opi
|
||||
esp32s3dev_8MB_opi
|
||||
esp32s3dev_8MB_qspi
|
||||
esp32s3_4M_qspi
|
||||
usermods
|
||||
|
||||
@@ -134,6 +135,7 @@ extra_scripts =
|
||||
pre:pio-scripts/set_metadata.py
|
||||
post:pio-scripts/output_bins.py
|
||||
post:pio-scripts/strip-floats.py
|
||||
post:pio-scripts/dynarray.py
|
||||
pre:pio-scripts/user_config_copy.py
|
||||
pre:pio-scripts/load_usermods.py
|
||||
pre:pio-scripts/build_ui.py
|
||||
@@ -159,7 +161,6 @@ upload_speed = 115200
|
||||
# ------------------------------------------------------------------------------
|
||||
lib_compat_mode = strict
|
||||
lib_deps =
|
||||
fastled/FastLED @ 3.6.0
|
||||
IRremoteESP8266 @ 2.8.2
|
||||
https://github.com/Makuna/NeoPixelBus.git#a0919d1c10696614625978dd6fb750a1317a14ce
|
||||
https://github.com/Aircoookie/ESPAsyncWebServer.git#v2.4.2
|
||||
@@ -247,7 +248,6 @@ lib_deps_compat =
|
||||
ESPAsyncTCP @ 1.2.2
|
||||
ESPAsyncUDP
|
||||
ESP8266PWM
|
||||
fastled/FastLED @ 3.6.0
|
||||
IRremoteESP8266 @ 2.8.2
|
||||
makuna/NeoPixelBus @ 2.7.9
|
||||
https://github.com/blazoncek/QuickESPNow.git#optional-debug
|
||||
@@ -290,8 +290,7 @@ AR_lib_deps = ;; for pre-usermod-library platformio_override compatibility
|
||||
;; please note that you can NOT update existing ESP32 installs with a "V4" build. Also updating by OTA will not work properly.
|
||||
;; You need to completely erase your device (esptool erase_flash) first, then install the "V4" build from VSCode+platformio.
|
||||
|
||||
;; select arduino-esp32 v2.0.9 (arduino-esp32 2.0.10 thru 2.0.14 are buggy so avoid them)
|
||||
platform = https://github.com/tasmota/platform-espressif32/releases/download/2023.06.02/platform-espressif32.zip ;; Tasmota Arduino Core 2.0.9 with IPv6 support, based on IDF 4.4.4
|
||||
platform = https://github.com/tasmota/platform-espressif32/releases/download/2024.06.00/platform-espressif32.zip ;; Tasmota Arduino Core 2.0.18 with IPv6 support, based on IDF 4.4.8
|
||||
platform_packages =
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = -g
|
||||
@@ -431,6 +430,7 @@ build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=
|
||||
; -D WLED_USE_REAL_MATH ;; may fix wrong sunset/sunrise times, at the cost of 7064 bytes FLASH and 975 bytes RAM
|
||||
-D WLED_DISABLE_PARTICLESYSTEM1D
|
||||
-D WLED_DISABLE_PARTICLESYSTEM2D
|
||||
-D WLED_DISABLE_PIXELFORGE
|
||||
lib_deps = ${esp8266.lib_deps}
|
||||
|
||||
[env:esp01_1m_full_compat]
|
||||
@@ -441,6 +441,7 @@ platform_packages = ${esp8266.platform_packages_compat}
|
||||
build_flags = ${common.build_flags} ${esp8266.build_flags_compat} -D WLED_RELEASE_NAME=\"ESP01_compat\" -D WLED_DISABLE_OTA #-DWLED_DISABLE_2D
|
||||
-D WLED_DISABLE_PARTICLESYSTEM1D
|
||||
-D WLED_DISABLE_PARTICLESYSTEM2D
|
||||
-D WLED_DISABLE_PIXELFORGE
|
||||
|
||||
[env:esp01_1m_full_160]
|
||||
extends = env:esp01_1m_full
|
||||
@@ -449,6 +450,7 @@ build_flags = ${common.build_flags} ${esp8266.build_flags} -D WLED_RELEASE_NAME=
|
||||
; -D WLED_USE_REAL_MATH ;; may fix wrong sunset/sunrise times, at the cost of 7064 bytes FLASH and 975 bytes RAM
|
||||
-D WLED_DISABLE_PARTICLESYSTEM1D
|
||||
-D WLED_DISABLE_PARTICLESYSTEM2D
|
||||
-D WLED_DISABLE_PIXELFORGE
|
||||
custom_usermods = audioreactive
|
||||
|
||||
[env:esp32dev]
|
||||
@@ -511,8 +513,10 @@ upload_speed = 921600
|
||||
custom_usermods = audioreactive
|
||||
build_unflags = ${common.build_unflags}
|
||||
build_flags = ${common.build_flags} ${esp32.build_flags} -D WLED_RELEASE_NAME=\"ESP32_Ethernet\" -D RLYPIN=-1 -D WLED_USE_ETHERNET -D BTNPIN=-1
|
||||
-D SR_DMTYPE=-1 -D AUDIOPIN=-1 -D I2S_SDPIN=-1 -D I2S_WSPIN=-1 -D I2S_CKPIN=-1 -D MCLK_PIN=-1 ;; force AR to not allocate any PINs at startup
|
||||
-D DATA_PINS=4 ;; default led pin = 16 conflicts with pins used for ethernet
|
||||
; -D WLED_DISABLE_ESPNOW ;; ESP-NOW requires wifi, may crash with ethernet only => uncomment if your board uses ETH_CLOCK_GPIO0_OUT, ETH_CLOCK_GPIO16_OUT, ETH_CLOCK_GPIO17_OUT
|
||||
-DARDUINO_USB_CDC_ON_BOOT=0 ;; this flag is mandatory for "classic ESP32" when building with arduino-esp32 >=2.0.3
|
||||
; -D WLED_DISABLE_ESPNOW ;; ESP-NOW requires wifi, may crash with ethernet only
|
||||
lib_deps = ${esp32.lib_deps}
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
board_build.flash_mode = dio
|
||||
@@ -538,6 +542,7 @@ platform_packages = ${esp32c3.platform_packages}
|
||||
framework = arduino
|
||||
board = esp32-c3-devkitm-1
|
||||
board_build.partitions = ${esp32.default_partitions}
|
||||
custom_usermods = audioreactive
|
||||
build_flags = ${common.build_flags} ${esp32c3.build_flags} -D WLED_RELEASE_NAME=\"ESP32-C3\"
|
||||
-D WLED_WATCHDOG_TIMEOUT=0
|
||||
-DLOLIN_WIFI_FIX ; seems to work much better with this
|
||||
@@ -595,6 +600,19 @@ board_build.f_flash = 80000000L
|
||||
board_build.flash_mode = qio
|
||||
monitor_filters = esp32_exception_decoder
|
||||
|
||||
[env:esp32s3dev_8MB_qspi]
|
||||
;; generic ESP32-S3 board with 8MB FLASH and PSRAM (memory_type: qio_qspi). Try this one if esp32s3dev_8MB_opi does not work on your board
|
||||
extends = env:esp32s3dev_8MB_opi
|
||||
board_build.arduino.memory_type = qio_qspi
|
||||
board_build.flash_mode = qio
|
||||
build_flags = ${common.build_flags} ${esp32s3.build_flags} -D WLED_RELEASE_NAME=\"ESP32-S3_8MB_qspi\"
|
||||
-D WLED_WATCHDOG_TIMEOUT=0
|
||||
;-D ARDUINO_USB_CDC_ON_BOOT=0 ;; -D ARDUINO_USB_MODE=1 ;; for boards with serial-to-USB chip
|
||||
-D ARDUINO_USB_CDC_ON_BOOT=1 ;; -D ARDUINO_USB_MODE=1 ;; for boards with USB-OTG connector only (USBCDC or "TinyUSB")
|
||||
-DBOARD_HAS_PSRAM
|
||||
;; -DLOLIN_WIFI_FIX ;; uncomment if you have WiFi connectivity problems
|
||||
monitor_filters = esp32_exception_decoder
|
||||
|
||||
[env:esp32S3_wroom2]
|
||||
;; For ESP32-S3 WROOM-2, a.k.a. ESP32-S3 DevKitC-1 v1.1
|
||||
;; with >= 16MB FLASH and >= 8MB PSRAM (memory_type: opi_opi)
|
||||
|
||||
@@ -47,7 +47,7 @@ build_flags = ${common.build_flags} ${esp8266.build_flags}
|
||||
; -D WLED_DISABLE_MQTT
|
||||
; -D WLED_DISABLE_ADALIGHT
|
||||
; -D WLED_DISABLE_2D
|
||||
; -D WLED_DISABLE_PXMAGIC
|
||||
; -D WLED_DISABLE_PIXELFORGE
|
||||
; -D WLED_DISABLE_ESPNOW
|
||||
; -D WLED_DISABLE_BROWNOUT_DET
|
||||
;
|
||||
@@ -538,9 +538,21 @@ monitor_filters = esp32_exception_decoder
|
||||
# 433MHz RF remote example for esp32dev
|
||||
[env:esp32dev_usermod_RF433]
|
||||
extends = env:esp32dev
|
||||
build_flags = ${env:esp32dev.build_flags} -D USERMOD_RF433
|
||||
lib_deps = ${env:esp32dev.lib_deps}
|
||||
sui77/rc-switch @ 2.6.4
|
||||
custom_usermods =
|
||||
${env:esp32dev.custom_usermods}
|
||||
RF433
|
||||
|
||||
# External usermod from a git repository.
|
||||
# The library's `library.json` must include `"build": {"libArchive": false}`.
|
||||
# The name PlatformIO assigns is taken from the library's `library.json` "name" field.
|
||||
# If that name doesn't match the repo name in the URL, use the "LibName = URL" form
|
||||
# shown in the commented-out line below to supply the name explicitly.
|
||||
[env:esp32dev_external_usermod]
|
||||
extends = env:esp32dev
|
||||
custom_usermods =
|
||||
${env:esp32dev.custom_usermods}
|
||||
https://github.com/wled/wled-usermod-example.git#main
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Hub75 examples
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ pyelftools==0.32
|
||||
# via platformio
|
||||
pyserial==3.5
|
||||
# via platformio
|
||||
requests==2.32.4
|
||||
requests==2.33.0
|
||||
# via platformio
|
||||
semantic-version==2.10.0
|
||||
# via platformio
|
||||
|
||||
+34
-1
@@ -26,7 +26,7 @@ const packageJson = require("../package.json");
|
||||
// Export functions for testing
|
||||
module.exports = { isFileNewerThan, isAnyFileInFolderNewerThan };
|
||||
|
||||
const output = ["wled00/html_ui.h", "wled00/html_pixart.h", "wled00/html_cpal.h", "wled00/html_edit.h", "wled00/html_pxmagic.h", "wled00/html_pixelforge.h", "wled00/html_settings.h", "wled00/html_other.h"]
|
||||
const output = ["wled00/html_ui.h", "wled00/html_pixart.h", "wled00/html_cpal.h", "wled00/html_edit.h", "wled00/html_pxmagic.h", "wled00/html_pixelforge.h", "wled00/html_settings.h", "wled00/html_other.h", "wled00/js_iro.h", "wled00/js_omggif.h"]
|
||||
|
||||
// \x1b[34m is blue, \x1b[36m is cyan, \x1b[0m is reset
|
||||
const wledBanner = `
|
||||
@@ -257,6 +257,33 @@ writeHtmlGzipped("wled00/data/pxmagic/pxmagic.htm", "wled00/html_pxmagic.h", 'px
|
||||
writeHtmlGzipped("wled00/data/pixelforge/pixelforge.htm", "wled00/html_pixelforge.h", 'pixelforge', false); // do not inline css
|
||||
//writeHtmlGzipped("wled00/data/edit.htm", "wled00/html_edit.h", 'edit');
|
||||
|
||||
writeChunks(
|
||||
"wled00/data/",
|
||||
[
|
||||
{
|
||||
file: "iro.js",
|
||||
name: "JS_iro",
|
||||
method: "gzip",
|
||||
filter: "plain", // no minification, it is already minified
|
||||
mangle: (s) => s.replace(/^\/\*![\s\S]*?\*\//, '') // remove license comment at the top
|
||||
}
|
||||
],
|
||||
"wled00/js_iro.h"
|
||||
);
|
||||
|
||||
writeChunks(
|
||||
"wled00/data/pixelforge",
|
||||
[
|
||||
{
|
||||
file: "omggif.js",
|
||||
name: "JS_omggif",
|
||||
method: "gzip",
|
||||
filter: "js-minify",
|
||||
mangle: (s) => s.replace(/^\/\*![\s\S]*?\*\//, '') // remove license comment at the top
|
||||
}
|
||||
],
|
||||
"wled00/js_omggif.h"
|
||||
);
|
||||
|
||||
writeChunks(
|
||||
"wled00/data",
|
||||
@@ -367,6 +394,12 @@ writeChunks(
|
||||
name: "PAGE_settings_pin",
|
||||
method: "gzip",
|
||||
filter: "html-minify"
|
||||
},
|
||||
{
|
||||
file: "settings_pininfo.htm",
|
||||
name: "PAGE_settings_pininfo",
|
||||
method: "gzip",
|
||||
filter: "html-minify"
|
||||
}
|
||||
],
|
||||
"wled00/html_settings.h"
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/* ESP32 linker script fragment to add dynamic array section to binary */
|
||||
SECTIONS
|
||||
{
|
||||
.dynarray :
|
||||
{
|
||||
. = ALIGN(0x10);
|
||||
KEEP(*(SORT_BY_INIT_PRIORITY(.dynarray.*)))
|
||||
} > default_rodata_seg
|
||||
}
|
||||
INSERT AFTER .flash.rodata;
|
||||
@@ -0,0 +1,696 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>WBF ↔ C Header Bi-Directional Converter</title>
|
||||
<style>
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
}
|
||||
body {
|
||||
font-family: system-ui, sans-serif;
|
||||
background: #0a0a0a;
|
||||
color: #e0e0e0;
|
||||
padding: 20px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
.card {
|
||||
max-width: 900px;
|
||||
margin: auto;
|
||||
background: #16213e;
|
||||
padding: 30px;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 20px rgba(0, 242, 255, .15);
|
||||
border: 1px solid rgba(0, 242, 255, .1);
|
||||
}
|
||||
h1 {
|
||||
color: #00f2ff;
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
font-size: 2rem;
|
||||
text-shadow: 0 0 25px #ffffff;
|
||||
}
|
||||
.mode-selector {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.mode-btn {
|
||||
padding: 14px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
border: 2px solid rgba(0, 242, 255, .3);
|
||||
background: rgba(0, 0, 0, .4);
|
||||
color: #888;
|
||||
transition: all .3s;
|
||||
}
|
||||
.mode-btn.active {
|
||||
background: linear-gradient(135deg, #0095b3 0%, #00d4ff 100%);
|
||||
border-color: #00f2ff;
|
||||
color: #fff;
|
||||
box-shadow: 0 0 14px rgba(0, 242, 255, .6);
|
||||
}
|
||||
.mode-btn:hover:not(.active) {
|
||||
border-color: #00f2ff;
|
||||
color: #00f2ff;
|
||||
}
|
||||
.controls {
|
||||
background: rgba(255, 255, 255, .03);
|
||||
padding: 20px;
|
||||
border-radius: 15px;
|
||||
margin-bottom: 20px;
|
||||
border: 1px solid rgba(0, 242, 255, .1);
|
||||
display: none;
|
||||
}
|
||||
.controls.active {
|
||||
display: block;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
font-size: .85rem;
|
||||
font-weight: 600;
|
||||
color: #00d4ff;
|
||||
margin-bottom: 8px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .5px;
|
||||
}
|
||||
input[type="file"] {
|
||||
display: none;
|
||||
}
|
||||
.file-label {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(0, 242, 255, .2);
|
||||
background: rgba(0, 0, 0, .4);
|
||||
color: #888;
|
||||
cursor: pointer;
|
||||
text-align: center;
|
||||
transition: all .3s;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
.file-label:hover {
|
||||
border-color: #00f2ff;
|
||||
color: #00f2ff;
|
||||
}
|
||||
.file-label.has-file {
|
||||
color: #00f2ff;
|
||||
}
|
||||
input[type="text"], textarea {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(0, 242, 255, .2);
|
||||
background: rgba(0, 0, 0, .4);
|
||||
color: #fff;
|
||||
margin-bottom: 15px;
|
||||
transition: all .3s;
|
||||
font-family: 'Courier New', monospace;
|
||||
}
|
||||
textarea {
|
||||
min-height: 300px;
|
||||
resize: vertical;
|
||||
font-size: .85rem;
|
||||
}
|
||||
input[type="text"]:focus, textarea:focus {
|
||||
outline: none;
|
||||
border-color: #00f2ff;
|
||||
box-shadow: 0 0 8px rgba(0, 242, 255, .3);
|
||||
}
|
||||
button {
|
||||
width: 100%;
|
||||
padding: 14px;
|
||||
border-radius: 50px;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
border: none;
|
||||
background: linear-gradient(135deg, #0095b3 0%, #00d4ff 100%);
|
||||
box-shadow: 0 0 14px rgba(0, 242, 255, .6);
|
||||
color: #fff;
|
||||
transition: all .3s;
|
||||
}
|
||||
button:hover:not(:disabled) {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 0 18px rgba(0, 242, 255, .9);
|
||||
}
|
||||
button:disabled {
|
||||
opacity: .3;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.info {
|
||||
background: rgba(0, 242, 255, .05);
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 20px;
|
||||
border: 1px solid rgba(0, 242, 255, .2);
|
||||
font-size: .85rem;
|
||||
}
|
||||
.output {
|
||||
background: rgba(0, 0, 0, .6);
|
||||
padding: 20px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid rgba(0, 242, 255, .2);
|
||||
max-height: 500px;
|
||||
overflow-y: auto;
|
||||
display: none;
|
||||
}
|
||||
.output.active {
|
||||
display: block;
|
||||
}
|
||||
pre {
|
||||
color: #00f2ff;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: .85rem;
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
.copy-btn {
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>WBF ↔ C Header Converter</h1>
|
||||
|
||||
<div class="mode-selector">
|
||||
<button class="mode-btn active" onclick="switchMode('wbf-to-header')">WBF → C Header</button>
|
||||
<button class="mode-btn" onclick="switchMode('header-to-wbf')">C Header → WBF</button>
|
||||
</div>
|
||||
|
||||
<!-- WBF to Header Mode -->
|
||||
<div id="wbf-to-header" class="controls active">
|
||||
<div class="info">
|
||||
Load a WLED Bitmap Font (.wbf) file and convert it to a C/C++ header file.
|
||||
</div>
|
||||
|
||||
<label>Select WBF Font File</label>
|
||||
<label for="wbfFile" class="file-label" id="wbfFileLabel">Choose .wbf file</label>
|
||||
<input type="file" id="wbfFile" accept=".wbf">
|
||||
|
||||
<label>Array Name</label>
|
||||
<input type="text" id="arrayName" placeholder="console_font_4x6" value="console_font_4x6">
|
||||
|
||||
<button id="convertToHeaderBtn" disabled>Convert to Header</button>
|
||||
</div>
|
||||
|
||||
<!-- Header to WBF Mode -->
|
||||
<div id="header-to-wbf" class="controls">
|
||||
<div class="info">
|
||||
Paste a C/C++ header file containing a WLED font array and convert it to a .wbf file.
|
||||
</div>
|
||||
|
||||
<label>Paste C Header Code</label>
|
||||
<textarea id="headerInput" placeholder="Paste your C header code here (e.g., static const unsigned char font[] PROGMEM = {...};)"></textarea>
|
||||
|
||||
<label>Output Filename (without .wbf extension)</label>
|
||||
<input type="text" id="wbfFilename" placeholder="console_font_4x6" value="console_font_4x6">
|
||||
|
||||
<button id="convertToWbfBtn" disabled>Convert to WBF</button>
|
||||
</div>
|
||||
|
||||
<div id="output" class="output">
|
||||
<pre id="outputCode"></pre>
|
||||
<button class="copy-btn" onclick="copyToClipboard(event)">Copy to Clipboard</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Elements for WBF to Header
|
||||
const wbfFileInput = document.getElementById('wbfFile');
|
||||
const wbfFileLabel = document.getElementById('wbfFileLabel');
|
||||
const arrayNameInput = document.getElementById('arrayName');
|
||||
const convertToHeaderBtn = document.getElementById('convertToHeaderBtn');
|
||||
|
||||
// Elements for Header to WBF
|
||||
const headerInput = document.getElementById('headerInput');
|
||||
const wbfFilenameInput = document.getElementById('wbfFilename');
|
||||
const convertToWbfBtn = document.getElementById('convertToWbfBtn');
|
||||
|
||||
// Output elements
|
||||
const output = document.getElementById('output');
|
||||
const outputCode = document.getElementById('outputCode');
|
||||
|
||||
let wbfData = null;
|
||||
let fileName = '';
|
||||
|
||||
// Mode switching
|
||||
function switchMode(mode) {
|
||||
document.querySelectorAll('.mode-btn').forEach(btn => btn.classList.remove('active'));
|
||||
document.querySelectorAll('.controls').forEach(ctrl => ctrl.classList.remove('active'));
|
||||
|
||||
event.target.classList.add('active');
|
||||
document.getElementById(mode).classList.add('active');
|
||||
output.classList.remove('active');
|
||||
}
|
||||
|
||||
// ==================== WBF to Header ====================
|
||||
wbfFileInput.addEventListener('change', (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (file) {
|
||||
fileName = file.name.replace(/\.[^.]+$/, '');
|
||||
wbfFileLabel.textContent = file.name;
|
||||
wbfFileLabel.classList.add('has-file');
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (ev) => {
|
||||
wbfData = new Uint8Array(ev.target.result);
|
||||
convertToHeaderBtn.disabled = false;
|
||||
};
|
||||
reader.readAsArrayBuffer(file);
|
||||
}
|
||||
});
|
||||
|
||||
convertToHeaderBtn.addEventListener('click', () => {
|
||||
if (!wbfData) return;
|
||||
|
||||
const header = parseWBF(wbfData);
|
||||
if (header) {
|
||||
generateHeader(header);
|
||||
}
|
||||
});
|
||||
|
||||
function parseWBF(data) {
|
||||
if (data.length < 12) {
|
||||
alert('Invalid WBF file: too short');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Parse header
|
||||
if (data[0] !== 0x57) { // 'W'
|
||||
alert('Invalid WBF file: missing magic byte');
|
||||
return null;
|
||||
}
|
||||
|
||||
const height = data[1];
|
||||
const maxWidth = data[2];
|
||||
const spacing = data[3];
|
||||
const flags = data[4];
|
||||
const first = data[5];
|
||||
const last = data[6];
|
||||
const reserved = data[7];
|
||||
|
||||
// Unicode offset is 32-bit little-endian
|
||||
const unicodeOffset = data[8] | (data[9] << 8) | (data[10] << 16) | (data[11] << 24);
|
||||
|
||||
const numChars = last - first + 1;
|
||||
const isVariableWidth = (flags & 0x01) !== 0;
|
||||
|
||||
let offset = 12; // Start after header
|
||||
let widthTable = null;
|
||||
|
||||
// If variable width, read width table
|
||||
if (isVariableWidth) {
|
||||
if (data.length < 12 + numChars) {
|
||||
alert('Invalid WBF file: missing width table');
|
||||
return null;
|
||||
}
|
||||
widthTable = Array.from(data.slice(12, 12 + numChars));
|
||||
offset = 12 + numChars;
|
||||
}
|
||||
|
||||
// Calculate expected data size
|
||||
let expectedDataSize = 0;
|
||||
if (isVariableWidth) {
|
||||
for (let w of widthTable) {
|
||||
expectedDataSize += Math.ceil((w * height) / 8);
|
||||
}
|
||||
} else {
|
||||
expectedDataSize = numChars * Math.ceil((maxWidth * height) / 8);
|
||||
}
|
||||
|
||||
if (data.length < offset + expectedDataSize) {
|
||||
alert(`Invalid WBF file: expected ${offset + expectedDataSize} bytes, got ${data.length}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
height,
|
||||
maxWidth,
|
||||
spacing,
|
||||
flags,
|
||||
first,
|
||||
last,
|
||||
reserved,
|
||||
unicodeOffset,
|
||||
data: data,
|
||||
isVariableWidth,
|
||||
widthTable,
|
||||
dataOffset: offset
|
||||
};
|
||||
}
|
||||
|
||||
function generateHeader(header) {
|
||||
const arrayName = arrayNameInput.value || 'console_font';
|
||||
let code = '';
|
||||
|
||||
// Header comment
|
||||
code += `// Font: ${fileName}\n`;
|
||||
code += `// Height: ${header.height}, Max Width: ${header.maxWidth}, Spacing: ${header.spacing}\n`;
|
||||
code += `// Characters: ${header.first}-${header.last} (${header.last - header.first + 1} glyphs)\n`;
|
||||
code += `// Unicode Offset: 0x${header.unicodeOffset.toString(16).padStart(8, '0').toUpperCase()}\n`;
|
||||
code += `// Variable Width: ${header.isVariableWidth ? 'Yes' : 'No'}\n\n`;
|
||||
|
||||
// Array declaration
|
||||
code += `static const unsigned char ${arrayName}[] PROGMEM = {\n`;
|
||||
|
||||
// Header bytes (12 bytes)
|
||||
code += ' ';
|
||||
code += `0x${header.data[0].toString(16).padStart(2, '0').toUpperCase()}, `; // Magic 'W'
|
||||
code += `0x${header.height.toString(16).padStart(2, '0').toUpperCase()}, `; // Height
|
||||
code += `0x${header.maxWidth.toString(16).padStart(2, '0').toUpperCase()}, `; // Max Width
|
||||
code += `0x${header.spacing.toString(16).padStart(2, '0').toUpperCase()}, `; // Spacing
|
||||
code += `0x${header.flags.toString(16).padStart(2, '0').toUpperCase()}, `; // Flags
|
||||
code += `0x${header.first.toString(16).padStart(2, '0').toUpperCase()}, `; // First char
|
||||
code += `0x${header.last.toString(16).padStart(2, '0').toUpperCase()}, `; // Last char
|
||||
code += `0x${header.reserved.toString(16).padStart(2, '0').toUpperCase()}, `; // Reserved
|
||||
|
||||
// Unicode offset (4 bytes, little-endian)
|
||||
code += `0x${header.data[8].toString(16).padStart(2, '0').toUpperCase()}, `;
|
||||
code += `0x${header.data[9].toString(16).padStart(2, '0').toUpperCase()}, `;
|
||||
code += `0x${header.data[10].toString(16).padStart(2, '0').toUpperCase()}, `;
|
||||
code += `0x${header.data[11].toString(16).padStart(2, '0').toUpperCase()}`;
|
||||
|
||||
code += ', // Header: \'W\', H, W, S, Flags, First, Last, Reserved, UnicodeOffset (32bit)\n\n';
|
||||
|
||||
// Width table (if variable width)
|
||||
if (header.isVariableWidth) {
|
||||
code += ' // Width table\n';
|
||||
const numChars = header.last - header.first + 1;
|
||||
for (let i = 0; i < numChars; i++) {
|
||||
if (i % 16 === 0) {
|
||||
if (i > 0) code += '\n';
|
||||
code += ' ';
|
||||
}
|
||||
code += `0x${header.widthTable[i].toString(16).padStart(2, '0').toUpperCase()}`;
|
||||
if (i < numChars - 1) {
|
||||
code += ', ';
|
||||
}
|
||||
}
|
||||
code += ',\n\n';
|
||||
}
|
||||
|
||||
// Character data
|
||||
const numChars = header.last - header.first + 1;
|
||||
let offset = header.dataOffset;
|
||||
|
||||
// First pass: calculate max byte width for alignment
|
||||
let maxByteWidth = 0;
|
||||
let tempOffset = header.dataOffset;
|
||||
for (let i = 0; i < numChars; i++) {
|
||||
const charWidth = header.isVariableWidth ? header.widthTable[i] : header.maxWidth;
|
||||
const bytesPerChar = Math.ceil((charWidth * header.height) / 8);
|
||||
const byteStr = Array(bytesPerChar).fill('0x00').join(', ');
|
||||
maxByteWidth = Math.max(maxByteWidth, byteStr.length);
|
||||
tempOffset += bytesPerChar;
|
||||
}
|
||||
|
||||
// Second pass: generate output with aligned comments
|
||||
for (let i = 0; i < numChars; i++) {
|
||||
const charCode = header.first + i;
|
||||
const charStr = getAsciiString(charCode);
|
||||
|
||||
// Calculate bytes for this character
|
||||
const charWidth = header.isVariableWidth ? header.widthTable[i] : header.maxWidth;
|
||||
const bytesPerChar = Math.ceil((charWidth * header.height) / 8);
|
||||
|
||||
code += ' ';
|
||||
let byteStr = '';
|
||||
for (let b = 0; b < bytesPerChar; b++) {
|
||||
const byte = header.data[offset++];
|
||||
byteStr += `0x${byte.toString(16).padStart(2, '0').toUpperCase()}`;
|
||||
if (b < bytesPerChar - 1) {
|
||||
byteStr += ', ';
|
||||
}
|
||||
}
|
||||
code += byteStr;
|
||||
code += ',';
|
||||
|
||||
// Pad to align comments
|
||||
const padding = ' '.repeat(maxByteWidth - byteStr.length + 5);
|
||||
|
||||
const widthInfo = header.isVariableWidth ? `, w=${charWidth}` : '';
|
||||
code += `${padding}/* code=${charCode}, hex=0x${charCode.toString(16).padStart(2, '0').toUpperCase()}, ascii="${charStr}"${widthInfo} */\n`;
|
||||
}
|
||||
|
||||
code += '};\n';
|
||||
|
||||
// Display output
|
||||
outputCode.textContent = code;
|
||||
output.classList.add('active');
|
||||
}
|
||||
|
||||
// ==================== Header to WBF ====================
|
||||
headerInput.addEventListener('input', () => {
|
||||
convertToWbfBtn.disabled = headerInput.value.trim().length === 0;
|
||||
});
|
||||
|
||||
convertToWbfBtn.addEventListener('click', () => {
|
||||
const headerText = headerInput.value.trim();
|
||||
if (!headerText) return;
|
||||
|
||||
const wbfData = parseHeaderToWBF(headerText);
|
||||
if (wbfData) {
|
||||
downloadWBF(wbfData);
|
||||
}
|
||||
});
|
||||
|
||||
function parseHeaderToWBF(headerText) {
|
||||
try {
|
||||
// Properly remove C-style comments
|
||||
let cleanedText = removeComments(headerText);
|
||||
|
||||
// Extract all hex values from the cleaned text
|
||||
const hexPattern = /0x[0-9a-fA-F]{2}/g;
|
||||
const hexValues = cleanedText.match(hexPattern);
|
||||
|
||||
if (!hexValues || hexValues.length < 12) {
|
||||
alert('Invalid header: Could not find enough hex values (need at least 12 for header)\nFound: ' + (hexValues ? hexValues.length : 0) + ' bytes');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Convert hex strings to bytes
|
||||
const allBytes = hexValues.map(hex => parseInt(hex, 16));
|
||||
|
||||
// Parse the header (first 12 bytes)
|
||||
const height = allBytes[1];
|
||||
const maxWidth = allBytes[2];
|
||||
const spacing = allBytes[3];
|
||||
const flags = allBytes[4];
|
||||
const first = allBytes[5];
|
||||
const last = allBytes[6];
|
||||
const reserved = allBytes[7];
|
||||
const unicodeOffset = allBytes[8] | (allBytes[9] << 8) | (allBytes[10] << 16) | (allBytes[11] << 24);
|
||||
|
||||
// Validate magic byte
|
||||
if (allBytes[0] !== 0x57) {
|
||||
alert('Invalid header: First byte should be 0x57 (magic \'W\'), found 0x' + allBytes[0].toString(16).padStart(2, '0').toUpperCase());
|
||||
return null;
|
||||
}
|
||||
|
||||
const numChars = last - first + 1;
|
||||
const isVariableWidth = (flags & 0x01) !== 0;
|
||||
|
||||
// Now we need to separate header, width table (if present), and bitmap data
|
||||
let dataStartIndex = 12; // After the 12-byte header
|
||||
let widthTable = null;
|
||||
|
||||
if (isVariableWidth) {
|
||||
// Extract width table
|
||||
widthTable = allBytes.slice(dataStartIndex, dataStartIndex + numChars);
|
||||
dataStartIndex += numChars;
|
||||
}
|
||||
|
||||
// Calculate expected bitmap data size
|
||||
let expectedBitmapSize = 0;
|
||||
if (isVariableWidth) {
|
||||
for (let w of widthTable) {
|
||||
expectedBitmapSize += Math.ceil((w * height) / 8);
|
||||
}
|
||||
} else {
|
||||
expectedBitmapSize = numChars * Math.ceil((maxWidth * height) / 8);
|
||||
}
|
||||
|
||||
// Extract bitmap data
|
||||
const bitmapData = allBytes.slice(dataStartIndex, dataStartIndex + expectedBitmapSize);
|
||||
|
||||
// Validate we have all the data
|
||||
const totalExpected = dataStartIndex + expectedBitmapSize;
|
||||
if (allBytes.length < totalExpected) {
|
||||
alert(`Invalid header: Expected at least ${totalExpected} bytes, found ${allBytes.length}\n\n` +
|
||||
`Header shows: ${numChars} characters from ${first} to ${last}\n` +
|
||||
`${isVariableWidth ? 'Variable width font' : 'Fixed width font'}\n` +
|
||||
`Height: ${height}, Max Width: ${maxWidth}\n` +
|
||||
`Expected bitmap size: ${expectedBitmapSize} bytes`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Reconstruct the WBF file
|
||||
let wbfSize = 12; // Header
|
||||
if (isVariableWidth) {
|
||||
wbfSize += numChars; // Width table
|
||||
}
|
||||
wbfSize += expectedBitmapSize; // Bitmap data
|
||||
|
||||
const wbfData = new Uint8Array(wbfSize);
|
||||
let offset = 0;
|
||||
|
||||
// Write header
|
||||
wbfData[offset++] = 0x57; // Magic 'W'
|
||||
wbfData[offset++] = height;
|
||||
wbfData[offset++] = maxWidth;
|
||||
wbfData[offset++] = spacing;
|
||||
wbfData[offset++] = flags;
|
||||
wbfData[offset++] = first;
|
||||
wbfData[offset++] = last;
|
||||
wbfData[offset++] = reserved;
|
||||
wbfData[offset++] = unicodeOffset & 0xFF;
|
||||
wbfData[offset++] = (unicodeOffset >> 8) & 0xFF;
|
||||
wbfData[offset++] = (unicodeOffset >> 16) & 0xFF;
|
||||
wbfData[offset++] = (unicodeOffset >> 24) & 0xFF;
|
||||
|
||||
// Write width table if variable width
|
||||
if (isVariableWidth) {
|
||||
for (let w of widthTable) {
|
||||
wbfData[offset++] = w;
|
||||
}
|
||||
}
|
||||
|
||||
// Write bitmap data
|
||||
for (let byte of bitmapData) {
|
||||
wbfData[offset++] = byte;
|
||||
}
|
||||
|
||||
// Show success message
|
||||
outputCode.textContent = `Successfully parsed header!\n\n` +
|
||||
`Height: ${height}\n` +
|
||||
`Max Width: ${maxWidth}\n` +
|
||||
`Spacing: ${spacing}\n` +
|
||||
`Flags: 0x${flags.toString(16).padStart(2, '0').toUpperCase()} (${isVariableWidth ? 'Variable Width' : 'Fixed Width'})\n` +
|
||||
`Characters: ${first}-${last} (${numChars} glyphs)\n` +
|
||||
`Unicode Offset: 0x${unicodeOffset.toString(16).padStart(8, '0').toUpperCase()}\n` +
|
||||
`Total Size: ${wbfData.length} bytes\n` +
|
||||
` Header: 12 bytes\n` +
|
||||
(isVariableWidth ? ` Width table: ${numChars} bytes\n` : '') +
|
||||
` Bitmap data: ${expectedBitmapSize} bytes\n` +
|
||||
`Parsed ${allBytes.length} total hex values\n\n` +
|
||||
`Your .wbf file is ready to download!`;
|
||||
output.classList.add('active');
|
||||
|
||||
return wbfData;
|
||||
} catch (error) {
|
||||
alert('Error parsing header: ' + error.message);
|
||||
console.error('Parse error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Proper C-style comment removal
|
||||
function removeComments(code) {
|
||||
let result = '';
|
||||
let i = 0;
|
||||
|
||||
while (i < code.length) {
|
||||
// Check for // comment (single-line)
|
||||
if (code[i] === '/' && code[i + 1] === '/') {
|
||||
// Skip until end of line
|
||||
i += 2;
|
||||
while (i < code.length && code[i] !== '\n') {
|
||||
i++;
|
||||
}
|
||||
// Keep the newline
|
||||
if (i < code.length) {
|
||||
result += '\n';
|
||||
i++;
|
||||
}
|
||||
}
|
||||
// Check for /* comment (multi-line)
|
||||
else if (code[i] === '/' && code[i + 1] === '*') {
|
||||
// Skip until we find */
|
||||
i += 2;
|
||||
while (i < code.length - 1) {
|
||||
if (code[i] === '*' && code[i + 1] === '/') {
|
||||
i += 2;
|
||||
break;
|
||||
}
|
||||
// Preserve newlines in multi-line comments (for line counting if needed)
|
||||
if (code[i] === '\n') {
|
||||
result += '\n';
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
// Regular character
|
||||
else {
|
||||
result += code[i];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function downloadWBF(data) {
|
||||
const filename = wbfFilenameInput.value.trim() || 'font';
|
||||
const blob = new Blob([data], { type: 'application/octet-stream' });
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = `${filename}.wbf`;
|
||||
a.click();
|
||||
}
|
||||
|
||||
// ==================== Utility Functions ====================
|
||||
function getAsciiString(code) {
|
||||
if (code < 32) {
|
||||
// Control characters
|
||||
return '^' + String.fromCharCode(64 + code);
|
||||
} else if (code === 127) {
|
||||
return '^?';
|
||||
} else if (code >= 32 && code <= 126) {
|
||||
// Printable ASCII
|
||||
return String.fromCharCode(code);
|
||||
} else {
|
||||
// Extended ASCII
|
||||
return '\\x' + code.toString(16).padStart(2, '0');
|
||||
}
|
||||
}
|
||||
|
||||
function copyToClipboard(event) {
|
||||
const text = outputCode.textContent;
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
const btn = event.target;
|
||||
const originalText = btn.textContent;
|
||||
btn.textContent = 'Copied!';
|
||||
setTimeout(() => {
|
||||
btn.textContent = originalText;
|
||||
}, 2000);
|
||||
}).catch(err => {
|
||||
console.error('Clipboard error:', err);
|
||||
// Fallback method for older browsers
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = text;
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.opacity = '0';
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
const btn = event.target;
|
||||
const originalText = btn.textContent;
|
||||
btn.textContent = 'Copied!';
|
||||
setTimeout(() => {
|
||||
btn.textContent = originalText;
|
||||
}, 2000);
|
||||
} catch (e) {
|
||||
alert('Failed to copy to clipboard: ' + e.message);
|
||||
}
|
||||
document.body.removeChild(textarea);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -3,7 +3,6 @@
|
||||
/*
|
||||
* Usermod for analog clock
|
||||
*/
|
||||
extern Timezone* tz;
|
||||
|
||||
class AnalogClockUsermod : public Usermod {
|
||||
private:
|
||||
@@ -116,7 +115,7 @@ private:
|
||||
);
|
||||
}
|
||||
|
||||
static inline uint32_t scale32(uint32_t c, fract8 scale) {
|
||||
static inline uint32_t scale32(uint32_t c, uint8_t scale) {
|
||||
return RGBW32(
|
||||
scale8(R(c), scale),
|
||||
scale8(G(c), scale),
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
#include "wled.h"
|
||||
#include "FXparticleSystem.h"
|
||||
|
||||
unsigned long nextCometCreationTime = 0;
|
||||
|
||||
#define FX_FALLBACK_STATIC { SEGMENT.fill(SEGCOLOR(0)); return; }
|
||||
// Use UINT32_MAX - 1 for the "no comet" case so we can add 1 later and not have it overflow
|
||||
#define NULL_INDEX UINT32_MAX - 1
|
||||
|
||||
///////////////////////
|
||||
// Effect Function //
|
||||
///////////////////////
|
||||
|
||||
void mode_pscomet() {
|
||||
ParticleSystem2D *PartSys = nullptr;
|
||||
uint32_t i;
|
||||
|
||||
if (SEGMENT.call == 0) { // Initialization
|
||||
// Try to allocate one comet for every column
|
||||
if (!initParticleSystem2D(PartSys, SEGMENT.vWidth())) {
|
||||
FX_FALLBACK_STATIC; // Allocation failed or not 2D
|
||||
}
|
||||
PartSys->setMotionBlur(170); // Enable motion blur
|
||||
PartSys->setParticleSize(0); // Allow small comets to be a single pixel wide
|
||||
}
|
||||
else {
|
||||
PartSys = reinterpret_cast<ParticleSystem2D *>(SEGENV.data); // If not first call, use existing data
|
||||
}
|
||||
if (PartSys == nullptr || SEGMENT.vHeight() < 2 || SEGMENT.vWidth() < 2) {
|
||||
FX_FALLBACK_STATIC;
|
||||
}
|
||||
|
||||
PartSys->updateSystem(); // Update system properties (dimensions and data pointers)
|
||||
|
||||
auto has_fallen_off_screen = [PartSys](uint32_t particleIndex) {
|
||||
return particleIndex < PartSys->numSources
|
||||
? PartSys->sources[particleIndex].source.y < PartSys->maxY * -1
|
||||
: true;
|
||||
};
|
||||
|
||||
// This will be SEGMENT.vWidth() unless the particle system had insufficient memory
|
||||
uint32_t numComets = PartSys->numSources;
|
||||
// Pick a random column for a new comet to spawn, but reset it to null if it's not time yet or there's already a
|
||||
// comet nearby
|
||||
uint32_t chosenIndex = hw_random(numComets);
|
||||
if (
|
||||
strip.now < nextCometCreationTime
|
||||
|| !has_fallen_off_screen(chosenIndex - 1)
|
||||
|| !has_fallen_off_screen(chosenIndex)
|
||||
|| !has_fallen_off_screen(chosenIndex + 1)
|
||||
) {
|
||||
chosenIndex = NULL_INDEX;
|
||||
} else {
|
||||
uint16_t cometFrequencyDelay = 2040 - (SEGMENT.intensity << 3);
|
||||
nextCometCreationTime = strip.now + cometFrequencyDelay + hw_random16(cometFrequencyDelay);
|
||||
}
|
||||
uint8_t canLargeCometSpawn =
|
||||
// Slider 3 determines % of large comets with extra particle sources on their sides
|
||||
SEGMENT.custom1 > hw_random8(254)
|
||||
&& chosenIndex != 0
|
||||
&& chosenIndex != numComets - 1;
|
||||
uint8_t fallingSpeed = 1 + (SEGMENT.speed >> 2);
|
||||
|
||||
// Update the comets
|
||||
for (i = 0; i < numComets; i++) {
|
||||
auto& source = PartSys->sources[i];
|
||||
auto& sourceParticle = source.source;
|
||||
|
||||
if (!has_fallen_off_screen(i)) {
|
||||
// Active comets fall downwards and emit flames
|
||||
sourceParticle.y -= fallingSpeed;
|
||||
source.vy = (SEGMENT.speed >> 5) - fallingSpeed; // Emitting speed (upwards)
|
||||
PartSys->flameEmit(PartSys->sources[i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
bool isChosenComet = i == chosenIndex;
|
||||
bool isChosenSideComet =
|
||||
canLargeCometSpawn &&
|
||||
(i == chosenIndex - 1 || i == chosenIndex + 1);
|
||||
|
||||
// Chosen comets respawn at the top
|
||||
if (isChosenComet || isChosenSideComet) {
|
||||
// Map the comet index into an output pixel index
|
||||
sourceParticle.x = i * PartSys->maxX / (SEGMENT.vWidth() - 1);
|
||||
// Spawn a bit above the top to avoid popping into view
|
||||
sourceParticle.y = PartSys->maxY + (2 * fallingSpeed);
|
||||
if (isChosenComet) {
|
||||
// Slider 4 controls comet length via particle lifetime and fire intensity adjustments
|
||||
source.maxLife = 16 + (SEGMENT.custom2 >> 2);
|
||||
source.minLife = source.maxLife >> 1;
|
||||
sourceParticle.ttl = 16 - (SEGMENT.custom2 >> 4);
|
||||
} else {
|
||||
// Side comets have fixed length
|
||||
source.maxLife = 18;
|
||||
source.minLife = 14;
|
||||
sourceParticle.ttl = 16;
|
||||
// Shift side comets up by 1 pixel
|
||||
sourceParticle.y += 2 * PartSys->maxY / (SEGMENT.vHeight() - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Slider 4 controls comet length via particle lifetime and fire intensity adjustments
|
||||
PartSys->updateFire(max(255U - SEGMENT.custom2, 45U));
|
||||
}
|
||||
static const char _data_FX_MODE_PSCOMET[] PROGMEM = "PS Comet@Falling Speed,Comet Frequency,Large Comet Probability,Comet Length;;!;2;pal=35,sx=128,ix=255,c1=32,c2=128";
|
||||
|
||||
/////////////////////
|
||||
// UserMod Class //
|
||||
/////////////////////
|
||||
|
||||
class PSCometUsermod : public Usermod {
|
||||
public:
|
||||
void setup() override {
|
||||
strip.addEffect(255, &mode_pscomet, _data_FX_MODE_PSCOMET);
|
||||
}
|
||||
|
||||
void loop() override {}
|
||||
};
|
||||
|
||||
static PSCometUsermod ps_comet;
|
||||
REGISTER_USERMOD(ps_comet);
|
||||
@@ -0,0 +1,25 @@
|
||||
## Description
|
||||
|
||||
A 2D falling comet effect similar to "Matrix" but with a fire particle simulation to enhance the comet trail visuals. Works with custom color palettes, defaulting to "Fire". Supports "small" and "large" comets which are 1px and 3px wide respectively.
|
||||
|
||||
Demo: [https://imgur.com/a/i1v5WAy](https://imgur.com/a/i1v5WAy)
|
||||
|
||||
## Installation
|
||||
|
||||
To activate the usermod, add the following line to your platformio_override.ini
|
||||
```ini
|
||||
custom_usermods = ps_comet
|
||||
```
|
||||
Or if you are already using a usermod, append ps_comet to the list
|
||||
```ini
|
||||
custom_usermods = audioreactive ps_comet
|
||||
```
|
||||
|
||||
You should now see "PS Comet" appear in your effect list.
|
||||
|
||||
## Parameters
|
||||
|
||||
1. **Falling Speed** sets how fast the comets fall
|
||||
2. **Comet Frequency** determines how many comets are on screen at a time
|
||||
3. **Large Comet Probability** determines how often large 3px wide comets spawn
|
||||
4. **Comet Length** sets how far comet trails stretch vertically
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"name": "PS Comet",
|
||||
"build": { "libArchive": false }
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#include "UsermodTemperature.h"
|
||||
|
||||
static uint16_t mode_temperature();
|
||||
static void mode_temperature();
|
||||
|
||||
//Dallas sensor quick (& dirty) reading. Credit to - Author: Peter Scargill, August 17th, 2013
|
||||
float UsermodTemperature::readDallas() {
|
||||
@@ -369,13 +369,12 @@ const char UsermodTemperature::_temperature[] PROGMEM = "temperature";
|
||||
const char UsermodTemperature::_Temperature[] PROGMEM = "/temperature";
|
||||
const char UsermodTemperature::_data_fx[] PROGMEM = "Temperature@Min,Max;;!;01;pal=54,sx=255,ix=0";
|
||||
|
||||
static uint16_t mode_temperature() {
|
||||
static void mode_temperature() {
|
||||
float low = roundf(mapf((float)SEGMENT.speed, 0.f, 255.f, -150.f, 150.f)); // default: 15°C, range: -15°C to 15°C
|
||||
float high = roundf(mapf((float)SEGMENT.intensity, 0.f, 255.f, 300.f, 600.f)); // default: 30°C, range 30°C to 60°C
|
||||
float temp = constrain(UsermodTemperature::getInstance()->getTemperatureC()*10.f, low, high); // get a little better resolution (*10)
|
||||
unsigned i = map(roundf(temp), (unsigned)low, (unsigned)high, 0, 248);
|
||||
SEGMENT.fill(SEGMENT.color_from_palette(i, false, false, 255));
|
||||
return FRAMETIME;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -5,9 +5,12 @@
|
||||
#include "tetrisaigame.h"
|
||||
// By: muebau
|
||||
|
||||
bool noFlashOnClear = false;
|
||||
|
||||
typedef struct TetrisAI_data
|
||||
{
|
||||
unsigned long lastTime = 0;
|
||||
unsigned long clearingStartTime = 0;
|
||||
TetrisAIGame tetris;
|
||||
uint8_t intelligence;
|
||||
uint8_t rotate;
|
||||
@@ -31,16 +34,27 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
//GRID
|
||||
for (auto index_y = 4; index_y < tetris->grid.height; index_y++)
|
||||
{
|
||||
bool isRowClearing = tetris->grid.gridBW.clearingRows[index_y];
|
||||
for (auto index_x = 0; index_x < tetris->grid.width; index_x++)
|
||||
{
|
||||
CRGB color;
|
||||
if (*tetris->grid.getPixel(index_x, index_y) == 0)
|
||||
{
|
||||
uint8_t gridPixel = *tetris->grid.getPixel(index_x, index_y);
|
||||
if (isRowClearing) {
|
||||
if (noFlashOnClear) {
|
||||
color = CRGB::Gray;
|
||||
} else {
|
||||
//flash color white and black every 200ms
|
||||
color = (strip.now % 200) < 150
|
||||
? CRGB::Gray
|
||||
: CRGB::Black;
|
||||
}
|
||||
}
|
||||
else if (gridPixel == 0) {
|
||||
//BG color
|
||||
color = SEGCOLOR(1);
|
||||
}
|
||||
//game over animation
|
||||
else if(*tetris->grid.getPixel(index_x, index_y) == 254)
|
||||
else if (gridPixel == 254)
|
||||
{
|
||||
//use fg
|
||||
color = SEGCOLOR(0);
|
||||
@@ -48,7 +62,7 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
else
|
||||
{
|
||||
//spread the color over the whole palette
|
||||
uint8_t colorIndex = *tetris->grid.getPixel(index_x, index_y) * 32;
|
||||
uint8_t colorIndex = gridPixel * 32;
|
||||
colorIndex += tetrisai_data->colorOffset;
|
||||
color = ColorFromPalette(SEGPALETTE, colorIndex, 255, NOBLEND);
|
||||
}
|
||||
@@ -98,13 +112,13 @@ void drawGrid(TetrisAIGame* tetris, TetrisAI_data* tetrisai_data)
|
||||
////////////////////////////
|
||||
// 2D Tetris AI //
|
||||
////////////////////////////
|
||||
uint16_t mode_2DTetrisAI()
|
||||
void mode_2DTetrisAI()
|
||||
{
|
||||
if (!strip.isMatrix || !SEGENV.allocateData(sizeof(tetrisai_data)))
|
||||
{
|
||||
// not a 2D set-up
|
||||
SEGMENT.fill(SEGCOLOR(0));
|
||||
return 350;
|
||||
return;
|
||||
}
|
||||
TetrisAI_data* tetrisai_data = reinterpret_cast<TetrisAI_data*>(SEGENV.data);
|
||||
|
||||
@@ -170,6 +184,7 @@ uint16_t mode_2DTetrisAI()
|
||||
|
||||
tetrisai_data->tetris = TetrisAIGame(gridWidth, gridHeight, nLookAhead, piecesData, numPieces);
|
||||
tetrisai_data->tetris.state = TetrisAIGame::States::INIT;
|
||||
tetrisai_data->clearingStartTime = 0;
|
||||
SEGMENT.fill(SEGCOLOR(1));
|
||||
}
|
||||
|
||||
@@ -184,7 +199,21 @@ uint16_t mode_2DTetrisAI()
|
||||
tetrisai_data->tetris.ai.bumpiness = -0.184483f + dui;
|
||||
}
|
||||
|
||||
if (tetrisai_data->tetris.state == TetrisAIGame::ANIMATE_MOVE)
|
||||
//end line clearing flashing effect if needed
|
||||
if (tetrisai_data->tetris.grid.gridBW.hasClearingRows())
|
||||
{
|
||||
if (tetrisai_data->clearingStartTime == 0) {
|
||||
tetrisai_data->clearingStartTime = strip.now;
|
||||
}
|
||||
if (strip.now - tetrisai_data->clearingStartTime > 750)
|
||||
{
|
||||
tetrisai_data->tetris.grid.gridBW.clearedLinesReadyForRemoval = true;
|
||||
tetrisai_data->tetris.grid.cleanupFullLines();
|
||||
tetrisai_data->clearingStartTime = 0;
|
||||
}
|
||||
drawGrid(&tetrisai_data->tetris, tetrisai_data);
|
||||
}
|
||||
else if (tetrisai_data->tetris.state == TetrisAIGame::ANIMATE_MOVE)
|
||||
{
|
||||
|
||||
if (strip.now - tetrisai_data->lastTime > msDelayMove)
|
||||
@@ -222,8 +251,6 @@ uint16_t mode_2DTetrisAI()
|
||||
{
|
||||
tetrisai_data->tetris.poll();
|
||||
}
|
||||
|
||||
return FRAMETIME;
|
||||
} // mode_2DTetrisAI()
|
||||
static const char _data_FX_MODE_2DTETRISAI[] PROGMEM = "Tetris AI@!,Look ahead,Intelligence,Rotate color,Mistake free,Show next,Border,Mistakes;Game Over,!,Border;!;2;sx=127,ix=64,c1=255,c2=0,c3=31,o1=1,o2=1,o3=0,pal=11";
|
||||
|
||||
@@ -231,6 +258,7 @@ class TetrisAIUsermod : public Usermod
|
||||
{
|
||||
|
||||
private:
|
||||
static const char _name[];
|
||||
|
||||
public:
|
||||
void setup()
|
||||
@@ -238,6 +266,20 @@ public:
|
||||
strip.addEffect(255, &mode_2DTetrisAI, _data_FX_MODE_2DTETRISAI);
|
||||
}
|
||||
|
||||
void addToConfig(JsonObject& root) override
|
||||
{
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name));
|
||||
top["noFlashOnClear"] = noFlashOnClear;
|
||||
}
|
||||
|
||||
bool readFromConfig(JsonObject& root) override
|
||||
{
|
||||
JsonObject top = root[FPSTR(_name)];
|
||||
bool configComplete = !top.isNull();
|
||||
configComplete &= getJsonValue(top["noFlashOnClear"], noFlashOnClear);
|
||||
return configComplete;
|
||||
}
|
||||
|
||||
void loop()
|
||||
{
|
||||
|
||||
@@ -249,6 +291,7 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
const char TetrisAIUsermod::_name[] PROGMEM = "TetrisAI_v2";
|
||||
|
||||
static TetrisAIUsermod tetrisai_v2;
|
||||
REGISTER_USERMOD(tetrisai_v2);
|
||||
@@ -13,7 +13,6 @@
|
||||
#ifndef __GRIDBW_H__
|
||||
#define __GRIDBW_H__
|
||||
|
||||
#include <iterator>
|
||||
#include <vector>
|
||||
#include "pieces.h"
|
||||
|
||||
@@ -26,11 +25,18 @@ public:
|
||||
uint8_t width;
|
||||
uint8_t height;
|
||||
std::vector<uint32_t> pixels;
|
||||
// When a row fills, we mark it here first so it can flash before being
|
||||
// fully removed.
|
||||
std::vector<bool> clearingRows;
|
||||
// True when a line clearing flashing effect is over and we're ready to
|
||||
// fully clean up the lines
|
||||
bool clearedLinesReadyForRemoval = false;
|
||||
|
||||
GridBW(uint8_t width, uint8_t height):
|
||||
width(width),
|
||||
height(height),
|
||||
pixels(height)
|
||||
pixels(height),
|
||||
clearingRows(height)
|
||||
{
|
||||
if (width > 32)
|
||||
{
|
||||
@@ -85,9 +91,26 @@ public:
|
||||
piece->landingY = piece->landingY > 0 ? piece->landingY - 1 : 0;
|
||||
}
|
||||
|
||||
bool hasClearingRows()
|
||||
{
|
||||
for (bool rowClearing : clearingRows)
|
||||
{
|
||||
if (rowClearing)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void cleanupFullLines()
|
||||
{
|
||||
// Skip cleanup if there are rows clearing
|
||||
if (hasClearingRows() && !clearedLinesReadyForRemoval) {
|
||||
return;
|
||||
}
|
||||
uint8_t offset = 0;
|
||||
bool doneRemovingClearedLines = false;
|
||||
|
||||
//from "height - 1" to "0", so from bottom row to top
|
||||
for (uint8_t row = height; row-- > 0; )
|
||||
@@ -95,8 +118,13 @@ public:
|
||||
//full line?
|
||||
if (isLineFull(row))
|
||||
{
|
||||
offset++;
|
||||
pixels[row] = 0x0;
|
||||
if (clearedLinesReadyForRemoval) {
|
||||
offset++;
|
||||
pixels[row] = 0x0;
|
||||
doneRemovingClearedLines = true;
|
||||
} else {
|
||||
clearingRows[row] = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -106,11 +134,20 @@ public:
|
||||
pixels[row] = 0x0;
|
||||
}
|
||||
}
|
||||
if (doneRemovingClearedLines) {
|
||||
clearingRows.assign(height, false);
|
||||
clearedLinesReadyForRemoval = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool isLineFull(uint8_t y)
|
||||
{
|
||||
return pixels[y] == (uint32_t)((1 << width) - 1);
|
||||
return pixels[y] == (width >= 32 ? UINT32_MAX : (1U << width) - 1);
|
||||
}
|
||||
|
||||
bool isLineReadyForRemoval(uint8_t y)
|
||||
{
|
||||
return clearedLinesReadyForRemoval && isLineFull(y);
|
||||
}
|
||||
|
||||
void reset()
|
||||
@@ -122,6 +159,8 @@ public:
|
||||
|
||||
pixels.clear();
|
||||
pixels.resize(height);
|
||||
clearingRows.assign(height, false);
|
||||
clearedLinesReadyForRemoval = false;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ public:
|
||||
//from "height - 1" to "0", so from bottom row to top
|
||||
for (uint8_t y = height; y-- > 0; )
|
||||
{
|
||||
if (gridBW.isLineFull(y))
|
||||
if (gridBW.isLineReadyForRemoval(y))
|
||||
{
|
||||
offset++;
|
||||
for (uint8_t x = 0; x < width; x++)
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
#include <bitset>
|
||||
#include <cstddef>
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
|
||||
#define numPieces 7
|
||||
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
This usermod adds a self-playing Tetris game as an 'effect'. The mod requires version 0.14 or higher as it relies on matrix support. The effect was tested on an ESP32 4MB with a WS2812B 16x16 matrix.
|
||||
|
||||
Version 1.0
|
||||
PHOTOSENSITIVE EPILEPSY WARNING: By default the effect features a flashing animation on line clear. This can be disabled
|
||||
from the usermod settings page in WLED.
|
||||
|
||||
## Installation
|
||||
|
||||
Just activate the usermod with `-D USERMOD_TETRISAI` and the effect will become available under the name 'Tetris AI'. If you are running out of flash memory, use a different memory layout (e.g. [WLED_ESP32_4MB_256KB_FS.csv](https://github.com/wled-dev/WLED/blob/main/tools/WLED_ESP32_4MB_256KB_FS.csv)).
|
||||
To activate the usermod, add the following line to your platformio_override.ini
|
||||
`custom_usermods = tetrisai_v2`
|
||||
The effect will then become available under the name 'Tetris AI'. If you are running out of flash memory, use a different memory layout (e.g. [WLED_ESP32_4MB_256KB_FS.csv](https://github.com/wled-dev/WLED/blob/main/tools/WLED_ESP32_4MB_256KB_FS.csv)).
|
||||
|
||||
If needed simply add to `platformio_override.ini` (or `platformio_override.ini`):
|
||||
If needed simply add to `platformio_override.ini`:
|
||||
|
||||
```ini
|
||||
board_build.partitions = tools/WLED_ESP32_4MB_256KB_FS.csv
|
||||
|
||||
@@ -68,7 +68,7 @@ public:
|
||||
}
|
||||
|
||||
//line full if all ones in mask :-)
|
||||
if (grid.isLineFull(row))
|
||||
if (grid.isLineReadyForRemoval(row))
|
||||
{
|
||||
rating->fullLines++;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
|
||||
#include <stdint.h>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
#include "tetrisbag.h"
|
||||
|
||||
@@ -87,17 +86,12 @@ public:
|
||||
void queuePiece()
|
||||
{
|
||||
//move vector to left
|
||||
std::rotate(piecesQueue.begin(), piecesQueue.begin() + 1, piecesQueue.end());
|
||||
for (uint8_t i = 1; i < piecesQueue.size(); i++) {
|
||||
piecesQueue[i - 1] = piecesQueue[i];
|
||||
}
|
||||
piecesQueue[piecesQueue.size() - 1] = getNextPiece();
|
||||
}
|
||||
|
||||
void queuePiece(uint8_t idx)
|
||||
{
|
||||
//move vector to left
|
||||
std::rotate(piecesQueue.begin(), piecesQueue.begin() + 1, piecesQueue.end());
|
||||
piecesQueue[piecesQueue.size() - 1] = Piece(idx % nPieces);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
bag.clear();
|
||||
|
||||
@@ -20,6 +20,26 @@
|
||||
* ....
|
||||
*/
|
||||
|
||||
#define FFT_PREFER_EXACT_PEAKS // use Blackman-Harris FFT windowing instead of Flat Top -> results in "sharper" peaks and less "leaking" into other frequencies (credits to @softhack)
|
||||
|
||||
/*
|
||||
* Note on FFT variants:
|
||||
* - ArduinoFFT: uses floating point calculations, very slow on S2 and C3 (no FPU)
|
||||
* - ESP-IDF DSP library:
|
||||
- faster but uses ~13k of extra flash on ESP32 and S3
|
||||
* - uses integer math on S2 and C3: slightly less accurate but over 10x faster than ArduinoFFT and uses less flash
|
||||
- not available in IDF < 4.4
|
||||
* - ArduinoFFT is used by default on ESP32 and S3
|
||||
* - ESP-IDF DSP FFT with integer math is used by default on S2 and C3
|
||||
* - defines:
|
||||
* - UM_AUDIOREACTIVE_USE_ARDUINO_FFT: use ArduinoFFT library for FFT
|
||||
* - UM_AUDIOREACTIVE_USE_ESPDSP_FFT: use ESP-IDF DSP for FFT
|
||||
*/
|
||||
|
||||
//#define UM_AUDIOREACTIVE_USE_ESPDSP_FFT // default on S2 and C3
|
||||
//#define UM_AUDIOREACTIVE_USE_INTEGER_FFT // use integer FFT if using ESP-IDF DSP library, always used on S2 and C3 (UM_AUDIOREACTIVE_USE_ARDUINO_FFT takes priority)
|
||||
//#define UM_AUDIOREACTIVE_USE_ARDUINO_FFT // default on ESP32 and S3
|
||||
|
||||
#if !defined(FFTTASK_PRIORITY)
|
||||
#define FFTTASK_PRIORITY 1 // standard: looptask prio
|
||||
//#define FFTTASK_PRIORITY 2 // above looptask, below asyc_tcp
|
||||
@@ -99,6 +119,46 @@ static uint8_t maxVol = 31; // (was 10) Reasonable value for constant v
|
||||
static uint8_t binNum = 8; // Used to select the bin for FFT based beat detection (deprecated)
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#if !defined(UM_AUDIOREACTIVE_USE_ESPDSP_FFT) && (defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32))
|
||||
#define UM_AUDIOREACTIVE_USE_ARDUINO_FFT // use ArduinoFFT library for FFT instead of ESP-IDF DSP library by default on ESP32 and S3
|
||||
#endif
|
||||
|
||||
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 4, 0)
|
||||
#define UM_AUDIOREACTIVE_USE_ARDUINO_FFT // DSP FFT library is not available in ESP-IDF < 4.4
|
||||
#endif
|
||||
|
||||
#ifdef UM_AUDIOREACTIVE_USE_ARDUINO_FFT
|
||||
#include <arduinoFFT.h> // ArduinoFFT library for FFT and window functions
|
||||
#undef UM_AUDIOREACTIVE_USE_INTEGER_FFT // arduinoFFT has not integer support
|
||||
#else
|
||||
#include "dsps_fft2r.h" // ESP-IDF DSP library for FFT and window functions
|
||||
#ifdef FFT_PREFER_EXACT_PEAKS
|
||||
#include "dsps_wind_blackman_harris.h"
|
||||
#else
|
||||
#include "dsps_wind_flat_top.h"
|
||||
#endif
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
#define UM_AUDIOREACTIVE_USE_INTEGER_FFT // always use integer FFT on ESP32-S2 and ESP32-C3
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if !defined(UM_AUDIOREACTIVE_USE_INTEGER_FFT)
|
||||
using FFTsampleType = float;
|
||||
using FFTmathType = float;
|
||||
#define FFTabs fabsf
|
||||
#else
|
||||
using FFTsampleType = int16_t;
|
||||
using FFTmathType = int32_t;
|
||||
#define FFTabs abs
|
||||
#endif
|
||||
// These are the input and output vectors. Input vectors receive computed results from FFT.
|
||||
static FFTsampleType* valFFT = nullptr;
|
||||
#ifdef UM_AUDIOREACTIVE_USE_ARDUINO_FFT
|
||||
static float* vImag = nullptr; // imaginary part of FFT results
|
||||
#endif
|
||||
|
||||
// pre-computed window function
|
||||
static FFTsampleType* windowFFT = nullptr;
|
||||
|
||||
// use audio source class (ESP32 specific)
|
||||
#include "audio_source.h"
|
||||
@@ -108,14 +168,14 @@ constexpr int BLOCK_SIZE = 128; // I2S buffer size (samples)
|
||||
// globals
|
||||
static uint8_t inputLevel = 128; // UI slider value
|
||||
#ifndef SR_SQUELCH
|
||||
uint8_t soundSquelch = 10; // squelch value for volume reactive routines (config value)
|
||||
static uint8_t soundSquelch = 10; // squelch value for volume reactive routines (config value)
|
||||
#else
|
||||
uint8_t soundSquelch = SR_SQUELCH; // squelch value for volume reactive routines (config value)
|
||||
static uint8_t soundSquelch = SR_SQUELCH; // squelch value for volume reactive routines (config value)
|
||||
#endif
|
||||
#ifndef SR_GAIN
|
||||
uint8_t sampleGain = 60; // sample gain (config value)
|
||||
static uint8_t sampleGain = 60; // sample gain (config value)
|
||||
#else
|
||||
uint8_t sampleGain = SR_GAIN; // sample gain (config value)
|
||||
static uint8_t sampleGain = SR_GAIN; // sample gain (config value)
|
||||
#endif
|
||||
// user settable options for FFTResult scaling
|
||||
static uint8_t FFTScalingMode = 3; // 0 none; 1 optimized logarithmic; 2 optimized linear; 3 optimized square root
|
||||
@@ -140,8 +200,8 @@ const float agcSampleSmooth[AGC_NUM_PRESETS] = { 1/12.f, 1/6.f, 1/16.f}; //
|
||||
// AGC presets end
|
||||
|
||||
static AudioSource *audioSource = nullptr;
|
||||
static bool useBandPassFilter = false; // if true, enables a bandpass filter 80Hz-16Khz to remove noise. Applies before FFT.
|
||||
|
||||
static bool useBandPassFilter = false; // if true, enables a hard cutoff bandpass filter. Applies after FFT.
|
||||
static bool useMicFilter = false; // if true, enables a IIR bandpass filter 80Hz-20Khz to remove noise. Applies before FFT.
|
||||
////////////////////
|
||||
// Begin FFT Code //
|
||||
////////////////////
|
||||
@@ -149,7 +209,7 @@ static bool useBandPassFilter = false; // if true, enables a
|
||||
// some prototypes, to ensure consistent interfaces
|
||||
static float fftAddAvg(int from, int to); // average of several FFT result bins
|
||||
void FFTcode(void * parameter); // audio processing task: read samples, run FFT, fill GEQ channels from FFT results
|
||||
static void runMicFilter(uint16_t numSamples, float *sampleBuffer); // pre-filtering of raw samples (band-pass)
|
||||
static void runMicFilter(uint16_t numSamples, FFTsampleType *sampleBuffer);
|
||||
static void postProcessFFTResults(bool noiseGateOpen, int numberOfChannels); // post-processing and post-amp of GEQ channels
|
||||
|
||||
static TaskHandle_t FFT_Task = nullptr;
|
||||
@@ -185,13 +245,13 @@ constexpr uint16_t samplesFFT = 512; // Samples in an FFT batch - Thi
|
||||
constexpr uint16_t samplesFFT_2 = 256; // meaningfull part of FFT results - only the "lower half" contains useful information.
|
||||
// the following are observed values, supported by a bit of "educated guessing"
|
||||
//#define FFT_DOWNSCALE 0.65f // 20kHz - downscaling factor for FFT results - "Flat-Top" window @20Khz, old freq channels
|
||||
#ifdef FFT_PREFER_EXACT_PEAKS
|
||||
#define FFT_DOWNSCALE 0.40f // downscaling factor for FFT results, RMS averaging for "Blackman-Harris" Window @22kHz (credit to MM)
|
||||
#else
|
||||
#define FFT_DOWNSCALE 0.46f // downscaling factor for FFT results - for "Flat-Top" window @22Khz, new freq channels
|
||||
#endif
|
||||
#define LOG_256 5.54517744f // log(256)
|
||||
|
||||
// These are the input and output vectors. Input vectors receive computed results from FFT.
|
||||
static float* vReal = nullptr; // FFT sample inputs / freq output - these are our raw result bins
|
||||
static float* vImag = nullptr; // imaginary parts
|
||||
|
||||
// Create FFT object
|
||||
// lib_deps += https://github.com/kosme/arduinoFFT#develop @ 1.9.2
|
||||
// these options actually cause slow-downs on all esp32 processors, don't use them.
|
||||
@@ -200,16 +260,20 @@ static float* vImag = nullptr; // imaginary parts
|
||||
// Below options are forcing ArduinoFFT to use sqrtf() instead of sqrt()
|
||||
// #define sqrt_internal sqrtf // see https://github.com/kosme/arduinoFFT/pull/83 - since v2.0.0 this must be done in build_flags
|
||||
|
||||
#include <arduinoFFT.h> // FFT object is created in FFTcode
|
||||
// Helper functions
|
||||
|
||||
// compute average of several FFT result bins
|
||||
static float fftAddAvg(int from, int to) {
|
||||
float result = 0.0f;
|
||||
FFTmathType result = 0;
|
||||
for (int i = from; i <= to; i++) {
|
||||
result += vReal[i];
|
||||
result += valFFT[i];
|
||||
}
|
||||
return result / float(to - from + 1);
|
||||
#if !defined(UM_AUDIOREACTIVE_USE_INTEGER_FFT)
|
||||
result = result * 0.0625; // divide by 16 to reduce magnitude. Want end result to be scaled linear and ~4096 max.
|
||||
#else
|
||||
result *= 32; // scale result to match float values. note: raw scaling value between float and int is 512, float version is scaled down by 16
|
||||
#endif
|
||||
return float(result) / float(to - from + 1); // return average as float
|
||||
}
|
||||
|
||||
//
|
||||
@@ -218,18 +282,61 @@ static float fftAddAvg(int from, int to) {
|
||||
void FFTcode(void * parameter)
|
||||
{
|
||||
DEBUGSR_PRINT("FFT started on core: "); DEBUGSR_PRINTLN(xPortGetCoreID());
|
||||
|
||||
#ifdef UM_AUDIOREACTIVE_USE_ARDUINO_FFT
|
||||
// allocate FFT buffers on first call
|
||||
if (vReal == nullptr) vReal = (float*) calloc(samplesFFT, sizeof(float));
|
||||
if (vImag == nullptr) vImag = (float*) calloc(samplesFFT, sizeof(float));
|
||||
if ((vReal == nullptr) || (vImag == nullptr)) {
|
||||
if (valFFT == nullptr) valFFT = (float*) calloc(samplesFFT, sizeof(float));
|
||||
if (vImag == nullptr) vImag = (float*) calloc(samplesFFT, sizeof(float));
|
||||
if ((valFFT == nullptr) || (vImag == nullptr)) {
|
||||
// something went wrong
|
||||
if (vReal) free(vReal); vReal = nullptr;
|
||||
if (valFFT) free(valFFT); valFFT = nullptr;
|
||||
if (vImag) free(vImag); vImag = nullptr;
|
||||
return;
|
||||
}
|
||||
// Create FFT object with weighing factor storage
|
||||
ArduinoFFT<float> FFT = ArduinoFFT<float>( vReal, vImag, samplesFFT, SAMPLE_RATE, true);
|
||||
ArduinoFFT<float> FFT = ArduinoFFT<float>(valFFT, vImag, samplesFFT, SAMPLE_RATE, true);
|
||||
#elif !defined(UM_AUDIOREACTIVE_USE_INTEGER_FFT)
|
||||
// allocate and initialize FFT buffers on first call
|
||||
// note: free() is never used on these pointers. If it ever is implemented, this implementation can cause memory leaks (need to free raw pointers)
|
||||
if (valFFT == nullptr) {
|
||||
float* raw_buffer = (float*)heap_caps_malloc((2 * samplesFFT * sizeof(float)) + 16, MALLOC_CAP_8BIT);
|
||||
if ((raw_buffer == nullptr)) return; // something went wrong
|
||||
valFFT = (float*)(((uintptr_t)raw_buffer + 15) & ~15); // SIMD requires aligned memory to 16-byte boundary. note in IDF5 there is MALLOC_CAP_SIMD available
|
||||
}
|
||||
// create window
|
||||
if (windowFFT == nullptr) {
|
||||
float* raw_buffer = (float*)heap_caps_malloc((samplesFFT * sizeof(float)) + 16, MALLOC_CAP_8BIT);
|
||||
if ((raw_buffer == nullptr)) return; // something went wrong
|
||||
windowFFT = (float*)(((uintptr_t)raw_buffer + 15) & ~15); // SIMD requires aligned memory to 16-byte boundary
|
||||
}
|
||||
if (dsps_fft2r_init_fc32(NULL, samplesFFT) != ESP_OK) return; // initialize FFT tables
|
||||
// create window function for FFT
|
||||
#ifdef FFT_PREFER_EXACT_PEAKS
|
||||
dsps_wind_blackman_harris_f32(windowFFT, samplesFFT);
|
||||
#else
|
||||
dsps_wind_flat_top_f32(windowFFT, samplesFFT);
|
||||
#endif
|
||||
#else
|
||||
// allocate and initialize integer FFT buffers on first call
|
||||
if (valFFT == nullptr) valFFT = (int16_t*) calloc(sizeof(int16_t), samplesFFT * 2);
|
||||
if ((valFFT == nullptr)) return; // something went wrong
|
||||
// create window
|
||||
if (windowFFT == nullptr) windowFFT = (int16_t*) calloc(sizeof(int16_t), samplesFFT);
|
||||
if ((windowFFT == nullptr)) return; // something went wrong
|
||||
if (dsps_fft2r_init_sc16(NULL, samplesFFT) != ESP_OK) return; // initialize FFT tables
|
||||
// create window function for FFT
|
||||
float *windowFloat = (float*) calloc(sizeof(float), samplesFFT); // temporary buffer for window function
|
||||
if ((windowFloat == nullptr)) return; // something went wrong
|
||||
#ifdef FFT_PREFER_EXACT_PEAKS
|
||||
dsps_wind_blackman_harris_f32(windowFloat, samplesFFT);
|
||||
#else
|
||||
dsps_wind_flat_top_f32(windowFloat, samplesFFT);
|
||||
#endif
|
||||
// convert float window to 16-bit int
|
||||
for (int i = 0; i < samplesFFT; i++) {
|
||||
windowFFT[i] = (int16_t)(windowFloat[i] * 32767.0f);
|
||||
}
|
||||
free(windowFloat); // free temporary buffer
|
||||
#endif
|
||||
|
||||
// see https://www.freertos.org/vtaskdelayuntil.html
|
||||
const TickType_t xFrequency = FFT_MIN_CYCLE * portTICK_PERIOD_MS;
|
||||
@@ -251,8 +358,7 @@ void FFTcode(void * parameter)
|
||||
#endif
|
||||
|
||||
// get a fresh batch of samples from I2S
|
||||
if (audioSource) audioSource->getSamples(vReal, samplesFFT);
|
||||
memset(vImag, 0, samplesFFT * sizeof(float)); // set imaginary parts to 0
|
||||
if (audioSource) audioSource->getSamples(valFFT, samplesFFT); // note: valFFT is used as a int16_t buffer on C3 and S2, could optimize RAM use by only allocating half the size (but makes code harder to read)
|
||||
|
||||
#if defined(WLED_DEBUG) || defined(SR_DEBUG)
|
||||
if (start < esp_timer_get_time()) { // filter out overflows
|
||||
@@ -264,16 +370,15 @@ void FFTcode(void * parameter)
|
||||
|
||||
xLastWakeTime = xTaskGetTickCount(); // update "last unblocked time" for vTaskDelay
|
||||
|
||||
// band pass filter - can reduce noise floor by a factor of 50
|
||||
// band pass filter - can reduce noise floor by a factor of 50 and avoid aliasing effects to base & high frequency bands
|
||||
// downside: frequencies below 100Hz will be ignored
|
||||
if (useBandPassFilter) runMicFilter(samplesFFT, vReal);
|
||||
|
||||
if (useMicFilter) runMicFilter(samplesFFT, valFFT);
|
||||
// find highest sample in the batch
|
||||
float maxSample = 0.0f; // max sample from FFT batch
|
||||
FFTsampleType maxSample = 0; // max sample from FFT batch
|
||||
for (int i=0; i < samplesFFT; i++) {
|
||||
// pick our our current mic sample - we take the max value from all samples that go into FFT
|
||||
if ((vReal[i] <= (INT16_MAX - 1024)) && (vReal[i] >= (INT16_MIN + 1024))) //skip extreme values - normally these are artefacts
|
||||
if (fabsf((float)vReal[i]) > maxSample) maxSample = fabsf((float)vReal[i]);
|
||||
if ((valFFT[i] <= (INT16_MAX - 1024)) && (valFFT[i] >= (INT16_MIN + 1024))) //skip extreme values - normally these are artefacts
|
||||
if (FFTabs(valFFT[i]) > maxSample) maxSample = FFTabs(valFFT[i]);
|
||||
}
|
||||
// release highest sample to volume reactive effects early - not strictly necessary here - could also be done at the end of the function
|
||||
// early release allows the filters (getSample() and agcAvg()) to work with fresh values - we will have matching gain and noise gate values when we want to process the FFT results.
|
||||
@@ -285,32 +390,97 @@ void FFTcode(void * parameter)
|
||||
if (sampleAvg > 0.25f) { // noise gate open means that FFT results will be used. Don't run FFT if results are not needed.
|
||||
#endif
|
||||
|
||||
// run FFT (takes 3-5ms on ESP32, ~12ms on ESP32-S2)
|
||||
#ifdef UM_AUDIOREACTIVE_USE_ARDUINO_FFT
|
||||
// run Arduino FFT (takes 3-5ms on ESP32, ~12ms on ESP32-S2, ~20ms on ESP32-C3)
|
||||
memset(vImag, 0, samplesFFT * sizeof(float)); // set imaginary parts to 0
|
||||
FFT.dcRemoval(); // remove DC offset
|
||||
#ifdef FFT_PREFER_EXACT_PEAKS
|
||||
FFT.windowing(FFTWindow::Blackman_Harris, FFTDirection::Forward); // Weigh data using "Blackman- Harris" window - sharp peaks due to excellent sideband rejection
|
||||
#else
|
||||
FFT.windowing( FFTWindow::Flat_top, FFTDirection::Forward); // Weigh data using "Flat Top" function - better amplitude accuracy
|
||||
//FFT.windowing(FFTWindow::Blackman_Harris, FFTDirection::Forward); // Weigh data using "Blackman- Harris" window - sharp peaks due to excellent sideband rejection
|
||||
#endif
|
||||
FFT.compute( FFTDirection::Forward ); // Compute FFT
|
||||
FFT.complexToMagnitude(); // Compute magnitudes
|
||||
vReal[0] = 0; // The remaining DC offset on the signal produces a strong spike on position 0 that should be eliminated to avoid issues.
|
||||
|
||||
FFT.majorPeak(&FFT_MajorPeak, &FFT_Magnitude); // let the effects know which freq was most dominant
|
||||
valFFT[0] = 0; // The remaining DC offset on the signal produces a strong spike on position 0 that should be eliminated to avoid issues.
|
||||
FFT.majorPeak(&FFT_MajorPeak, &FFT_Magnitude); // let the effects know which freq was most dominant
|
||||
// note: scaling is done in fftAddAvg(), so we don't scale here
|
||||
#else
|
||||
// run run float DSP FFT (takes ~x ms on ESP32, ~x ms on ESP32-S2, , ~x ms on ESP32-C3) TODO: test and fill in these values
|
||||
// remove DC offset
|
||||
FFTmathType sum = 0;
|
||||
for (int i = 0; i < samplesFFT; i++) sum += valFFT[i];
|
||||
FFTmathType mean = sum / (FFTmathType)samplesFFT;
|
||||
for (int i = 0; i < samplesFFT; i++) valFFT[i] -= mean;
|
||||
#if !defined(UM_AUDIOREACTIVE_USE_INTEGER_FFT)
|
||||
//apply window function to samples and fill buffer with interleaved complex values [Re,Im,Re,Im,...]
|
||||
for (int i = samplesFFT - 1; i >= 0 ; i--) {
|
||||
// fill the buffer back to front to avoid overwriting samples
|
||||
float windowed_sample = valFFT[i] * windowFFT[i];
|
||||
valFFT[i * 2] = windowed_sample;
|
||||
valFFT[i * 2 + 1] = 0.0; // set imaginary part to zero
|
||||
}
|
||||
#ifdef CONFIG_IDF_TARGET_ESP32S3
|
||||
dsps_fft2r_fc32_aes3(valFFT, samplesFFT); // ESP32 S3 optimized version of FFT
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32)
|
||||
dsps_fft2r_fc32_ae32(valFFT, samplesFFT); // ESP32 optimized version of FFT
|
||||
#else
|
||||
dsps_fft2r_fc32_ansi(valFFT, samplesFFT); // perform FFT using ANSI C implementation
|
||||
#endif
|
||||
dsps_bit_rev_fc32(valFFT, samplesFFT); // bit reverse
|
||||
valFFT[0] = 0; // set DC bin to 0, as it is not needed and can cause issues
|
||||
// convert to magnitude & find FFT_MajorPeak and FFT_Magnitude
|
||||
FFT_MajorPeak = 0;
|
||||
FFT_Magnitude = 0;
|
||||
for (int i = 1; i < samplesFFT_2; i++) { // skip [0] as it is DC offset
|
||||
float real_part = valFFT[i * 2];
|
||||
float imag_part = valFFT[i * 2 + 1];
|
||||
valFFT[i] = sqrtf(real_part * real_part + imag_part * imag_part);
|
||||
if (valFFT[i] > FFT_Magnitude) {
|
||||
FFT_Magnitude = valFFT[i];
|
||||
FFT_MajorPeak = i*(SAMPLE_RATE/samplesFFT);
|
||||
}
|
||||
// note: scaling is done in fftAddAvg(), so we don't scale here
|
||||
}
|
||||
#else
|
||||
// run integer DSP FFT (takes ~x ms on ESP32, ~x ms on ESP32-S2, , ~1.5 ms on ESP32-C3) TODO: test and fill in these values
|
||||
//apply window function to samples and fill buffer with interleaved complex values [Re,Im,Re,Im,...]
|
||||
for (int i = samplesFFT - 1; i >= 0 ; i--) {
|
||||
// fill the buffer back to front to avoid overwriting samples
|
||||
int16_t windowed_sample = ((int32_t)valFFT[i] * (int32_t)windowFFT[i]) >> 15; // both values are ±15bit
|
||||
valFFT[i * 2] = windowed_sample;
|
||||
valFFT[i * 2 + 1] = 0; // set imaginary part to zero
|
||||
}
|
||||
dsps_fft2r_sc16_ansi(valFFT, samplesFFT); // perform FFT on complex value pairs (Re,Im)
|
||||
dsps_bit_rev_sc16_ansi(valFFT, samplesFFT); // bit reverse i.e. "unshuffle" the results
|
||||
valFFT[0] = 0; // set DC bin to 0, as it is not needed and can cause issues
|
||||
// convert to magnitude, FFT returns interleaved complex values [Re,Im,Re,Im,...]
|
||||
int FFT_MajorPeak_int = 0;
|
||||
int FFT_Magnitude_int = 0;
|
||||
for (int i = 1; i < samplesFFT_2; i++) { // skip [0], it is DC offset
|
||||
int32_t real_part = valFFT[i * 2];
|
||||
int32_t imag_part = valFFT[i * 2 + 1];
|
||||
valFFT[i] = sqrt32_bw(real_part * real_part + imag_part * imag_part); // note: this should never overflow as Re and Im form a vector of maximum length 32767
|
||||
if (valFFT[i] > FFT_Magnitude_int) {
|
||||
FFT_Magnitude_int = valFFT[i];
|
||||
FFT_MajorPeak_int = ((i * SAMPLE_RATE)/samplesFFT);
|
||||
}
|
||||
// note: scaling is done in fftAddAvg(), so we don't scale here
|
||||
}
|
||||
FFT_Magnitude = FFT_Magnitude_int * 512; // scale to match raw float value
|
||||
FFT_MajorPeak = FFT_MajorPeak_int;
|
||||
FFT_Magnitude = FFT_Magnitude_int;
|
||||
#endif
|
||||
#endif
|
||||
FFT_MajorPeak = constrain(FFT_MajorPeak, 1.0f, 11025.0f); // restrict value to range expected by effects
|
||||
|
||||
#if defined(WLED_DEBUG) || defined(SR_DEBUG)
|
||||
haveDoneFFT = true;
|
||||
#endif
|
||||
|
||||
} else { // noise gate closed - only clear results as FFT was skipped. MIC samples are still valid when we do this.
|
||||
memset(vReal, 0, samplesFFT * sizeof(float));
|
||||
} else { // noise gate closed - only clear results as FFT was skipped. MIC samples are still valid when we do this -> set all samples to 0
|
||||
memset(valFFT, 0, samplesFFT * sizeof(FFTsampleType));
|
||||
FFT_MajorPeak = 1;
|
||||
FFT_Magnitude = 0.001;
|
||||
}
|
||||
|
||||
for (int i = 0; i < samplesFFT; i++) {
|
||||
float t = fabsf(vReal[i]); // just to be sure - values in fft bins should be positive any way
|
||||
vReal[i] = t / 16.0f; // Reduce magnitude. Want end result to be scaled linear and ~4096 max.
|
||||
} // for()
|
||||
|
||||
// mapping of FFT result bins to frequency channels
|
||||
if (fabsf(sampleAvg) > 0.5f) { // noise gate open
|
||||
#if 0
|
||||
@@ -341,7 +511,7 @@ void FFTcode(void * parameter)
|
||||
fftCalc[15] = fftAddAvg(194,250); // 3880 - 5000 // avoid the last 5 bins, which are usually inaccurate
|
||||
#else
|
||||
/* new mapping, optimized for 22050 Hz by softhack007 */
|
||||
// bins frequency range
|
||||
// bins frequency range
|
||||
if (useBandPassFilter) {
|
||||
// skip frequencies below 100hz
|
||||
fftCalc[ 0] = 0.8f * fftAddAvg(3,4);
|
||||
@@ -403,12 +573,15 @@ void FFTcode(void * parameter)
|
||||
// Pre / Postprocessing //
|
||||
///////////////////////////
|
||||
|
||||
static void runMicFilter(uint16_t numSamples, float *sampleBuffer) // pre-filtering of raw samples (band-pass)
|
||||
static void runMicFilter(uint16_t numSamples, FFTsampleType *sampleBuffer) // pre-filtering of raw samples (band-pass)
|
||||
{
|
||||
// low frequency cutoff parameter - see https://dsp.stackexchange.com/questions/40462/exponential-moving-average-cut-off-frequency
|
||||
#if !defined(UM_AUDIOREACTIVE_USE_INTEGER_FFT)
|
||||
// low frequency cutoff parameter - see https://dsp.stackexchange.com/questions/40462/exponential-moving-average-cut-off-frequency (alpha = 2π × fc / fs)
|
||||
//constexpr float alpha = 0.04f; // 150Hz
|
||||
//constexpr float alpha = 0.03f; // 110Hz
|
||||
constexpr float alpha = 0.0225f; // 80hz
|
||||
//constexpr float alpha = 0.0285f; //100Hz
|
||||
constexpr float alpha = 0.0256f; //90Hz
|
||||
//constexpr float alpha = 0.0225f; // 80hz
|
||||
//constexpr float alpha = 0.01693f;// 60hz
|
||||
// high frequency cutoff parameter
|
||||
//constexpr float beta1 = 0.75f; // 11Khz
|
||||
@@ -432,6 +605,39 @@ static void runMicFilter(uint16_t numSamples, float *sampleBuffer) // p
|
||||
lowfilt += alpha * (sampleBuffer[i] - lowfilt);
|
||||
sampleBuffer[i] = sampleBuffer[i] - lowfilt;
|
||||
}
|
||||
#else
|
||||
// low frequency cutoff parameter 17.15 fixed point format
|
||||
//constexpr int32_t ALPHA_FP = 1311; // 0.04f * (1<<15) (150Hz)
|
||||
//constexpr int32_t ALPHA_FP = 983; // 0.03f * (1<<15) (110Hz)
|
||||
//constexpr int32_t ALPHA_FP = 934; // 0.0285f * (1<<15) (100Hz)
|
||||
constexpr int32_t ALPHA_FP = 840; // 0.0256f * (1<<15) (90Hz)
|
||||
//constexpr int32_t ALPHA_FP = 737; // 0.0225f * (1<<15) (80Hz)
|
||||
//constexpr int32_t ALPHA_FP = 555; // 0.01693f * (1<<15) (60Hz)
|
||||
|
||||
// high frequency cutoff parameters 16.16 fixed point format
|
||||
//constexpr int32_t BETA1_FP = 49152; // 0.75f * (1<<16) (11KHz)
|
||||
//constexpr int32_t BETA1_FP = 53740; // 0.82f * (1<<16) (15KHz)
|
||||
//constexpr int32_t BETA1_FP = 54297; // 0.8285f * (1<<16) (18KHz)
|
||||
constexpr int32_t BETA1_FP = 55706; // 0.85f * (1<<16) (20KHz)
|
||||
constexpr int32_t BETA2_FP = (65536 - BETA1_FP) / 2; // ((1.0f - beta1) / 2.0f) * (1<<16)
|
||||
|
||||
static int32_t last_vals[2] = { 0 }; // FIR high freq cutoff filter (scaled by sample range)
|
||||
static int32_t lowfilt_fp = 0; // IIR low frequency cutoff filter (16.16 fixed point)
|
||||
|
||||
for (int i = 0; i < numSamples; i++) {
|
||||
// FIR lowpass filter to remove high frequency noise
|
||||
int32_t highFilteredSample_fp;
|
||||
|
||||
if (i < (numSamples - 1))
|
||||
highFilteredSample_fp = (BETA1_FP * (int32_t)sampleBuffer[i] + BETA2_FP * last_vals[0] + BETA2_FP * (int32_t)sampleBuffer[i + 1]) >> 16; // smooth out spikes
|
||||
else
|
||||
highFilteredSample_fp = (BETA1_FP * (int32_t)sampleBuffer[i] + BETA2_FP * last_vals[0] + BETA2_FP * last_vals[1]) >> 16; // special handling for last sample in array
|
||||
last_vals[1] = last_vals[0];
|
||||
last_vals[0] = (int32_t)sampleBuffer[i];
|
||||
lowfilt_fp += ALPHA_FP * (highFilteredSample_fp - (lowfilt_fp >> 15)); // low pass filter in 17.15 fixed point format
|
||||
sampleBuffer[i] = highFilteredSample_fp - (lowfilt_fp >> 15);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
static void postProcessFFTResults(bool noiseGateOpen, int numberOfChannels) // post-processing and post-amp of GEQ channels
|
||||
@@ -520,7 +726,7 @@ static void detectSamplePeak(void) {
|
||||
// Poor man's beat detection by seeing if sample > Average + some value.
|
||||
// This goes through ALL of the 255 bins - but ignores stupid settings
|
||||
// Then we got a peak, else we don't. The peak has to time out on its own in order to support UDP sound sync.
|
||||
if ((sampleAvg > 1) && (maxVol > 0) && (binNum > 4) && (vReal[binNum] > maxVol) && ((millis() - timeOfPeak) > 100)) {
|
||||
if ((sampleAvg > 1) && (maxVol > 0) && (binNum > 4) && (valFFT[binNum] > maxVol) && ((millis() - timeOfPeak) > 100)) {
|
||||
havePeak = true;
|
||||
}
|
||||
|
||||
@@ -1165,8 +1371,8 @@ class AudioReactive : public Usermod {
|
||||
periph_module_reset(PERIPH_I2S0_MODULE); // not possible on -C3
|
||||
#endif
|
||||
delay(100); // Give that poor microphone some time to setup.
|
||||
|
||||
useBandPassFilter = false;
|
||||
useBandPassFilter = false; // filter cuts lowest and highest frequency bands from FFT result (use on very noisy mic inputs)
|
||||
useMicFilter = true; // filter fixes aliasing to base & highest frequency bands and reduces noise floor (recommended for all mic inputs)
|
||||
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
if ((i2sckPin == I2S_PIN_NO_CHANGE) && (i2ssdPin >= 0) && (i2swsPin >= 0) && ((dmType == 1) || (dmType == 4)) ) dmType = 5; // dummy user support: SCK == -1 --means--> PDM microphone
|
||||
@@ -1201,12 +1407,13 @@ class AudioReactive : public Usermod {
|
||||
case 4:
|
||||
DEBUGSR_PRINT(F("AR: Generic I2S Microphone with Master Clock - ")); DEBUGSR_PRINTLN(F(I2S_MIC_CHANNEL_TEXT));
|
||||
audioSource = new I2SSource(SAMPLE_RATE, BLOCK_SIZE, 1.0f/24.0f);
|
||||
useMicFilter = false; // I2S with Master Clock is mostly used for line-in, skip sample filtering
|
||||
delay(100);
|
||||
if (audioSource) audioSource->initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin);
|
||||
break;
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
case 5:
|
||||
DEBUGSR_PRINT(F("AR: I2S PDM Microphone - ")); DEBUGSR_PRINTLN(F(I2S_PDM_MIC_CHANNEL_TEXT));
|
||||
DEBUGSR_PRINT(F("AR: Generic PDM Microphone - ")); DEBUGSR_PRINTLN(F(I2S_PDM_MIC_CHANNEL_TEXT));
|
||||
audioSource = new I2SSource(SAMPLE_RATE, BLOCK_SIZE, 1.0f/4.0f);
|
||||
useBandPassFilter = true; // this reduces the noise floor on SPM1423 from 5% Vpp (~380) down to 0.05% Vpp (~5)
|
||||
delay(100);
|
||||
@@ -1216,6 +1423,7 @@ class AudioReactive : public Usermod {
|
||||
case 6:
|
||||
DEBUGSR_PRINTLN(F("AR: ES8388 Source"));
|
||||
audioSource = new ES8388Source(SAMPLE_RATE, BLOCK_SIZE);
|
||||
useMicFilter = false;
|
||||
delay(100);
|
||||
if (audioSource) audioSource->initialize(i2swsPin, i2ssdPin, i2sckPin, mclkPin);
|
||||
break;
|
||||
@@ -1624,7 +1832,8 @@ class AudioReactive : public Usermod {
|
||||
if (audioSource->getType() == AudioSource::Type_I2SAdc) {
|
||||
infoArr.add(F("ADC analog"));
|
||||
} else {
|
||||
infoArr.add(F("I2S digital"));
|
||||
if (dmType == 5) infoArr.add(F("PDM digital")); // dmType 5 => generic PDM microphone
|
||||
else infoArr.add(F("I2S digital"));
|
||||
}
|
||||
// input level or "silence"
|
||||
if (maxSample5sec > 1.0f) {
|
||||
@@ -1742,14 +1951,14 @@ class AudioReactive : public Usermod {
|
||||
}
|
||||
#endif
|
||||
}
|
||||
if (root.containsKey(F("rmcpal")) && root[F("rmcpal")].as<bool>()) {
|
||||
if (palettes > 0 && root.containsKey(F("rmcpal"))) {
|
||||
// handle removal of custom palettes from JSON call so we don't break things
|
||||
removeAudioPalettes();
|
||||
}
|
||||
}
|
||||
|
||||
void onStateChange(uint8_t callMode) override {
|
||||
if (initDone && enabled && addPalettes && palettes==0 && customPalettes.size()<10) {
|
||||
if (initDone && enabled && addPalettes && palettes==0 && customPalettes.size()<WLED_MAX_CUSTOM_PALETTES) {
|
||||
// if palettes were removed during JSON call re-add them
|
||||
createAudioPalettes();
|
||||
}
|
||||
@@ -1911,7 +2120,7 @@ class AudioReactive : public Usermod {
|
||||
uiScript.print(F("addOption(dd,'SPH0654',3);"));
|
||||
uiScript.print(F("addOption(dd,'Generic I2S with Mclk',4);"));
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
uiScript.print(F("addOption(dd,'Generic I2S PDM',5);"));
|
||||
uiScript.print(F("addOption(dd,'Generic PDM',5);"));
|
||||
#endif
|
||||
uiScript.print(F("addOption(dd,'ES8388',6);"));
|
||||
|
||||
@@ -2007,12 +2216,12 @@ CRGB AudioReactive::getCRGBForBand(int x, int pal) {
|
||||
case 2:
|
||||
b = map(x, 0, 255, 0, NUM_GEQ_CHANNELS/2); // convert palette position to lower half of freq band
|
||||
hsv = CHSV(fftResult[b], 255, x);
|
||||
hsv2rgb_rainbow(hsv, value); // convert to R,G,B
|
||||
value = hsv; // convert to R,G,B
|
||||
break;
|
||||
case 1:
|
||||
b = map(x, 1, 255, 0, 10); // convert palette position to lower half of freq band
|
||||
hsv = CHSV(fftResult[b], 255, map(fftResult[b], 0, 255, 30, 255)); // pick hue
|
||||
hsv2rgb_rainbow(hsv, value); // convert to R,G,B
|
||||
value = hsv; // convert to R,G,B
|
||||
break;
|
||||
default:
|
||||
if (x == 1) {
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
// see https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/hw-reference/chip-series-comparison.html#related-documents
|
||||
// and https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/api-reference/peripherals/i2s.html#overview-of-all-modes
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(ESP8266) || defined(ESP8265)
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(ESP8266) || defined(ESP8265)
|
||||
// there are two things in these MCUs that could lead to problems with audio processing:
|
||||
// * no floating point hardware (FPU) support - FFT uses float calculations. If done in software, a strong slow-down can be expected (between 8x and 20x)
|
||||
// * single core, so FFT task might slow down other things like LED updates
|
||||
@@ -71,7 +71,7 @@
|
||||
* if you want to receive two channels, one is the actual data from microphone and another channel is suppose to receive 0, it's different data in two channels, you need to choose I2S_CHANNEL_FMT_RIGHT_LEFT in this case.
|
||||
*/
|
||||
|
||||
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)) && (ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(4, 4, 6))
|
||||
#if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0)) && (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(4, 5, 0))
|
||||
// espressif bug: only_left has no sound, left and right are swapped
|
||||
// https://github.com/espressif/esp-idf/issues/9635 I2S mic not working since 4.4 (IDFGH-8138)
|
||||
// https://github.com/espressif/esp-idf/issues/8538 I2S channel selection issue? (IDFGH-6918)
|
||||
@@ -134,7 +134,7 @@ class AudioSource {
|
||||
Read num_samples from the microphone, and store them in the provided
|
||||
buffer
|
||||
*/
|
||||
virtual void getSamples(float *buffer, uint16_t num_samples) = 0;
|
||||
virtual void getSamples(FFTsampleType *buffer, uint16_t num_samples) = 0;
|
||||
|
||||
/* check if the audio source driver was initialized successfully */
|
||||
virtual bool isInitialized(void) {return(_initialized);}
|
||||
@@ -225,15 +225,17 @@ class I2SSource : public AudioSource {
|
||||
|
||||
_config.mode = i2s_mode_t(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_PDM); // Change mode to pdm if clock pin not provided. PDM is not supported on ESP32-S2. PDM RX not supported on ESP32-C3
|
||||
_config.channel_format =I2S_PDM_MIC_CHANNEL; // seems that PDM mono mode always uses left channel.
|
||||
_config.use_apll = true; // experimental - use aPLL clock source to improve sampling quality
|
||||
_config.use_apll = false; // don't use aPLL clock source (fix for #5391)
|
||||
#endif
|
||||
}
|
||||
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 2, 0)
|
||||
if (mclkPin != I2S_PIN_NO_CHANGE) {
|
||||
#if !defined(WLED_USE_ETHERNET) // fix for #5391 aPLL resource conflict - aPLL is needed for ethernet boards with internal RMII clock
|
||||
_config.use_apll = true; // experimental - use aPLL clock source to improve sampling quality, and to avoid glitches.
|
||||
// //_config.fixed_mclk = 512 * _sampleRate;
|
||||
// //_config.fixed_mclk = 256 * _sampleRate;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !defined(SOC_I2S_SUPPORTS_APLL)
|
||||
@@ -314,7 +316,7 @@ class I2SSource : public AudioSource {
|
||||
if (_mclkPin != I2S_PIN_NO_CHANGE) PinManager::deallocatePin(_mclkPin, PinOwner::UM_Audioreactive);
|
||||
}
|
||||
|
||||
virtual void getSamples(float *buffer, uint16_t num_samples) {
|
||||
virtual void getSamples(FFTsampleType *buffer, uint16_t num_samples) {
|
||||
if (_initialized) {
|
||||
esp_err_t err;
|
||||
size_t bytes_read = 0; /* Counter variable to check if we actually got enough data */
|
||||
@@ -332,19 +334,36 @@ class I2SSource : public AudioSource {
|
||||
return;
|
||||
}
|
||||
|
||||
// Store samples in sample buffer and update DC offset
|
||||
for (int i = 0; i < num_samples; i++) {
|
||||
|
||||
newSamples[i] = postProcessSample(newSamples[i]); // perform postprocessing (needed for ADC samples)
|
||||
|
||||
float currSample = 0.0f;
|
||||
#ifdef I2S_SAMPLE_DOWNSCALE_TO_16BIT
|
||||
currSample = (float) newSamples[i] / 65536.0f; // 32bit input -> 16bit; keeping lower 16bits as decimal places
|
||||
#else
|
||||
currSample = (float) newSamples[i]; // 16bit input -> use as-is
|
||||
// Store samples in sample buffer
|
||||
#if defined(UM_AUDIOREACTIVE_USE_INTEGER_FFT)
|
||||
//constexpr int32_t FIXEDSHIFT = 8; // shift by 8 bits for fixed point math (no loss at 24bit input sample resolution)
|
||||
//int32_t intSampleScale = _sampleScale * (1<<FIXEDSHIFT); // _sampleScale <= 1.0f, shift for fixed point math
|
||||
#endif
|
||||
|
||||
for (int i = 0; i < num_samples; i++) {
|
||||
newSamples[i] = postProcessSample(newSamples[i]); // perform postprocessing (needed for ADC samples)
|
||||
|
||||
#if !defined(UM_AUDIOREACTIVE_USE_INTEGER_FFT)
|
||||
#ifdef I2S_SAMPLE_DOWNSCALE_TO_16BIT
|
||||
float currSample = (float) newSamples[i] / 65536.0f; // 32bit input -> 16bit; keeping lower 16bits as decimal places
|
||||
#else
|
||||
float currSample = (float) newSamples[i]; // 16bit input -> use as-is
|
||||
#endif
|
||||
buffer[i] = currSample;
|
||||
buffer[i] *= _sampleScale; // scale samples
|
||||
buffer[i] *= _sampleScale; // scale samples
|
||||
#else
|
||||
#ifdef I2S_SAMPLE_DOWNSCALE_TO_16BIT
|
||||
// note on sample scaling: scaling is only used for inputs with master clock and those are better suited for ESP32 or S3
|
||||
// execution speed is critical on single core MCUs
|
||||
//int32_t currSample = newSamples[i] >> FIXEDSHIFT; // shift to avoid overlow in multiplication
|
||||
//currSample = (currSample * intSampleScale) >> 16; // scale samples, shift down to 16bit
|
||||
int16_t currSample = newSamples[i] >> 16; // no sample scaling, just shift down to 16bit (not scaling saves ~0.4ms on C3)
|
||||
#else
|
||||
//int32_t currSample = (newSamples[i] * intSampleScale) >> FIXEDSHIFT; // scale samples, shift back down to 16bit
|
||||
int16_t currSample = newSamples[i]; // 16bit input -> use as-is
|
||||
#endif
|
||||
buffer[i] = (int16_t)currSample;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -622,7 +641,7 @@ class I2SAdcSource : public I2SSource {
|
||||
}
|
||||
|
||||
// see example in https://github.com/espressif/arduino-esp32/blob/master/libraries/ESP32/examples/I2S/HiFreq_ADC/HiFreq_ADC.ino
|
||||
adc1_config_channel_atten(adc1_channel_t(channel), ADC_ATTEN_DB_11); // configure ADC input amplification
|
||||
adc1_config_channel_atten(adc1_channel_t(channel), ADC_ATTEN_DB_12); // configure ADC input amplification
|
||||
|
||||
#if defined(I2S_GRAB_ADC1_COMPLETELY)
|
||||
// according to docs from espressif, the ADC needs to be started explicitly
|
||||
@@ -687,7 +706,7 @@ class I2SAdcSource : public I2SSource {
|
||||
}
|
||||
|
||||
|
||||
void getSamples(float *buffer, uint16_t num_samples) {
|
||||
void getSamples(FFTsampleType *buffer, uint16_t num_samples) {
|
||||
/* Enable ADC. This has to be enabled and disabled directly before and
|
||||
* after sampling, otherwise Wifi dies
|
||||
*/
|
||||
|
||||
@@ -89,28 +89,29 @@ class DeepSleepUsermod : public Usermod {
|
||||
int currentWeekday = weekdayMondayFirst(); // 1=Monday ... 7=Sunday
|
||||
int minDifference = INT_MAX;
|
||||
|
||||
for (uint8_t i = 0; i < 8; i++) {
|
||||
// check if timer is enabled and date is in range, also wakes up if no macro is used
|
||||
if ((timerWeekday[i] & 0x01) && isTodayInDateRange(((timerMonth[i] >> 4) & 0x0F), timerDay[i], timerMonth[i] & 0x0F, timerDayEnd[i])) {
|
||||
for (size_t i = 0; i < timers.size(); i++) {
|
||||
const Timer& t = timers[i];
|
||||
// only regular enabled timers with valid date range can be used for wake scheduling
|
||||
if (!t.isEnabled() || !t.isRegular()) continue;
|
||||
if (!isTodayInDateRange(t.monthStart, t.dayStart, t.monthEnd, t.dayEnd)) continue;
|
||||
|
||||
// if timer is enabled (bit0 of timerWeekday) and date is in range, check all weekdays it is set for
|
||||
for (int dayOffset = 0; dayOffset < 7; dayOffset++) {
|
||||
int checkWeekday = ((currentWeekday + dayOffset) % 7); // 1-7, check all weekdays starting from today
|
||||
if (checkWeekday == 0) {
|
||||
checkWeekday = 7; // sunday is 7 not 0
|
||||
}
|
||||
// check all weekdays for the current timer, starting from today
|
||||
for (int dayOffset = 0; dayOffset < 7; dayOffset++) {
|
||||
int checkWeekday = (currentWeekday + dayOffset) % 7; // 1-7, check all weekdays starting from today
|
||||
if (checkWeekday == 0) {
|
||||
checkWeekday = 7; // sunday is 7 not 0
|
||||
}
|
||||
|
||||
int targetHour = timerHours[i];
|
||||
int targetMinute = timerMinutes[i];
|
||||
if ((timerWeekday[i] >> (checkWeekday)) & 0x01) {
|
||||
if (dayOffset == 0 && (targetHour < currentHour || (targetHour == currentHour && targetMinute <= currentMinute)))
|
||||
continue; // skip if time has already passed today
|
||||
int targetHour = t.hour;
|
||||
int targetMinute = t.minute;
|
||||
if ((t.weekdays >> checkWeekday) & 0x01) {
|
||||
if (dayOffset == 0 && (targetHour < currentHour || (targetHour == currentHour && targetMinute <= currentMinute)))
|
||||
continue; // skip if time has already passed today
|
||||
|
||||
int timeDifference = calculateTimeDifference(currentHour, currentMinute, targetHour + (dayOffset * 24), targetMinute);
|
||||
if (timeDifference < minDifference) {
|
||||
minDifference = timeDifference;
|
||||
wakeupPreset = timerMacro[i];
|
||||
}
|
||||
int timeDifference = calculateTimeDifference(currentHour, currentMinute, targetHour + (dayOffset * 24), targetMinute);
|
||||
if (timeDifference < minDifference) {
|
||||
minDifference = timeDifference;
|
||||
wakeupPreset = t.preset;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,7 +157,7 @@ class DeepSleepUsermod : public Usermod {
|
||||
delay(1000); // just in case: give user a short ~10s window to turn LEDs on in UI (delaycounter is 10 by default)
|
||||
return;
|
||||
}
|
||||
if (powerup == false && delaycounter) { // delay sleep in case a preset is being loaded and turnOnAtBoot is disabled (handleIO() does enable offMode temporarily in this case)
|
||||
if (powerup == false && delaycounter) { // delay sleep in case a preset is being loaded and turnOnAtBoot is disabled (beginStrip() / handleIO() does enable offMode temporarily in this case)
|
||||
delaycounter--;
|
||||
if (delaycounter == 1 && offMode) { // force turn on, no matter the settings (device is bricked if user set sleepDelay=0, no bootup preset and turnOnAtBoot=false)
|
||||
if (briS == 0) bri = 10; // turn on and set low brightness to avoid automatic turn off
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# pixels_dice_tray Usermod - BLE Requirement Notice
|
||||
|
||||
## Important: This Usermod Requires Special Configuration
|
||||
|
||||
The `pixels_dice_tray` usermod requires **ESP32 BLE (Bluetooth Low Energy)** support, which is not available in all WLED build configurations.
|
||||
|
||||
### Why is library.json disabled?
|
||||
|
||||
The `library.json` file has been renamed to `library.json.disabled` to prevent this usermod from being automatically included in builds that use `custom_usermods = *` (like the `usermods` environment in platformio.ini).
|
||||
|
||||
The Tasmota Arduino ESP32 platform used by WLED does not include Arduino BLE library by default, which causes compilation failures when this usermod is auto-included.
|
||||
|
||||
### How to Use This Usermod
|
||||
|
||||
This usermod **requires a custom build configuration**. You cannot simply enable it with `custom_usermods = *`.
|
||||
|
||||
1. **Copy the sample configuration:**
|
||||
```bash
|
||||
cp platformio_override.ini.sample ../../../platformio_override.ini
|
||||
```
|
||||
|
||||
2. **Edit `platformio_override.ini`** to match your ESP32 board configuration
|
||||
|
||||
3. **Build with the custom environment:**
|
||||
```bash
|
||||
pio run -e t_qt_pro_8MB_dice
|
||||
# or
|
||||
pio run -e esp32s3dev_8MB_qspi_dice
|
||||
```
|
||||
|
||||
### Platform Requirements
|
||||
|
||||
- ESP32-S3 or compatible ESP32 board with BLE support
|
||||
- Custom platformio environment (see `platformio_override.ini.sample`)
|
||||
- Cannot be used with ESP8266 or ESP32-S2
|
||||
|
||||
### Re-enabling for Custom Builds
|
||||
|
||||
If you want to use this usermod in a custom build:
|
||||
|
||||
1. Rename `library.json.disabled` back to `library.json`
|
||||
2. Manually add it to your custom environment's `custom_usermods` list
|
||||
3. Ensure your platform includes BLE support
|
||||
|
||||
### References
|
||||
|
||||
- See `README.md` for full usermod documentation
|
||||
- See `platformio_override.ini.sample` for build configuration examples
|
||||
@@ -8,10 +8,10 @@
|
||||
#include "dice_state.h"
|
||||
|
||||
// Reuse FX display functions.
|
||||
extern uint16_t mode_breath();
|
||||
extern uint16_t mode_blends();
|
||||
extern uint16_t mode_glitter();
|
||||
extern uint16_t mode_gravcenter();
|
||||
extern void mode_breath();
|
||||
extern void mode_blends();
|
||||
extern void mode_glitter();
|
||||
extern void mode_gravcenter();
|
||||
|
||||
static constexpr uint8_t USER_ANY_DIE = 0xFF;
|
||||
/**
|
||||
@@ -40,8 +40,8 @@ static pixels::RollEvent GetLastRollForSegment() {
|
||||
* Alternating pixels running function (copied static function).
|
||||
*/
|
||||
// paletteBlend: 0 - wrap when moving, 1 - always wrap, 2 - never wrap, 3 - none (undefined)
|
||||
#define PALETTE_SOLID_WRAP (strip.paletteBlend == 1 || strip.paletteBlend == 3)
|
||||
static uint16_t running_copy(uint32_t color1, uint32_t color2, bool theatre = false) {
|
||||
#define PALETTE_SOLID_WRAP (paletteBlend == 1 || paletteBlend == 3)
|
||||
static void running_copy(uint32_t color1, uint32_t color2, bool theatre = false) {
|
||||
int width = (theatre ? 3 : 1) + (SEGMENT.intensity >> 4); // window
|
||||
uint32_t cycleTime = 50 + (255 - SEGMENT.speed);
|
||||
uint32_t it = strip.now / cycleTime;
|
||||
@@ -63,10 +63,9 @@ static uint16_t running_copy(uint32_t color1, uint32_t color2, bool theatre = fa
|
||||
SEGENV.aux0 = (SEGENV.aux0 +1) % (theatre ? width : (width<<1));
|
||||
SEGENV.step = it;
|
||||
}
|
||||
return FRAMETIME;
|
||||
}
|
||||
|
||||
static uint16_t simple_roll() {
|
||||
static void simple_roll() {
|
||||
auto roll = GetLastRollForSegment();
|
||||
if (roll.state != pixels::RollState::ON_FACE) {
|
||||
SEGMENT.fill(0);
|
||||
@@ -79,7 +78,6 @@ static uint16_t simple_roll() {
|
||||
SEGMENT.setPixelColor(i, SEGCOLOR(1));
|
||||
}
|
||||
}
|
||||
return FRAMETIME;
|
||||
}
|
||||
// See https://kno.wled.ge/interfaces/json-api/#effect-metadata
|
||||
// Name - DieSimple
|
||||
@@ -92,31 +90,34 @@ static uint16_t simple_roll() {
|
||||
static const char _data_FX_MODE_SIMPLE_DIE[] PROGMEM =
|
||||
"DieSimple@,,Selected Die;!,!;;1;c1=255";
|
||||
|
||||
static uint16_t pulse_roll() {
|
||||
static void pulse_roll() {
|
||||
auto roll = GetLastRollForSegment();
|
||||
if (roll.state != pixels::RollState::ON_FACE) {
|
||||
return mode_breath();
|
||||
mode_breath();
|
||||
return;
|
||||
} else {
|
||||
uint16_t ret = mode_blends();
|
||||
mode_blends();
|
||||
uint16_t num_segments = float(roll.current_face + 1) / 20.0 * SEGLEN;
|
||||
for (int i = num_segments; i < SEGLEN; i++) {
|
||||
SEGMENT.setPixelColor(i, SEGCOLOR(1));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
static const char _data_FX_MODE_PULSE_DIE[] PROGMEM =
|
||||
"DiePulse@!,!,Selected Die;!,!;!;1;sx=24,pal=50,c1=255";
|
||||
|
||||
static uint16_t check_roll() {
|
||||
static void check_roll() {
|
||||
auto roll = GetLastRollForSegment();
|
||||
if (roll.state != pixels::RollState::ON_FACE) {
|
||||
return running_copy(SEGCOLOR(0), SEGCOLOR(2));
|
||||
running_copy(SEGCOLOR(0), SEGCOLOR(2));
|
||||
return;
|
||||
} else {
|
||||
if (roll.current_face + 1 >= SEGMENT.custom2) {
|
||||
return mode_glitter();
|
||||
mode_glitter();
|
||||
return;
|
||||
} else {
|
||||
return mode_gravcenter();
|
||||
mode_gravcenter();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"name": "pixels_dice_tray",
|
||||
"build": { "libArchive": false},
|
||||
"dependencies": {
|
||||
"arduino-pixels-dice":"https://github.com/axlan/arduino-pixels-dice.git",
|
||||
"BLE":"*"
|
||||
}
|
||||
}
|
||||
@@ -5,37 +5,37 @@ static const char _data_FX_MODE_POV_IMAGE[] PROGMEM = "POV Image@!;;;;";
|
||||
|
||||
static POV s_pov;
|
||||
|
||||
uint16_t mode_pov_image(void) {
|
||||
void mode_pov_image(void) {
|
||||
Segment& mainseg = strip.getMainSegment();
|
||||
const char* segName = mainseg.name;
|
||||
if (!segName) {
|
||||
return FRAMETIME;
|
||||
return;
|
||||
}
|
||||
// Only proceed for files ending with .bmp (case-insensitive)
|
||||
size_t segLen = strlen(segName);
|
||||
if (segLen < 4) return FRAMETIME;
|
||||
if (segLen < 4) return;
|
||||
const char* ext = segName + (segLen - 4);
|
||||
// compare case-insensitive to ".bmp"
|
||||
if (!((ext[0]=='.') &&
|
||||
(ext[1]=='b' || ext[1]=='B') &&
|
||||
(ext[2]=='m' || ext[2]=='M') &&
|
||||
(ext[3]=='p' || ext[3]=='P'))) {
|
||||
return FRAMETIME;
|
||||
return;
|
||||
}
|
||||
|
||||
const char* current = s_pov.getFilename();
|
||||
if (current && strcmp(segName, current) == 0) {
|
||||
s_pov.showNextLine();
|
||||
return FRAMETIME;
|
||||
return;
|
||||
}
|
||||
|
||||
static unsigned long s_lastLoadAttemptMs = 0;
|
||||
unsigned long nowMs = millis();
|
||||
// Retry at most twice per second if the image is not yet loaded.
|
||||
if (nowMs - s_lastLoadAttemptMs < 500) return FRAMETIME;
|
||||
if (nowMs - s_lastLoadAttemptMs < 500) return;
|
||||
s_lastLoadAttemptMs = nowMs;
|
||||
s_pov.loadImage(segName);
|
||||
return FRAMETIME;
|
||||
return;
|
||||
}
|
||||
|
||||
class PovDisplayUsermod : public Usermod {
|
||||
|
||||
@@ -34,6 +34,7 @@ class RgbRotaryEncoderUsermod : public Usermod
|
||||
byte currentColors[3];
|
||||
byte lastKnownBri = 0;
|
||||
|
||||
inline uint32_t colorFromRgb(byte* rgb) { return uint32_t((byte(rgb[0]) << 16) | (byte(rgb[1]) << 8) | (byte(rgb[2]))); }
|
||||
|
||||
void initRotaryEncoder()
|
||||
{
|
||||
@@ -60,8 +61,8 @@ class RgbRotaryEncoderUsermod : public Usermod
|
||||
// …then set only the LED pin
|
||||
_pins[0] = static_cast<byte>(ledIo);
|
||||
BusConfig busCfg = BusConfig(TYPE_WS2812_RGB, _pins, 0, numLeds, COL_ORDER_GRB, false, 0);
|
||||
|
||||
ledBus = new BusDigital(busCfg, WLED_MAX_BUSSES - 1);
|
||||
busCfg.iType = BusManager::getI(busCfg.type, busCfg.pins, busCfg.driverType); // assign internal bus type and output driver
|
||||
ledBus = new BusDigital(busCfg);
|
||||
if (!ledBus->isOk()) {
|
||||
cleanup();
|
||||
return;
|
||||
@@ -79,7 +80,7 @@ class RgbRotaryEncoderUsermod : public Usermod
|
||||
for (int i = 0; i < currentPos / incrementPerClick - 1; i++) {
|
||||
ledBus->setPixelColor(i, 0);
|
||||
}
|
||||
ledBus->setPixelColor(currentPos / incrementPerClick - 1, colorFromRgbw(currentColors));
|
||||
ledBus->setPixelColor(currentPos / incrementPerClick - 1, colorFromRgb(currentColors));
|
||||
for (int i = currentPos / incrementPerClick; i < numLeds; i++) {
|
||||
ledBus->setPixelColor(i, 0);
|
||||
}
|
||||
@@ -95,7 +96,7 @@ class RgbRotaryEncoderUsermod : public Usermod
|
||||
if (ledMode == 3) {
|
||||
hsv2rgb((i) / float(numLeds), 1, .25);
|
||||
}
|
||||
ledBus->setPixelColor(i, colorFromRgbw(currentColors));
|
||||
ledBus->setPixelColor(i, colorFromRgb(currentColors));
|
||||
}
|
||||
for (int i = currentPos / incrementPerClick; i < numLeds; i++) {
|
||||
ledBus->setPixelColor(i, 0);
|
||||
|
||||
+32
-31
@@ -4,6 +4,7 @@ This usermod is a common place to put various users’ WLED effects. It lets you
|
||||
|
||||
Multiple Effects can be specified inside this single usermod, as we will illustrate below. You will be able to define them with custom names, sliders, etc. as with any other Effect.
|
||||
|
||||
* [Installation](./README.md#installation)
|
||||
* [How The Usermod Works](./README.md#how-the-usermod-works)
|
||||
* [Basic Syntax for WLED Effect Creation](./README.md#basic-syntax-for-wled-effect-creation)
|
||||
* [Understanding 2D WLED Effects](./README.md#understanding-2d-wled-effects)
|
||||
@@ -14,6 +15,17 @@ Multiple Effects can be specified inside this single usermod, as we will illustr
|
||||
* [Change Log](./README.md#change-log)
|
||||
* [Contact Us](./README.md#contact-us)
|
||||
|
||||
## Installation
|
||||
|
||||
To activate the usermod, add the following line to your platformio_override.ini
|
||||
```ini
|
||||
custom_usermods = user_fx
|
||||
```
|
||||
Or if you are already using a usermod, append user_fx to the list
|
||||
```ini
|
||||
custom_usermods = audioreactive user_fx
|
||||
```
|
||||
|
||||
## How The Usermod Works
|
||||
|
||||
The `user_fx.cpp` file can be broken down into four main parts:
|
||||
@@ -76,12 +88,14 @@ The first line of the code imports the [wled.h](https://github.com/wled/WLED/blo
|
||||
### Static Effect Definition
|
||||
The next code block is the `mode_static` definition. This is usually left as `SEGMENT.fill(SEGCOLOR(0));` to leave all pixels off if the effect fails to load, but in theory one could use this as a 'fallback effect' to take on a different behavior, such as displaying some other color instead of leaving the pixels off.
|
||||
|
||||
`FX_FALLBACK_STATIC` is a macro that calls `mode_static()` and then returns.
|
||||
|
||||
### User Effect Definitions
|
||||
Pre-loaded in this template is an example 2D Effect called "Diffusion Fire". (This is the name that would be shown in the UI once the binary is compiled and run on your device, as defined in the metadata string.)
|
||||
The effect starts off by checking to see if the segment that the effect is being applied to is a 2D Matrix, and if it is not, then it returns the static effect which displays no pattern:
|
||||
The effect starts off by checking to see if the segment that the effect is being applied to is a 2D Matrix, and if it is not, then it runs the static effect which displays no pattern:
|
||||
```cpp
|
||||
if (!strip.isMatrix || !SEGMENT.is2D())
|
||||
return mode_static(); // not a 2D set-up
|
||||
FX_FALLBACK_STATIC; // not a 2D set-up
|
||||
```
|
||||
The next code block contains several constant variable definitions which essentially serve to extract the dimensions of the user's 2D matrix and allow WLED to interpret the matrix as a 1D coordinate system (WLED must do this for all 2D animations):
|
||||
```cpp
|
||||
@@ -128,7 +142,7 @@ unsigned dataSize = cols * rows; // SEGLEN (virtual length) is equivalent to vW
|
||||
|
||||
```cpp
|
||||
if (!SEGENV.allocateData(dataSize))
|
||||
return mode_static(); // allocation failed
|
||||
FX_FALLBACK_STATIC; // allocation failed
|
||||
```
|
||||
* Upon the first call, this section allocates a persistent data buffer tied to the segment environment (`SEGENV.data`). All subsequent calls simply ensure that the data is still valid.
|
||||
* The syntax `SEGENV.allocateData(n)` requests a buffer of size n bytes (1 byte per pixel here).
|
||||
@@ -250,20 +264,14 @@ After calculating tmp_row, we now handle rendering the pixels by updating the ac
|
||||
* `SEGCOLOR(0)` gets the first user-selected color for the segment.
|
||||
* The final line of code fades that base color according to the heat value (acts as brightness multiplier).
|
||||
|
||||
The final piece of this custom effect returns the frame time:
|
||||
```cpp
|
||||
}
|
||||
return FRAMETIME;
|
||||
}
|
||||
```
|
||||
* The first bracket closes the earlier `if ((strip.now - SEGENV.step) >= refresh_ms)` block.
|
||||
* It ensures that the fire simulation (scrolling, sparking, diffusion, rendering) only runs when enough time has passed since the last update.
|
||||
* returning the frame time tells WLED how soon this effect wants to be called again.
|
||||
* `FRAMETIME` is a predefined macro in WLED, typically set to ~16ms, corresponding to ~60 FPS (frames per second).
|
||||
* Even though the effect logic itself controls when to update based on refresh_ms, WLED will still call this function at roughly FRAMETIME intervals to check whether an update is needed.
|
||||
* ⚠️ Important: Because the actual frame logic is gated by strip.now - SEGENV.step, returning FRAMETIME here doesn’t cause excessive updates — it just keeps the engine responsive. **Also note that an Effect should ALWAYS return FRAMETIME. Not doing so can cause glitches.**
|
||||
* The final bracket closes the `mode_diffusionfire()` function itself.
|
||||
* Even though the effect logic itself controls when to update based on refresh_ms, WLED will still call this function at roughly FRAMETIME intervals (the FPS limit set in config) to check whether an update is needed. If nothing needs to change, the frame still needs to be re-rendered so color or brightness transitions will be smooth.
|
||||
|
||||
If you want to run your effect at a fixed frame rate you can use the following code to not update your effect state, be aware however that transitions for your effect will also run at this frame rate - for example if you limit your effect to say 5 FPS, brightness changes and color changes may not look smooth. Also `SEGMENT.call` is still incremented on each function call.
|
||||
```cpp
|
||||
//limit update rate
|
||||
if (strip.now - SEGENV.step < FRAMETIME_FIXED) return;
|
||||
SEGENV.step = strip.now;
|
||||
```
|
||||
|
||||
### The Metadata String
|
||||
At the end of every effect is an important line of code called the **metadata string**.
|
||||
@@ -310,13 +318,13 @@ We will break this effect down step by step.
|
||||
(This effect was originally one of the FastLED example effects; more information on FastLED can be found [here](https://fastled.io/).)
|
||||
|
||||
```cpp
|
||||
static uint16_t sinelon_base(bool dual, bool rainbow=false) {
|
||||
static void sinelon_base(bool dual, bool rainbow=false) {
|
||||
```
|
||||
* The first line of code defines `sinelon base` as static helper function. This is how all effects are initially defined.
|
||||
* Notice that it has some optional flags; these parameters will allow us to easily define the effect in different ways in the UI.
|
||||
|
||||
```cpp
|
||||
if (SEGLEN <= 1) return mode_static();
|
||||
if (SEGLEN <= 1) FX_FALLBACK_STATIC;
|
||||
```
|
||||
* If segment length ≤ 1, there’s nothing to animate. Just show static mode.
|
||||
|
||||
@@ -396,28 +404,21 @@ This final part of the effect function will fill in the 'trailing' pixels to com
|
||||
* Works in both directions: Forward (if new pos > old pos), and Backward (if new pos < old pos).
|
||||
* Updates `SEGENV.aux0` to current position at the end.
|
||||
|
||||
Finally, we return the `FRAMETIME`, as with all effect functions:
|
||||
```cpp
|
||||
return FRAMETIME;
|
||||
}
|
||||
```
|
||||
* Returns `FRAMETIME` constant to set effect update rate (usually ~16 ms).
|
||||
|
||||
The last part of this effect has the Wrapper functions for different Sinelon modes.
|
||||
Notice that there are three different modes that we can define from the single effect definition by leveraging the arguments in the function:
|
||||
```cpp
|
||||
uint16_t mode_sinelon(void) {
|
||||
return sinelon_base(false);
|
||||
void mode_sinelon(void) {
|
||||
sinelon_base(false);
|
||||
}
|
||||
// Calls sinelon_base with dual = false and rainbow = false
|
||||
|
||||
uint16_t mode_sinelon_dual(void) {
|
||||
return sinelon_base(true);
|
||||
void mode_sinelon_dual(void) {
|
||||
sinelon_base(true);
|
||||
}
|
||||
// Calls sinelon_base with dual = true and rainbow = false
|
||||
|
||||
uint16_t mode_sinelon_rainbow(void) {
|
||||
return sinelon_base(false, true);
|
||||
void mode_sinelon_rainbow(void) {
|
||||
sinelon_base(false, true);
|
||||
}
|
||||
// Calls sinelon_base with dual = false and rainbow = true
|
||||
```
|
||||
|
||||
+1199
-6
File diff suppressed because it is too large
Load Diff
@@ -96,14 +96,14 @@ public:
|
||||
fastled_col.red = colPri[0];
|
||||
fastled_col.green = colPri[1];
|
||||
fastled_col.blue = colPri[2];
|
||||
prim_hsv = rgb2hsv_approximate(fastled_col);
|
||||
prim_hsv = rgb2hsv(fastled_col);
|
||||
new_val = (int16_t)prim_hsv.h + fadeAmount;
|
||||
if (new_val > 255)
|
||||
new_val -= 255; // roll-over if bigger than 255
|
||||
if (new_val < 0)
|
||||
new_val += 255; // roll-over if smaller than 0
|
||||
prim_hsv.h = (byte)new_val;
|
||||
hsv2rgb_rainbow(prim_hsv, fastled_col);
|
||||
fastled_col = prim_hsv ;
|
||||
colPri[0] = fastled_col.red;
|
||||
colPri[1] = fastled_col.green;
|
||||
colPri[2] = fastled_col.blue;
|
||||
@@ -121,14 +121,14 @@ public:
|
||||
fastled_col.red = colPri[0];
|
||||
fastled_col.green = colPri[1];
|
||||
fastled_col.blue = colPri[2];
|
||||
prim_hsv = rgb2hsv_approximate(fastled_col);
|
||||
prim_hsv = rgb2hsv(fastled_col);
|
||||
new_val = (int16_t)prim_hsv.h - fadeAmount;
|
||||
if (new_val > 255)
|
||||
new_val -= 255; // roll-over if bigger than 255
|
||||
if (new_val < 0)
|
||||
new_val += 255; // roll-over if smaller than 0
|
||||
prim_hsv.h = (byte)new_val;
|
||||
hsv2rgb_rainbow(prim_hsv, fastled_col);
|
||||
fastled_col = prim_hsv;
|
||||
colPri[0] = fastled_col.red;
|
||||
colPri[1] = fastled_col.green;
|
||||
colPri[2] = fastled_col.blue;
|
||||
|
||||
@@ -124,7 +124,7 @@ public:
|
||||
char objKey[14];
|
||||
bool parsed = false;
|
||||
|
||||
if (!requestJSONBufferLock(22)) return false;
|
||||
if (!requestJSONBufferLock(JSON_LOCK_REMOTE)) return false;
|
||||
|
||||
sprintf_P(objKey, PSTR("\"%d\":"), button);
|
||||
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
"name": "animartrix",
|
||||
"build": { "libArchive": false },
|
||||
"dependencies": {
|
||||
"Animartrix": "https://github.com/netmindz/animartrix.git#b172586"
|
||||
"Animartrix": "https://github.com/netmindz/animartrix.git#81eb09b91c8c9c8c01f8ea442787f8127d56c72f"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,266 +85,214 @@ class ANIMartRIXMod:public ANIMartRIX {
|
||||
};
|
||||
ANIMartRIXMod anim;
|
||||
|
||||
uint16_t mode_Module_Experiment10() {
|
||||
void mode_Module_Experiment10() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment10();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment9() {
|
||||
void mode_Module_Experiment9() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment9();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment8() {
|
||||
void mode_Module_Experiment8() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment8();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment7() {
|
||||
void mode_Module_Experiment7() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment7();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment6() {
|
||||
void mode_Module_Experiment6() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment6();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment5() {
|
||||
void mode_Module_Experiment5() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment5();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment4() {
|
||||
void mode_Module_Experiment4() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment4();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Zoom2() {
|
||||
void mode_Zoom2() {
|
||||
anim.initEffect();
|
||||
anim.Zoom2();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment3() {
|
||||
void mode_Module_Experiment3() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment3();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment2() {
|
||||
void mode_Module_Experiment2() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment2();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Module_Experiment1() {
|
||||
void mode_Module_Experiment1() {
|
||||
anim.initEffect();
|
||||
anim.Module_Experiment1();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Parametric_Water() {
|
||||
void mode_Parametric_Water() {
|
||||
anim.initEffect();
|
||||
anim.Parametric_Water();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Water() {
|
||||
void mode_Water() {
|
||||
anim.initEffect();
|
||||
anim.Water();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Complex_Kaleido_6() {
|
||||
void mode_Complex_Kaleido_6() {
|
||||
anim.initEffect();
|
||||
anim.Complex_Kaleido_6();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Complex_Kaleido_5() {
|
||||
void mode_Complex_Kaleido_5() {
|
||||
anim.initEffect();
|
||||
anim.Complex_Kaleido_5();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Complex_Kaleido_4() {
|
||||
void mode_Complex_Kaleido_4() {
|
||||
anim.initEffect();
|
||||
anim.Complex_Kaleido_4();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Complex_Kaleido_3() {
|
||||
void mode_Complex_Kaleido_3() {
|
||||
anim.initEffect();
|
||||
anim.Complex_Kaleido_3();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Complex_Kaleido_2() {
|
||||
void mode_Complex_Kaleido_2() {
|
||||
anim.initEffect();
|
||||
anim.Complex_Kaleido_2();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Complex_Kaleido() {
|
||||
void mode_Complex_Kaleido() {
|
||||
anim.initEffect();
|
||||
anim.Complex_Kaleido();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_SM10() {
|
||||
void mode_SM10() {
|
||||
anim.initEffect();
|
||||
anim.SM10();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_SM9() {
|
||||
void mode_SM9() {
|
||||
anim.initEffect();
|
||||
anim.SM9();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_SM8() {
|
||||
void mode_SM8() {
|
||||
anim.initEffect();
|
||||
anim.SM8();
|
||||
return FRAMETIME;
|
||||
}
|
||||
// uint16_t mode_SM7() {
|
||||
// void mode_SM7() {
|
||||
// anim.initEffect();
|
||||
// anim.SM7();
|
||||
//
|
||||
// return FRAMETIME;
|
||||
// }
|
||||
uint16_t mode_SM6() {
|
||||
void mode_SM6() {
|
||||
anim.initEffect();
|
||||
anim.SM6();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_SM5() {
|
||||
void mode_SM5() {
|
||||
anim.initEffect();
|
||||
anim.SM5();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_SM4() {
|
||||
void mode_SM4() {
|
||||
anim.initEffect();
|
||||
anim.SM4();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_SM3() {
|
||||
void mode_SM3() {
|
||||
anim.initEffect();
|
||||
anim.SM3();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_SM2() {
|
||||
void mode_SM2() {
|
||||
anim.initEffect();
|
||||
anim.SM2();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_SM1() {
|
||||
void mode_SM1() {
|
||||
anim.initEffect();
|
||||
anim.SM1();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Big_Caleido() {
|
||||
void mode_Big_Caleido() {
|
||||
anim.initEffect();
|
||||
anim.Big_Caleido();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_RGB_Blobs5() {
|
||||
void mode_RGB_Blobs5() {
|
||||
anim.initEffect();
|
||||
anim.RGB_Blobs5();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_RGB_Blobs4() {
|
||||
void mode_RGB_Blobs4() {
|
||||
anim.initEffect();
|
||||
anim.RGB_Blobs4();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_RGB_Blobs3() {
|
||||
void mode_RGB_Blobs3() {
|
||||
anim.initEffect();
|
||||
anim.RGB_Blobs3();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_RGB_Blobs2() {
|
||||
void mode_RGB_Blobs2() {
|
||||
anim.initEffect();
|
||||
anim.RGB_Blobs2();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_RGB_Blobs() {
|
||||
void mode_RGB_Blobs() {
|
||||
anim.initEffect();
|
||||
anim.RGB_Blobs();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Polar_Waves() {
|
||||
void mode_Polar_Waves() {
|
||||
anim.initEffect();
|
||||
anim.Polar_Waves();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Slow_Fade() {
|
||||
void mode_Slow_Fade() {
|
||||
anim.initEffect();
|
||||
anim.Slow_Fade();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Zoom() {
|
||||
void mode_Zoom() {
|
||||
anim.initEffect();
|
||||
anim.Zoom();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Hot_Blob() {
|
||||
void mode_Hot_Blob() {
|
||||
anim.initEffect();
|
||||
anim.Hot_Blob();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Spiralus2() {
|
||||
void mode_Spiralus2() {
|
||||
anim.initEffect();
|
||||
anim.Spiralus2();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Spiralus() {
|
||||
void mode_Spiralus() {
|
||||
anim.initEffect();
|
||||
anim.Spiralus();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Yves() {
|
||||
void mode_Yves() {
|
||||
anim.initEffect();
|
||||
anim.Yves();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Scaledemo1() {
|
||||
void mode_Scaledemo1() {
|
||||
anim.initEffect();
|
||||
anim.Scaledemo1();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Lava1() {
|
||||
void mode_Lava1() {
|
||||
anim.initEffect();
|
||||
anim.Lava1();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Caleido3() {
|
||||
void mode_Caleido3() {
|
||||
anim.initEffect();
|
||||
anim.Caleido3();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Caleido2() {
|
||||
void mode_Caleido2() {
|
||||
anim.initEffect();
|
||||
anim.Caleido2();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Caleido1() {
|
||||
void mode_Caleido1() {
|
||||
anim.initEffect();
|
||||
anim.Caleido1();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Distance_Experiment() {
|
||||
void mode_Distance_Experiment() {
|
||||
anim.initEffect();
|
||||
anim.Distance_Experiment();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Center_Field() {
|
||||
void mode_Center_Field() {
|
||||
anim.initEffect();
|
||||
anim.Center_Field();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Waves() {
|
||||
void mode_Waves() {
|
||||
anim.initEffect();
|
||||
anim.Waves();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Chasing_Spirals() {
|
||||
void mode_Chasing_Spirals() {
|
||||
anim.initEffect();
|
||||
anim.Chasing_Spirals();
|
||||
return FRAMETIME;
|
||||
}
|
||||
uint16_t mode_Rotating_Blob() {
|
||||
void mode_Rotating_Blob() {
|
||||
anim.initEffect();
|
||||
anim.Rotating_Blob();
|
||||
return FRAMETIME;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
// It can be configured to load auto saved preset at startup,
|
||||
// during the first `loop()`.
|
||||
//
|
||||
// By default it will not save the state if an unmodified preset
|
||||
// is selected (to not duplicate it). You can change this behaviour
|
||||
// by setting autoSaveIgnorePresets=false
|
||||
//
|
||||
// AutoSaveUsermod is standalone, but if FourLineDisplayUsermod
|
||||
// is installed, it will notify the user of the saved changes.
|
||||
|
||||
@@ -49,6 +53,8 @@ class AutoSaveUsermod : public Usermod {
|
||||
bool applyAutoSaveOnBoot = false; // do we load auto-saved preset on boot?
|
||||
#endif
|
||||
|
||||
bool autoSaveIgnorePresets = true; // ignore by default to not duplicate presets
|
||||
|
||||
// If we've detected the need to auto save, this will be non zero.
|
||||
unsigned long autoSaveAfter = 0;
|
||||
|
||||
@@ -68,6 +74,7 @@ class AutoSaveUsermod : public Usermod {
|
||||
static const char _autoSaveAfterSec[];
|
||||
static const char _autoSavePreset[];
|
||||
static const char _autoSaveApplyOnBoot[];
|
||||
static const char _autoSaveIgnorePresets[];
|
||||
|
||||
void inline saveSettings() {
|
||||
char presetNameBuffer[PRESET_NAME_BUFFER_SIZE];
|
||||
@@ -122,7 +129,8 @@ class AutoSaveUsermod : public Usermod {
|
||||
void loop() {
|
||||
static unsigned long lastRun = 0;
|
||||
unsigned long now = millis();
|
||||
if (!autoSaveAfterSec || !enabled || currentPreset>0 || (strip.isUpdating() && now - lastRun < 240)) return; // setting 0 as autosave seconds disables autosave
|
||||
if (!autoSaveAfterSec || !enabled || (autoSaveIgnorePresets && currentPreset>0) || (strip.isUpdating() && now - lastRun < 240)) return; // setting 0 as autosave seconds disables autosave
|
||||
lastRun = now;
|
||||
uint8_t currentMode = strip.getMainSegment().mode;
|
||||
uint8_t currentPalette = strip.getMainSegment().palette;
|
||||
|
||||
@@ -219,10 +227,11 @@ class AutoSaveUsermod : public Usermod {
|
||||
void addToConfig(JsonObject& root) {
|
||||
// we add JSON object: {"Autosave": {"autoSaveAfterSec": 10, "autoSavePreset": 99}}
|
||||
JsonObject top = root.createNestedObject(FPSTR(_name)); // usermodname
|
||||
top[FPSTR(_autoSaveEnabled)] = enabled;
|
||||
top[FPSTR(_autoSaveAfterSec)] = autoSaveAfterSec; // usermodparam
|
||||
top[FPSTR(_autoSavePreset)] = autoSavePreset; // usermodparam
|
||||
top[FPSTR(_autoSaveApplyOnBoot)] = applyAutoSaveOnBoot;
|
||||
top[FPSTR(_autoSaveEnabled)] = enabled;
|
||||
top[FPSTR(_autoSaveAfterSec)] = autoSaveAfterSec; // usermodparam
|
||||
top[FPSTR(_autoSavePreset)] = autoSavePreset; // usermodparam
|
||||
top[FPSTR(_autoSaveApplyOnBoot)] = applyAutoSaveOnBoot;
|
||||
top[FPSTR(_autoSaveIgnorePresets)] = autoSaveIgnorePresets;
|
||||
DEBUG_PRINTLN(F("Autosave config saved."));
|
||||
}
|
||||
|
||||
@@ -245,12 +254,13 @@ class AutoSaveUsermod : public Usermod {
|
||||
return false;
|
||||
}
|
||||
|
||||
enabled = top[FPSTR(_autoSaveEnabled)] | enabled;
|
||||
autoSaveAfterSec = top[FPSTR(_autoSaveAfterSec)] | autoSaveAfterSec;
|
||||
autoSaveAfterSec = (uint16_t) min(3600,max(10,(int)autoSaveAfterSec)); // bounds checking
|
||||
autoSavePreset = top[FPSTR(_autoSavePreset)] | autoSavePreset;
|
||||
autoSavePreset = (uint8_t) min(250,max(100,(int)autoSavePreset)); // bounds checking
|
||||
applyAutoSaveOnBoot = top[FPSTR(_autoSaveApplyOnBoot)] | applyAutoSaveOnBoot;
|
||||
enabled = top[FPSTR(_autoSaveEnabled)] | enabled;
|
||||
autoSaveAfterSec = top[FPSTR(_autoSaveAfterSec)] | autoSaveAfterSec;
|
||||
autoSaveAfterSec = (uint16_t) min(3600,max(10,(int)autoSaveAfterSec)); // bounds checking
|
||||
autoSavePreset = top[FPSTR(_autoSavePreset)] | autoSavePreset;
|
||||
autoSavePreset = (uint8_t) min(250,max(100,(int)autoSavePreset)); // bounds checking
|
||||
applyAutoSaveOnBoot = top[FPSTR(_autoSaveApplyOnBoot)] | applyAutoSaveOnBoot;
|
||||
autoSaveIgnorePresets = top[FPSTR(_autoSaveIgnorePresets)] | autoSaveIgnorePresets;
|
||||
DEBUG_PRINT(FPSTR(_name));
|
||||
DEBUG_PRINTLN(F(" config (re)loaded."));
|
||||
|
||||
@@ -268,11 +278,12 @@ class AutoSaveUsermod : public Usermod {
|
||||
};
|
||||
|
||||
// strings to reduce flash memory usage (used more than twice)
|
||||
const char AutoSaveUsermod::_name[] PROGMEM = "Autosave";
|
||||
const char AutoSaveUsermod::_autoSaveEnabled[] PROGMEM = "enabled";
|
||||
const char AutoSaveUsermod::_autoSaveAfterSec[] PROGMEM = "autoSaveAfterSec";
|
||||
const char AutoSaveUsermod::_autoSavePreset[] PROGMEM = "autoSavePreset";
|
||||
const char AutoSaveUsermod::_autoSaveApplyOnBoot[] PROGMEM = "autoSaveApplyOnBoot";
|
||||
const char AutoSaveUsermod::_name[] PROGMEM = "Autosave";
|
||||
const char AutoSaveUsermod::_autoSaveEnabled[] PROGMEM = "enabled";
|
||||
const char AutoSaveUsermod::_autoSaveAfterSec[] PROGMEM = "autoSaveAfterSec";
|
||||
const char AutoSaveUsermod::_autoSavePreset[] PROGMEM = "autoSavePreset";
|
||||
const char AutoSaveUsermod::_autoSaveApplyOnBoot[] PROGMEM = "autoSaveApplyOnBoot";
|
||||
const char AutoSaveUsermod::_autoSaveIgnorePresets[] PROGMEM = "autoSaveIgnorePresets";
|
||||
|
||||
static AutoSaveUsermod autosave;
|
||||
REGISTER_USERMOD(autosave);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,276 +0,0 @@
|
||||
#pragma once
|
||||
#include "wled.h"
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
|
||||
#include <TFT_eSPI.h>
|
||||
#include <SPI.h>
|
||||
|
||||
// Pin definitions - use TFT_eSPI definitions when available
|
||||
#ifndef TFT_CS
|
||||
#define TFT_CS 5 // Default fallback
|
||||
#endif
|
||||
#define GC9A01_CS_PIN TFT_CS
|
||||
|
||||
#ifndef TFT_DC
|
||||
#define TFT_DC 16 // Default fallback
|
||||
#endif
|
||||
#define GC9A01_DC_PIN TFT_DC
|
||||
|
||||
#ifndef TFT_RST
|
||||
#define TFT_RST 17 // Default fallback
|
||||
#endif
|
||||
#define GC9A01_RST_PIN TFT_RST
|
||||
|
||||
// Use TFT_eSPI's backlight pin definition
|
||||
#ifndef TFT_BL
|
||||
#define TFT_BL 4 // Default fallback if not defined by TFT_eSPI
|
||||
#endif
|
||||
|
||||
#ifndef USERMOD_ID_GC9A01_DISPLAY
|
||||
#define USERMOD_ID_GC9A01_DISPLAY 59 // Use the official ID from const.h
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Create the UsermodGC9A01Display singleton instance if one does not already exist.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Return the singleton instance of UsermodGC9A01Display.
|
||||
* @returns Pointer to the singleton instance, or nullptr if not constructed.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Initialize the TFT display hardware and internal display state.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Render the main interface. If overlayMode is >= 0, render the specified overlay instead of the normal UI.
|
||||
* @param overlayMode Overlay mode to render, or -1 to render the normal interface.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Draw the WLED logo on the display.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Draw a WiFi connectivity icon at the specified position.
|
||||
* @param x X coordinate in pixels.
|
||||
* @param y Y coordinate in pixels.
|
||||
* @param connected `true` to render as connected, `false` to render as disconnected.
|
||||
* @param rssi RSSI value to reflect signal strength (optional).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Set display brightness used for UI elements and indicators.
|
||||
* @param bri Brightness value (0-255).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Set the physical backlight level as a percentage.
|
||||
* @param percent Backlight brightness percentage (0-100).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Switch display between sleep behavior and clock-only behavior based on `enabled`.
|
||||
* @param enabled If `true`, enable clock/sleep behavior; if `false`, disable it.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Put the display into a low-power or off state.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Wake the display from sleep if it is sleeping.
|
||||
* @returns `true` if the display was sleeping and was woken, `false` otherwise.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Render the clock-only screen.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Render the current mode overlay (mode-specific information).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Draw an indicator for the currently active WLED mode.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Return a human-readable name for the given encoder mode.
|
||||
* @param mode Encoder mode identifier.
|
||||
* @returns Null-terminated string describing the mode.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Wake the display if it is sleeping.
|
||||
* @returns `true` if the display was sleeping and was woken, `false` otherwise.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Reset or update the inactivity timer to prevent the display from timing out.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Show a temporary overlay with a single line of text and optional glyph.
|
||||
* @param line1 Null-terminated string to display.
|
||||
* @param showHowLong Duration in milliseconds to show the overlay.
|
||||
* @param glyphType Optional glyph type identifier (default 0).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Trigger a display redraw.
|
||||
* @param forceRedraw If `true`, redraw regardless of internal change tracking.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check whether an overlay is currently active.
|
||||
* @returns `true` if an overlay is active, `false` otherwise.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the currently active overlay mode.
|
||||
* @returns Active overlay mode number, or -1 if none is active.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check whether the display is currently asleep.
|
||||
* @returns `true` if the display is sleeping, `false` otherwise.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Usermod setup hook called once after initialization to configure the display and state.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Usermod loop hook called regularly to handle updates, timeouts, and redraw scheduling.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Append informational state about the display to the provided JSON object.
|
||||
* @param root JSON object to which information will be added.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Read transient state values from JSON (runtime state).
|
||||
* @param root JSON object containing state values.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Append transient state values to JSON (runtime state).
|
||||
* @param root JSON object to populate with state values.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Read persistent configuration for the display from JSON.
|
||||
* @param root JSON object containing configuration.
|
||||
* @returns `true` if configuration was successfully read, `false` otherwise.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Append persistent configuration for the display to JSON.
|
||||
* @param root JSON object to populate with configuration values.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Append additional configuration data to the global configuration payload.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Return the unique usermod ID for this display usermod.
|
||||
* @returns Numeric usermod ID.
|
||||
*/
|
||||
class UsermodGC9A01Display : public Usermod {
|
||||
private:
|
||||
// Singleton pattern - allows rotary encoder usermod to find us
|
||||
static UsermodGC9A01Display* instance;
|
||||
|
||||
public:
|
||||
UsermodGC9A01Display() { if (!instance) instance = this; }
|
||||
static UsermodGC9A01Display* getInstance(void) { return instance; }
|
||||
|
||||
private:
|
||||
TFT_eSPI tft = TFT_eSPI();
|
||||
|
||||
bool displayEnabled = true;
|
||||
bool needsRedraw = true;
|
||||
bool displayTurnedOff = false;
|
||||
bool showingWelcomeScreen = true;
|
||||
bool showingClock = false; // Track if currently showing clock (for rotary encoder state reset)
|
||||
unsigned long welcomeScreenStartTime = 0;
|
||||
uint8_t backlight = 75; // Backlight brightness percentage (0-100%, default 75%)
|
||||
uint16_t displayTimeout = 60000; // 60 seconds default
|
||||
bool sleepMode = true; // Enable sleep mode by default
|
||||
bool clockMode = false; // Show clock only when idle
|
||||
bool flip = false; // Display rotation (0 or 2)
|
||||
bool clock12hour = false; // false = 24h format, true = 12h format with AM/PM
|
||||
|
||||
// Proper state tracking like 4-line display usermod
|
||||
uint8_t knownBrightness = 255;
|
||||
uint8_t knownMode = 255;
|
||||
uint8_t knownPalette = 255;
|
||||
uint8_t knownEffectSpeed = 255;
|
||||
uint8_t knownEffectIntensity = 255;
|
||||
uint32_t knownColor = 0; // colors[0] - Primary/FX
|
||||
uint32_t knownBgColor = 0; // colors[1] - Secondary/BG
|
||||
uint32_t knownCustomColor = 0; // colors[2] - Tertiary/CS
|
||||
bool knownPowerState = true;
|
||||
unsigned long nextUpdate = 0;
|
||||
unsigned long lastRedraw = ULONG_MAX; // Initialize to max value - sleep timer starts after first interaction
|
||||
uint16_t refreshRate = 1000; // Match 4-line display usermod (1 second) for better performance
|
||||
|
||||
// Time tracking for display updates
|
||||
uint8_t knownMinute = 99;
|
||||
uint8_t knownHour = 99;
|
||||
|
||||
// Integration with rotary encoder usermod (no direct pin handling)
|
||||
unsigned long overlayUntil = 0; // When overlay should expire (millis)
|
||||
int activeOverlayMode = -1; // Which overlay mode is active (-1 = none, 0-4 = overlay modes)
|
||||
unsigned long overlayInactivityTimeout = 3000; // 3 seconds of inactivity before returning to main screen
|
||||
String overlayText = "";
|
||||
|
||||
// Private method declarations
|
||||
void initDisplay();
|
||||
void drawMainInterface(int overlayMode = -1); // -1 = normal, 0+ = overlay mode
|
||||
void drawWLEDLogo();
|
||||
void drawWiFiIcon(int x, int y, bool connected, int rssi = 0);
|
||||
void setBrightness(uint8_t bri);
|
||||
void setBacklight(uint8_t percent); // Set backlight brightness (0-100%)
|
||||
void sleepOrClock(bool enabled); // Sleep display or show clock based on settings
|
||||
void sleepDisplay();
|
||||
bool wakeDisplayFromSleep(); // Return true if display was sleeping
|
||||
void drawClockScreen(); // Clock-only display mode
|
||||
|
||||
// Mode-specific drawing methods
|
||||
void drawModeOverlay();
|
||||
void drawCurrentModeIndicator();
|
||||
|
||||
// Get encoder state from rotary encoder usermod
|
||||
const char* getEncoderModeName(uint8_t mode);
|
||||
|
||||
public:
|
||||
|
||||
// Public interface methods for rotary encoder usermod (like 4-line display)
|
||||
bool wakeDisplay(); // Return true if was sleeping
|
||||
void updateRedrawTime(); // Prevent display timeout
|
||||
void overlay(const char* line1, long showHowLong, byte glyphType = 0); // Match 4-line interface
|
||||
void redraw(bool forceRedraw); // Force display update
|
||||
bool isOverlayActive(); // Check if overlay is currently showing
|
||||
int getActiveOverlayMode(); // Get current overlay mode (-1 = none)
|
||||
bool isDisplayAsleep(); // Check if display is sleeping
|
||||
|
||||
// Usermod API
|
||||
// Public method declarations (Usermod interface)
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
void addToJsonInfo(JsonObject& root) override;
|
||||
void readFromJsonState(JsonObject& root) override;
|
||||
void addToJsonState(JsonObject& root) override;
|
||||
bool readFromConfig(JsonObject& root) override;
|
||||
void addToConfig(JsonObject& root) override;
|
||||
void appendConfigData() override;
|
||||
uint16_t getId() override;
|
||||
};
|
||||
|
||||
#endif // USERMOD_GC9A01_DISPLAY
|
||||
@@ -31,10 +31,6 @@
|
||||
#include "usermod_v2_four_line_display.h"
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
#include "../usermod_v2_gc9a01_display/usermod_v2_gc9a01_display.h"
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_MODE_SORT
|
||||
#error "Usermod Mode Sort is no longer required. Remove -D USERMOD_MODE_SORT from platformio.ini"
|
||||
#endif
|
||||
@@ -182,12 +178,6 @@ class RotaryEncoderUIUsermod : public Usermod {
|
||||
void* display;
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
UsermodGC9A01Display *gc9a01Display;
|
||||
#else
|
||||
void* gc9a01Display;
|
||||
#endif
|
||||
|
||||
// Pointers the start of the mode names within JSON_mode_names
|
||||
const char **modes_qstrings;
|
||||
|
||||
@@ -261,16 +251,6 @@ class RotaryEncoderUIUsermod : public Usermod {
|
||||
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Construct a RotaryEncoderUIUsermod with default runtime configuration.
|
||||
*
|
||||
* Initializes internal state and safe defaults for pins, UI state, color values,
|
||||
* effect/palette indices, display pointers, preset ranges, and feature flags.
|
||||
*
|
||||
* The constructor does not allocate hardware resources or register interrupts;
|
||||
* it only sets member variables to their default values so setup() can perform
|
||||
* initialization later.
|
||||
*/
|
||||
RotaryEncoderUIUsermod()
|
||||
: fadeAmount(5)
|
||||
, buttonPressedTime(0)
|
||||
@@ -285,7 +265,6 @@ class RotaryEncoderUIUsermod : public Usermod {
|
||||
, currentSat1(255)
|
||||
, currentCCT(128)
|
||||
, display(nullptr)
|
||||
, gc9a01Display(nullptr)
|
||||
, modes_qstrings(nullptr)
|
||||
, modes_alpha_indexes(nullptr)
|
||||
, palettes_qstrings(nullptr)
|
||||
@@ -422,19 +401,19 @@ void RotaryEncoderUIUsermod::sortModesAndPalettes() {
|
||||
re_sortModes(modes_qstrings, modes_alpha_indexes, strip.getModeCount(), MODE_SORT_SKIP_COUNT);
|
||||
|
||||
DEBUG_PRINT(F("Sorting palettes: ")); DEBUG_PRINT(getPaletteCount()); DEBUG_PRINT('/'); DEBUG_PRINTLN(customPalettes.size());
|
||||
palettes_qstrings = re_findModeStrings(JSON_palette_names, getPaletteCount());
|
||||
palettes_alpha_indexes = re_initIndexArray(getPaletteCount());
|
||||
palettes_qstrings = re_findModeStrings(JSON_palette_names, getPaletteCount()); // allocates memory for all palette names
|
||||
palettes_alpha_indexes = re_initIndexArray(getPaletteCount()); // allocates memory for all palette indexes
|
||||
if (customPalettes.size()) {
|
||||
for (int i=0; i<customPalettes.size(); i++) {
|
||||
palettes_alpha_indexes[getPaletteCount()-customPalettes.size()+i] = 255-i;
|
||||
palettes_qstrings[getPaletteCount()-customPalettes.size()+i] = PSTR("~Custom~");
|
||||
palettes_alpha_indexes[FIXED_PALETTE_COUNT+i] = 255-i;
|
||||
palettes_qstrings[FIXED_PALETTE_COUNT+i] = PSTR("~Custom~");
|
||||
}
|
||||
}
|
||||
// How many palette names start with '*' and should not be sorted?
|
||||
// (Also skipping the first one, 'Default').
|
||||
int skipPaletteCount = 1;
|
||||
while (pgm_read_byte_near(palettes_qstrings[skipPaletteCount]) == '*') skipPaletteCount++;
|
||||
re_sortModes(palettes_qstrings, palettes_alpha_indexes, getPaletteCount()-customPalettes.size(), skipPaletteCount);
|
||||
int skipPaletteCount = 1; // could use DYNAMIC_PALETTE_COUNT instead
|
||||
while (pgm_read_byte_near(palettes_qstrings[skipPaletteCount]) == '*') skipPaletteCount++; // legacy code
|
||||
re_sortModes(palettes_qstrings, palettes_alpha_indexes, FIXED_PALETTE_COUNT, skipPaletteCount); // only sort fixed palettes (skip dynamic)
|
||||
}
|
||||
|
||||
byte *RotaryEncoderUIUsermod::re_initIndexArray(int numModes) {
|
||||
@@ -498,19 +477,10 @@ void RotaryEncoderUIUsermod::re_sortModes(const char **modeNames, byte *indexes,
|
||||
// public methods
|
||||
|
||||
|
||||
/**
|
||||
* @brief Initialize rotary-encoder UI: configure pins, optional PCF8574/I2C interrupt,
|
||||
* integrate available displays, and cache initial encoder state.
|
||||
*
|
||||
* Performs all startup setup required by the usermod: allocates and configures GPIO
|
||||
* pins or a PCF8574 I/O expander (including attaching an IRQ handler if requested),
|
||||
* sets pin modes, sorts mode/palette lists if needed, discovers and initializes
|
||||
* optional display usermods (FourLineDisplay or GC9A01), computes initial CCT, and
|
||||
* reads the encoder A/B inputs to prime internal state.
|
||||
*
|
||||
* If required pins, the IRQ, or I2C resources cannot be allocated, the usermod
|
||||
* disables itself. This runs once at boot before WiFi is connected.
|
||||
*/
|
||||
/*
|
||||
* setup() is called once at boot. WiFi is not yet connected at this point.
|
||||
* You can use it to initialize variables, sensors or similar.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::setup()
|
||||
{
|
||||
DEBUG_PRINTLN(F("Usermod Rotary Encoder init."));
|
||||
@@ -563,34 +533,22 @@ void RotaryEncoderUIUsermod::setup()
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
// This Usermod also works with GC9A01DisplayUsermod for round TFT displays.
|
||||
gc9a01Display = (UsermodGC9A01Display*) UsermodManager::lookup(USERMOD_ID_GC9A01_DISPLAY);
|
||||
if (gc9a01Display != nullptr) {
|
||||
DEBUG_PRINTLN(F("[RotaryEncoder] GC9A01 display integration enabled"));
|
||||
} else {
|
||||
DEBUG_PRINTLN(F("[RotaryEncoder] GC9A01 display NOT FOUND"));
|
||||
}
|
||||
#endif
|
||||
|
||||
initDone = true;
|
||||
Enc_A = readPin(pinA); // Read encoder pins
|
||||
Enc_B = readPin(pinB);
|
||||
Enc_A_prev = Enc_A;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Polls the rotary encoder and button, updates the current UI state, and applies the selected adjustments (brightness, effect, speed, intensity, palette, hue, saturation, CCT, presets, and custom parameters).
|
||||
*
|
||||
* @details
|
||||
* - Debounces and rate-limits encoder/button processing; uses ENCODER_MAX_DELAY_MS to avoid excessive polling.
|
||||
* - Detects short press (cycles UI state), double-press (toggles output state), and long-press (shows network information).
|
||||
* - When the active UI state changes, requests or updates an overlay on any attached display(s); handles GC9A01-specific overlay expiration and display sleep by reverting to the brightness state when needed.
|
||||
* - Validates that sliders (speed, intensity, custom) are supported by the current effect and resets to brightness if not supported.
|
||||
* - Translates encoder rotations into the appropriate change action for the current UI state and applies those changes to the LED segments and displays.
|
||||
*
|
||||
* Side effects: updates internal select_state, modifies strip/segment state, may wake/redraw displays, and triggers lamp/LED updates.
|
||||
*/
|
||||
/*
|
||||
* loop() is called continuously. Here you can check for events, read sensors, etc.
|
||||
*
|
||||
* Tips:
|
||||
* 1. You can use "if (WLED_CONNECTED)" to check for a successful network connection.
|
||||
* Additionally, "if (WLED_MQTT_CONNECTED)" is available to check for a connection to an MQTT broker.
|
||||
*
|
||||
* 2. Try to avoid using the delay() function. NEVER use delays longer than 10 milliseconds.
|
||||
* Instead, use a timer check as shown here.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::loop()
|
||||
{
|
||||
if (!enabled) return;
|
||||
@@ -660,59 +618,25 @@ void RotaryEncoderUIUsermod::loop()
|
||||
}
|
||||
if (newState > LAST_UI_STATE) newState = 0;
|
||||
} while (!changedState);
|
||||
// Support both Four Line Display and GC9A01 display
|
||||
if (display != nullptr || gc9a01Display != nullptr) {
|
||||
// Special handling for state 0 (Brightness) with GC9A01 - no overlay needed
|
||||
if (newState == 0 && gc9a01Display != nullptr && display == nullptr) {
|
||||
// For GC9A01 only (no four line display), just update main screen for brightness
|
||||
if (gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
changedState = false; // Throw away wake up input
|
||||
} else {
|
||||
gc9a01Display->redraw(false); // Update main screen directly
|
||||
changedState = true;
|
||||
}
|
||||
} else {
|
||||
// Normal overlay handling for all other states and for Four Line Display
|
||||
switch (newState) {
|
||||
case 0: changedState = changeState(lineBuffer, 1, 0, 1); break; //1 = sun
|
||||
case 1: changedState = changeState(lineBuffer, 1, 4, 2); break; //2 = skip forward
|
||||
case 2: changedState = changeState(lineBuffer, 1, 8, 3); break; //3 = fire
|
||||
case 3: changedState = changeState(lineBuffer, 2, 0, 4); break; //4 = custom palette
|
||||
case 4: changedState = changeState(lineBuffer, 3, 0, 5); break; //5 = puzzle piece
|
||||
case 5: changedState = changeState(lineBuffer, 255, 255, 7); break; //7 = brush
|
||||
case 6: changedState = changeState(lineBuffer, 255, 255, 8); break; //8 = contrast
|
||||
case 7: changedState = changeState(lineBuffer, 255, 255, 10); break; //10 = star
|
||||
case 8: changedState = changeState(lineBuffer, 255, 255, 11); break; //11 = heart
|
||||
case 9: changedState = changeState(lineBuffer, 255, 255, 10); break; //10 = star
|
||||
case 10: changedState = changeState(lineBuffer, 255, 255, 10); break; //10 = star
|
||||
case 11: changedState = changeState(lineBuffer, 255, 255, 10); break; //10 = star
|
||||
}
|
||||
if (display != nullptr) {
|
||||
switch (newState) {
|
||||
case 0: changedState = changeState(lineBuffer, 1, 0, 1); break; //1 = sun
|
||||
case 1: changedState = changeState(lineBuffer, 1, 4, 2); break; //2 = skip forward
|
||||
case 2: changedState = changeState(lineBuffer, 1, 8, 3); break; //3 = fire
|
||||
case 3: changedState = changeState(lineBuffer, 2, 0, 4); break; //4 = custom palette
|
||||
case 4: changedState = changeState(lineBuffer, 3, 0, 5); break; //5 = puzzle piece
|
||||
case 5: changedState = changeState(lineBuffer, 255, 255, 7); break; //7 = brush
|
||||
case 6: changedState = changeState(lineBuffer, 255, 255, 8); break; //8 = contrast
|
||||
case 7: changedState = changeState(lineBuffer, 255, 255, 10); break; //10 = star
|
||||
case 8: changedState = changeState(lineBuffer, 255, 255, 11); break; //11 = heart
|
||||
case 9: changedState = changeState(lineBuffer, 255, 255, 10); break; //10 = star
|
||||
case 10: changedState = changeState(lineBuffer, 255, 255, 10); break; //10 = star
|
||||
case 11: changedState = changeState(lineBuffer, 255, 255, 10); break; //10 = star
|
||||
}
|
||||
}
|
||||
if (changedState) select_state = newState;
|
||||
}
|
||||
|
||||
// Check if GC9A01 overlay has expired or display is asleep and reset to brightness mode (state 0)
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display != nullptr && select_state > 0) {
|
||||
if (!gc9a01Display->isOverlayActive() || gc9a01Display->isDisplayAsleep()) {
|
||||
// Overlay has expired or display is asleep, return to brightness mode
|
||||
select_state = 0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Check if current state is valid for current effect (for states 1=speed, 2=intensity, 9-11=custom)
|
||||
if (select_state == 1 || select_state == 2 || (select_state >= 9 && select_state <= 11)) {
|
||||
char tempBuffer[64];
|
||||
int sliderIndex = (select_state <= 2) ? (select_state - 1) : (select_state - 7);
|
||||
if (!extractModeSlider(effectCurrent, sliderIndex, tempBuffer, 63)) {
|
||||
// Current effect doesn't have this slider, reset to brightness
|
||||
select_state = 0;
|
||||
}
|
||||
}
|
||||
|
||||
Enc_A = readPin(pinA); // Read encoder pins
|
||||
Enc_B = readPin(pinB);
|
||||
if ((Enc_A) && (!Enc_A_prev))
|
||||
@@ -757,32 +681,12 @@ void RotaryEncoderUIUsermod::loop()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Show a temporary "NETWORK INFO" overlay on any attached display.
|
||||
*
|
||||
* Displays a "NETWORK INFO" overlay for 10 seconds on supported displays.
|
||||
* When a GC9A01 display is present, the overlay uses the network glyph.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::displayNetworkInfo() {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
display->networkOverlay(PSTR("NETWORK INFO"), 10000);
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display != nullptr) {
|
||||
gc9a01Display->overlay(PSTR("NETWORK INFO"), 10000, 12); // Use network glyph
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Resolve and cache the indices of the currently active effect and palette for UI navigation.
|
||||
*
|
||||
* Searches available modes and palettes to determine the display indices corresponding to
|
||||
* the current effect and palette identifiers, stores the resolved indices in
|
||||
* `effectCurrentIndex` and `effectPaletteIndex`, and marks `currentEffectAndPaletteInitialized`.
|
||||
* If no match is found for either, the corresponding index is set to 0.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::findCurrentEffectAndPalette() {
|
||||
DEBUG_PRINTLN(F("Finding current mode and palette."));
|
||||
currentEffectAndPaletteInitialized = true;
|
||||
@@ -798,7 +702,7 @@ void RotaryEncoderUIUsermod::findCurrentEffectAndPalette() {
|
||||
|
||||
effectPaletteIndex = 0;
|
||||
DEBUG_PRINTLN(effectPalette);
|
||||
for (unsigned i = 0; i < getPaletteCount(); i++) {
|
||||
for (unsigned i = 0; i < getPaletteCount()+customPalettes.size(); i++) {
|
||||
if (palettes_alpha_indexes[i] == effectPalette) {
|
||||
effectPaletteIndex = i;
|
||||
DEBUG_PRINTLN(F("Found palette."));
|
||||
@@ -807,18 +711,6 @@ void RotaryEncoderUIUsermod::findCurrentEffectAndPalette() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Show a short-term UI overlay on any attached display and optionally mark a line/column.
|
||||
*
|
||||
* Displays the given text with an optional glyph on the integrated FourLineDisplay and/or GC9A01 display.
|
||||
* If a display was sleeping and is awakened by this call, the wake is consumed (a redraw is performed) and the overlay is not shown.
|
||||
*
|
||||
* @param stateName Text to show in the overlay.
|
||||
* @param markedLine Line index to mark on the FourLineDisplay (ignored if not applicable).
|
||||
* @param markedCol Column index to mark on the FourLineDisplay (ignored if not applicable).
|
||||
* @param glyph Glyph index to display alongside the text (display-dependent).
|
||||
* @return true if the overlay was actually shown, false if a display wake-up was consumed instead.
|
||||
*/
|
||||
bool RotaryEncoderUIUsermod::changeState(const char *stateName, byte markedLine, byte markedCol, byte glyph) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display != nullptr) {
|
||||
@@ -831,20 +723,6 @@ bool RotaryEncoderUIUsermod::changeState(const char *stateName, byte markedLine,
|
||||
display->setMarkLine(markedLine, markedCol);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display != nullptr) {
|
||||
DEBUG_PRINTF("[RotaryEncoder] Calling GC9A01 overlay: '%s' glyph=%d\n", stateName, glyph);
|
||||
if (gc9a01Display->wakeDisplay()) {
|
||||
// Throw away wake up input
|
||||
gc9a01Display->redraw(true);
|
||||
return false;
|
||||
}
|
||||
gc9a01Display->overlay(stateName, 750, glyph);
|
||||
} else {
|
||||
DEBUG_PRINTLN(F("[RotaryEncoder] gc9a01Display is NULL!"));
|
||||
}
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -856,17 +734,6 @@ void RotaryEncoderUIUsermod::lampUdated() {
|
||||
updateInterfaces(CALL_MODE_BUTTON);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Adjusts the global brightness up or down and updates attached displays.
|
||||
*
|
||||
* Changes the global brightness by a configured step, using smaller steps when the
|
||||
* current brightness is below 40 to provide finer control at low levels. After
|
||||
* changing brightness the method notifies the system of the update and refreshes
|
||||
* any attached displays; display behavior will present an overlay or update the
|
||||
* main screen depending on the active UI state and the specific display type.
|
||||
*
|
||||
* @param increase True to increase brightness, false to decrease it.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changeBrightness(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -876,16 +743,6 @@ void RotaryEncoderUIUsermod::changeBrightness(bool increase) {
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
//bri = max(min((increase ? bri+fadeAmount : bri-fadeAmount), 255), 0);
|
||||
if (bri < 40) bri = max(min((increase ? bri+fadeAmount/2 : bri-fadeAmount/2), 255), 0); // slower steps when brightness < 16%
|
||||
else bri = max(min((increase ? bri+fadeAmount : bri-fadeAmount), 255), 0);
|
||||
@@ -893,34 +750,9 @@ void RotaryEncoderUIUsermod::changeBrightness(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
display->updateBrightness();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
// Only show overlay if we're NOT in default state (state 0)
|
||||
// In state 0, brightness changes should update the main screen directly
|
||||
if (select_state == 0) {
|
||||
gc9a01Display->redraw(false); // Update main interface directly (no overlay)
|
||||
} else {
|
||||
// Show brightness overlay like other modes (when in overlay mode)
|
||||
char brightnessStr[16];
|
||||
sprintf(brightnessStr, "Brightness %d%%", (bri * 100) / 255);
|
||||
gc9a01Display->overlay(brightnessStr, 500, 10);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Change the currently selected effect and apply it to segments.
|
||||
*
|
||||
* Updates the internal effect index (clamped to the available mode range), sets the selected
|
||||
* effect on either all active segments or just the main segment depending on `applyToAll`,
|
||||
* marks the usermod state as changed, triggers a lamp update, and refreshes any attached
|
||||
* displays (FourLineDisplay or GC9A01) including wake/overlay handling.
|
||||
*
|
||||
* @param increase `true` to advance to the next effect, `false` to go to the previous effect.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changeEffect(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -930,15 +762,6 @@ void RotaryEncoderUIUsermod::changeEffect(bool increase) {
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
effectCurrentIndex = max(min((increase ? effectCurrentIndex+1 : effectCurrentIndex-1), strip.getModeCount()-1), 0);
|
||||
effectCurrent = modes_alpha_indexes[effectCurrentIndex];
|
||||
stateChanged = true;
|
||||
@@ -959,15 +782,6 @@ void RotaryEncoderUIUsermod::changeEffect(bool increase) {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Adjusts the global effect speed and applies the change to segments and displays.
|
||||
*
|
||||
* Updates the stored effect speed by adding or subtracting the configured step (clamped to 0–255),
|
||||
* marks the state as changed, applies the new speed to either all active segments or the main segment
|
||||
* depending on the `applyToAll` flag, notifies the system of the update, and refreshes any attached displays.
|
||||
*
|
||||
* @param increase If `true`, increases the effect speed; if `false`, decreases it.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changeEffectSpeed(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -977,16 +791,6 @@ void RotaryEncoderUIUsermod::changeEffectSpeed(bool increase) {
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
effectSpeed = max(min((increase ? effectSpeed+fadeAmount : effectSpeed-fadeAmount), 255), 0);
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
@@ -1003,24 +807,9 @@ void RotaryEncoderUIUsermod::changeEffectSpeed(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
display->updateSpeed();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
gc9a01Display->redraw(false); // Update speed display
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Adjusts the current effect intensity up or down and applies the change to segments and UI.
|
||||
*
|
||||
* Updates the stored effect intensity by one step (bounded to 0–255), marks state as changed,
|
||||
* applies the new intensity to either all active segments or the main segment depending on configuration,
|
||||
* notifies the system of the update, and refreshes any attached display overlays.
|
||||
*
|
||||
* @param increase If `true`, increase intensity; if `false`, decrease intensity.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changeEffectIntensity(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -1030,16 +819,6 @@ void RotaryEncoderUIUsermod::changeEffectIntensity(bool increase) {
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
effectIntensity = max(min((increase ? effectIntensity+fadeAmount : effectIntensity-fadeAmount), 255), 0);
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
@@ -1056,29 +835,9 @@ void RotaryEncoderUIUsermod::changeEffectIntensity(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
display->updateIntensity();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
gc9a01Display->redraw(false); // Update intensity display
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Adjusts a segment custom parameter (custom1–custom3), updates segments and UI.
|
||||
*
|
||||
* Increases or decreases the selected custom parameter, clamps the resulting value to 0–255,
|
||||
* marks the usermod state as changed, notifies the system via lampUdated(), and shows an
|
||||
* overlay with the new value on any attached display.
|
||||
*
|
||||
* @param par Index of the custom parameter to change: 1, 2, or 3. Values other than 2 or 3
|
||||
* are treated as 1.
|
||||
* @param increase `true` to increase the parameter, `false` to decrease it.
|
||||
*
|
||||
* @note If `applyToAll` is true, the change is copied to all other active segments; otherwise
|
||||
* only the main segment is modified.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changeCustom(uint8_t par, bool increase) {
|
||||
uint8_t val = 0;
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
@@ -1089,16 +848,6 @@ void RotaryEncoderUIUsermod::changeCustom(uint8_t par, bool increase) {
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
uint8_t id = strip.getFirstSelectedSegId();
|
||||
@@ -1131,27 +880,9 @@ void RotaryEncoderUIUsermod::changeCustom(uint8_t par, bool increase) {
|
||||
sprintf(lineBuffer, "%d", val);
|
||||
display->overlay(lineBuffer, 500, 10); // use star
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
char lineBuffer[64];
|
||||
sprintf(lineBuffer, "Custom%d: %d", par, val);
|
||||
gc9a01Display->overlay(lineBuffer, 500, 10); // use star glyph
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @brief Change the selected color palette by one step and apply it to segments and displays.
|
||||
*
|
||||
* Updates the current palette index (advances if `increase` is true, otherwise moves backward),
|
||||
* constrains it to the valid palette range, sets the active palette, marks the usermod state as changed,
|
||||
* applies the new palette to either all active segments or only the main segment depending on configuration,
|
||||
* signals a lamp update to commit the change, and refreshes any attached displays (including wake handling).
|
||||
*
|
||||
* @param increase `true` to move to the next palette, `false` to move to the previous palette.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changePalette(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -1161,17 +892,7 @@ void RotaryEncoderUIUsermod::changePalette(bool increase) {
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
effectPaletteIndex = max(min((int)(increase ? effectPaletteIndex+1 : effectPaletteIndex-1), (int)(getPaletteCount()-1)), 0);
|
||||
effectPaletteIndex = max(min((unsigned)(increase ? effectPaletteIndex+1 : effectPaletteIndex-1), getPaletteCount()+customPalettes.size()-1), 0U);
|
||||
effectPalette = palettes_alpha_indexes[effectPaletteIndex];
|
||||
stateChanged = true;
|
||||
if (applyToAll) {
|
||||
@@ -1188,26 +909,9 @@ void RotaryEncoderUIUsermod::changePalette(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
display->showCurrentEffectOrPalette(effectPalette, JSON_palette_names, 2);
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
gc9a01Display->redraw(false); // Update palette display
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adjusts the primary hue value and applies the computed color to the active segment(s), then updates displays.
|
||||
*
|
||||
* This clamps the hue to the 0–255 range, converts the hue and current saturation to RGB(W), sets the internal
|
||||
* changed-state flag, applies the new color to either all active segments or the main segment depending on
|
||||
* configuration, and notifies the system of the update. If a connected display is sleeping, a wake event will
|
||||
* trigger a redraw and consume the input without changing the hue; otherwise an overlay showing the hue value
|
||||
* is displayed.
|
||||
*
|
||||
* @param increase If `true`, increases the hue by the configured step; if `false`, decreases the hue.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changeHue(bool increase){
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -1217,16 +921,6 @@ void RotaryEncoderUIUsermod::changeHue(bool increase){
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
currentHue1 = max(min((increase ? currentHue1+fadeAmount : currentHue1-fadeAmount), 255), 0);
|
||||
colorHStoRGB(currentHue1*256, currentSat1, colPri);
|
||||
stateChanged = true;
|
||||
@@ -1246,23 +940,8 @@ void RotaryEncoderUIUsermod::changeHue(bool increase){
|
||||
sprintf(lineBuffer, "%d", currentHue1);
|
||||
display->overlay(lineBuffer, 500, 7); // use brush
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
char lineBuffer[64];
|
||||
sprintf(lineBuffer, "Hue: %d", currentHue1);
|
||||
gc9a01Display->overlay(lineBuffer, 500, 7); // use brush glyph
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Adjusts the current saturation and applies the change to LEDs and displays.
|
||||
*
|
||||
* Increments or decrements the main saturation value by the configured step, clamps it to the range 0–255, updates the primary RGBW color, applies the new color to either all active segments or the main segment (depending on `applyToAll`), triggers a lamp update, and shows the updated saturation on attached display overlays.
|
||||
*
|
||||
* @param increase If true, increase saturation; if false, decrease saturation.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changeSat(bool increase){
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -1272,16 +951,6 @@ void RotaryEncoderUIUsermod::changeSat(bool increase){
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
currentSat1 = max(min((increase ? currentSat1+fadeAmount : currentSat1-fadeAmount), 255), 0);
|
||||
colorHStoRGB(currentHue1*256, currentSat1, colPri);
|
||||
if (applyToAll) {
|
||||
@@ -1300,28 +969,8 @@ void RotaryEncoderUIUsermod::changeSat(bool increase){
|
||||
sprintf(lineBuffer, "%d", currentSat1);
|
||||
display->overlay(lineBuffer, 500, 8); // use contrast
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
char lineBuffer[64];
|
||||
sprintf(lineBuffer, "Sat: %d", currentSat1);
|
||||
gc9a01Display->overlay(lineBuffer, 500, 8); // use contrast glyph
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Apply or clear a saved preset range and show a brief overlay.
|
||||
*
|
||||
* Constructs a preset state from the configured presetLow/presetHigh range and
|
||||
* applies it when `increase` is true or clears it when `increase` is false.
|
||||
* If no valid preset range is configured (presetHigh <= presetLow or either is 0),
|
||||
* the function does nothing. After applying/clearing the preset it notifies the
|
||||
* system of the change and, when a supported display is attached, shows a
|
||||
* short overlay indicating the current preset.
|
||||
*
|
||||
* @param increase `true` to apply the preset range, `false` to remove/clear it.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changePreset(bool increase) {
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -1331,16 +980,6 @@ void RotaryEncoderUIUsermod::changePreset(bool increase) {
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
if (presetHigh && presetLow && presetHigh > presetLow) {
|
||||
StaticJsonDocument<64> root;
|
||||
char str[64];
|
||||
@@ -1361,26 +1000,9 @@ void RotaryEncoderUIUsermod::changePreset(bool increase) {
|
||||
sprintf(str, "%d", currentPreset);
|
||||
display->overlay(str, 500, 11); // use heart
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
char lineBuffer[64];
|
||||
sprintf(lineBuffer, "Preset: %d", currentPreset);
|
||||
gc9a01Display->overlay(lineBuffer, 500, 11); // use heart glyph
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Adjusts the correlated color temperature (CCT) and applies it to active segments.
|
||||
*
|
||||
* Increments or decrements the stored CCT by the configured step, clamps the result to 0–255,
|
||||
* assigns the value to every active segment, triggers a lamp update, and shows a brief overlay
|
||||
* on any attached display.
|
||||
*
|
||||
* @param increase True to increase CCT, false to decrease.
|
||||
*/
|
||||
void RotaryEncoderUIUsermod::changeCCT(bool increase){
|
||||
#ifdef USERMOD_FOUR_LINE_DISPLAY
|
||||
if (display && display->wakeDisplay()) {
|
||||
@@ -1390,16 +1012,6 @@ void RotaryEncoderUIUsermod::changeCCT(bool increase){
|
||||
}
|
||||
display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display && gc9a01Display->wakeDisplay()) {
|
||||
gc9a01Display->redraw(true);
|
||||
// Throw away wake up input
|
||||
return;
|
||||
}
|
||||
if (gc9a01Display) gc9a01Display->updateRedrawTime();
|
||||
#endif
|
||||
|
||||
currentCCT = max(min((increase ? currentCCT+fadeAmount : currentCCT-fadeAmount), 255), 0);
|
||||
// if (applyToAll) {
|
||||
for (unsigned i=0; i<strip.getSegmentsNum(); i++) {
|
||||
@@ -1417,14 +1029,6 @@ void RotaryEncoderUIUsermod::changeCCT(bool increase){
|
||||
sprintf(lineBuffer, "%d", currentCCT);
|
||||
display->overlay(lineBuffer, 500, 10); // use star
|
||||
#endif
|
||||
|
||||
#ifdef USERMOD_GC9A01_DISPLAY
|
||||
if (gc9a01Display) {
|
||||
char lineBuffer[64];
|
||||
sprintf(lineBuffer, "CCT: %d", currentCCT);
|
||||
gc9a01Display->overlay(lineBuffer, 500, 10); // use star glyph
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
+932
-954
File diff suppressed because it is too large
Load Diff
+54
-67
@@ -18,7 +18,7 @@
|
||||
|
||||
#include <vector>
|
||||
#include "wled.h"
|
||||
|
||||
#include "colors.h"
|
||||
#ifdef WLED_DEBUG
|
||||
// enable additional debug output
|
||||
#if defined(WLED_DEBUG_HOST)
|
||||
@@ -38,10 +38,6 @@
|
||||
#define DEBUGFX_PRINTF_P(x...)
|
||||
#endif
|
||||
|
||||
#define FASTLED_INTERNAL //remove annoying pragma messages
|
||||
#define USE_GET_MILLISECOND_TIMER
|
||||
#include "FastLED.h"
|
||||
|
||||
#define DEFAULT_BRIGHTNESS (uint8_t)127
|
||||
#define DEFAULT_MODE (uint8_t)0
|
||||
#define DEFAULT_SPEED (uint8_t)128
|
||||
@@ -58,11 +54,6 @@
|
||||
#define MAX(a,b) ((a)>(b)?(a):(b))
|
||||
#endif
|
||||
|
||||
//color mangling macros
|
||||
#ifndef RGBW32
|
||||
#define RGBW32(r,g,b,w) (uint32_t((byte(w) << 24) | (byte(r) << 16) | (byte(g) << 8) | (byte(b))))
|
||||
#endif
|
||||
|
||||
extern bool realtimeRespectLedMaps; // used in getMappedPixelIndex()
|
||||
extern byte realtimeMode; // used in getMappedPixelIndex()
|
||||
|
||||
@@ -379,36 +370,38 @@ extern byte realtimeMode; // used in getMappedPixelIndex()
|
||||
#define FX_MODE_PS1DSONICBOOM 215
|
||||
#define FX_MODE_PS1DSPRINGY 216
|
||||
#define FX_MODE_PARTICLEGALAXY 217
|
||||
#define MODE_COUNT 218
|
||||
#define FX_MODE_COLORCLOUDS 218
|
||||
#define FX_MODE_SLOW_TRANSITION 219
|
||||
#define MODE_COUNT 220
|
||||
|
||||
|
||||
#define BLEND_STYLE_FADE 0x00 // universal
|
||||
#define BLEND_STYLE_FAIRY_DUST 0x01 // universal
|
||||
#define BLEND_STYLE_SWIPE_RIGHT 0x02 // 1D or 2D
|
||||
#define BLEND_STYLE_SWIPE_LEFT 0x03 // 1D or 2D
|
||||
#define BLEND_STYLE_OUTSIDE_IN 0x04 // 1D or 2D
|
||||
#define BLEND_STYLE_INSIDE_OUT 0x05 // 1D or 2D
|
||||
#define BLEND_STYLE_SWIPE_UP 0x06 // 2D
|
||||
#define BLEND_STYLE_SWIPE_DOWN 0x07 // 2D
|
||||
#define BLEND_STYLE_OPEN_H 0x08 // 2D
|
||||
#define BLEND_STYLE_OPEN_V 0x09 // 2D
|
||||
#define BLEND_STYLE_SWIPE_TL 0x0A // 2D
|
||||
#define BLEND_STYLE_SWIPE_TR 0x0B // 2D
|
||||
#define BLEND_STYLE_SWIPE_BR 0x0C // 2D
|
||||
#define BLEND_STYLE_SWIPE_BL 0x0D // 2D
|
||||
#define BLEND_STYLE_CIRCULAR_OUT 0x0E // 2D
|
||||
#define BLEND_STYLE_CIRCULAR_IN 0x0F // 2D
|
||||
#define TRANSITION_FADE 0x00 // universal
|
||||
#define TRANSITION_FAIRY_DUST 0x01 // universal
|
||||
#define TRANSITION_SWIPE_RIGHT 0x02 // 1D or 2D
|
||||
#define TRANSITION_SWIPE_LEFT 0x03 // 1D or 2D
|
||||
#define TRANSITION_OUTSIDE_IN 0x04 // 1D or 2D
|
||||
#define TRANSITION_INSIDE_OUT 0x05 // 1D or 2D
|
||||
#define TRANSITION_SWIPE_UP 0x06 // 2D
|
||||
#define TRANSITION_SWIPE_DOWN 0x07 // 2D
|
||||
#define TRANSITION_OPEN_H 0x08 // 2D
|
||||
#define TRANSITION_OPEN_V 0x09 // 2D
|
||||
#define TRANSITION_SWIPE_TL 0x0A // 2D
|
||||
#define TRANSITION_SWIPE_TR 0x0B // 2D
|
||||
#define TRANSITION_SWIPE_BR 0x0C // 2D
|
||||
#define TRANSITION_SWIPE_BL 0x0D // 2D
|
||||
#define TRANSITION_CIRCULAR_OUT 0x0E // 2D
|
||||
#define TRANSITION_CIRCULAR_IN 0x0F // 2D
|
||||
// as there are many push variants to optimise if statements they are groupped together
|
||||
#define BLEND_STYLE_PUSH_RIGHT 0x10 // 1D or 2D (& 0b00010000)
|
||||
#define BLEND_STYLE_PUSH_LEFT 0x11 // 1D or 2D (& 0b00010000)
|
||||
#define BLEND_STYLE_PUSH_UP 0x12 // 2D (& 0b00010000)
|
||||
#define BLEND_STYLE_PUSH_DOWN 0x13 // 2D (& 0b00010000)
|
||||
#define BLEND_STYLE_PUSH_TL 0x14 // 2D (& 0b00010000)
|
||||
#define BLEND_STYLE_PUSH_TR 0x15 // 2D (& 0b00010000)
|
||||
#define BLEND_STYLE_PUSH_BR 0x16 // 2D (& 0b00010000)
|
||||
#define BLEND_STYLE_PUSH_BL 0x17 // 2D (& 0b00010000)
|
||||
#define BLEND_STYLE_PUSH_MASK 0x10
|
||||
#define BLEND_STYLE_COUNT 18
|
||||
#define TRANSITION_PUSH_RIGHT 0x10 // 1D or 2D (& 0b00010000)
|
||||
#define TRANSITION_PUSH_LEFT 0x11 // 1D or 2D (& 0b00010000)
|
||||
#define TRANSITION_PUSH_UP 0x12 // 2D (& 0b00010000)
|
||||
#define TRANSITION_PUSH_DOWN 0x13 // 2D (& 0b00010000)
|
||||
#define TRANSITION_PUSH_TL 0x14 // 2D (& 0b00010000)
|
||||
#define TRANSITION_PUSH_TR 0x15 // 2D (& 0b00010000)
|
||||
#define TRANSITION_PUSH_BR 0x16 // 2D (& 0b00010000)
|
||||
#define TRANSITION_PUSH_BL 0x17 // 2D (& 0b00010000)
|
||||
#define TRANSITION_PUSH_MASK 0x10
|
||||
#define TRANSITION_COUNT 18
|
||||
|
||||
|
||||
typedef enum mapping1D2D {
|
||||
@@ -420,10 +413,12 @@ typedef enum mapping1D2D {
|
||||
} mapping1D2D_t;
|
||||
|
||||
class WS2812FX;
|
||||
class FontManager;
|
||||
|
||||
// segment, 76 bytes
|
||||
class Segment {
|
||||
public:
|
||||
friend class FontManager; // Allow FontManager to access protected members
|
||||
uint32_t colors[NUM_COLORS];
|
||||
uint16_t start; // start index / start X coordinate 2D (left)
|
||||
uint16_t stop; // stop index / stop X coordinate 2D (right); segment is invalid if stop == 0
|
||||
@@ -460,13 +455,11 @@ class Segment {
|
||||
bool check1 : 1; // checkmark 1
|
||||
bool check2 : 1; // checkmark 2
|
||||
bool check3 : 1; // checkmark 3
|
||||
//uint8_t blendMode : 4; // segment blending modes: top, bottom, add, subtract, difference, multiply, divide, lighten, darken, screen, overlay, hardlight, softlight, dodge, burn
|
||||
};
|
||||
uint8_t blendMode; // segment blending modes: top, bottom, add, subtract, difference, multiply, divide, lighten, darken, screen, overlay, hardlight, softlight, dodge, burn
|
||||
uint8_t blendMode; // segment blending modes: top, bottom, add, subtract, difference, average, multiply, divide, lighten, darken, screen, overlay, hardlight, softlight, dodge, burn, stencil
|
||||
char *name; // segment name
|
||||
|
||||
// runtime data
|
||||
mutable unsigned long next_time; // millis() of next update
|
||||
mutable uint32_t step; // custom "step" var
|
||||
mutable uint32_t call; // call counter
|
||||
mutable uint16_t aux0; // custom var
|
||||
@@ -521,7 +514,7 @@ class Segment {
|
||||
, _start(millis())
|
||||
, _colors{0,0,0}
|
||||
#ifndef WLED_SAVE_RAM
|
||||
, _palT(CRGBPalette16(CRGB::Black))
|
||||
, _palT(CRGBPalette16())
|
||||
#endif
|
||||
, _dur(dur)
|
||||
, _progress(0)
|
||||
@@ -538,7 +531,7 @@ class Segment {
|
||||
|
||||
protected:
|
||||
|
||||
inline static void addUsedSegmentData(int len) { Segment::_usedSegmentData += len; }
|
||||
inline static void addUsedSegmentData(int len) { Segment::_usedSegmentData = max(0, int(Segment::_usedSegmentData) + len); } // clamp negative results to 0
|
||||
|
||||
inline uint32_t *getPixels() const { return pixels; }
|
||||
inline void setPixelColorRaw(unsigned i, uint32_t c) const { pixels[i] = c; }
|
||||
@@ -548,7 +541,7 @@ class Segment {
|
||||
inline uint32_t getPixelColorXYRaw(unsigned x, unsigned y) const { auto XY = [](unsigned X, unsigned Y){ return X + Y*Segment::vWidth(); }; return pixels[XY(x,y)]; };
|
||||
#endif
|
||||
void resetIfRequired(); // sets all SEGENV variables to 0 and clears data buffer
|
||||
CRGBPalette16 &loadPalette(CRGBPalette16 &tgt, uint8_t pal);
|
||||
void loadPalette(CRGBPalette16 &tgt, uint8_t pal);
|
||||
|
||||
// transition functions
|
||||
void stopTransition(); // ends transition mode by destroying transition structure (does nothing if not in transition)
|
||||
@@ -560,9 +553,9 @@ class Segment {
|
||||
inline uint16_t progress() const { return isInTransition() ? _t->_progress : 0xFFFFU; } // relies on handleTransition()/updateTransitionProgress() to update progression variable
|
||||
inline Segment *getOldSegment() const { return isInTransition() ? _t->_oldSegment : nullptr; }
|
||||
|
||||
inline static void modeBlend(bool blend) { Segment::_modeBlend = blend; }
|
||||
inline static void modeBlend(bool blend) { Segment::_modeBlend = blend; } // for isPreviousMode()
|
||||
inline static void setClippingRect(int startX, int stopX, int startY = 0, int stopY = 1) { _clipStart = startX; _clipStop = stopX; _clipStartY = startY; _clipStopY = stopY; };
|
||||
inline static bool isPreviousMode() { return Segment::_modeBlend; } // needed for determining CCT/opacity during non-BLEND_STYLE_FADE transition
|
||||
inline static bool isPreviousMode() { return Segment::_modeBlend; } // needed for determining CCT/opacity during non-TRANSITION_FADE transition
|
||||
|
||||
static void handleRandomPalette();
|
||||
|
||||
@@ -592,7 +585,6 @@ class Segment {
|
||||
, check3(false)
|
||||
, blendMode(0)
|
||||
, name(nullptr)
|
||||
, next_time(0)
|
||||
, step(0)
|
||||
, call(0)
|
||||
, aux0(0)
|
||||
@@ -762,8 +754,8 @@ class Segment {
|
||||
{ addPixelColorXY(x, y, RGBW32(r,g,b,w), preserveCR); }
|
||||
inline void addPixelColorXY(int x, int y, CRGB c, bool preserveCR = true) const { addPixelColorXY(x, y, RGBW32(c.r,c.g,c.b,0), preserveCR); }
|
||||
inline void fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade) const { setPixelColorXY(x, y, color_fade(getPixelColorXY(x,y), fade, true)); }
|
||||
inline void blurCols(fract8 blur_amount, bool smear = false) const { blur2D(0, blur_amount, smear); } // blur all columns (50% faster than full 2D blur)
|
||||
inline void blurRows(fract8 blur_amount, bool smear = false) const { blur2D(blur_amount, 0, smear); } // blur all rows (50% faster than full 2D blur)
|
||||
inline void blurCols(uint8_t blur_amount, bool smear = false) const { blur2D(0, blur_amount, smear); } // blur all columns (50% faster than full 2D blur)
|
||||
inline void blurRows(uint8_t blur_amount, bool smear = false) const { blur2D(blur_amount, 0, smear); } // blur all rows (50% faster than full 2D blur)
|
||||
//void box_blur(unsigned r = 1U, bool smear = false); // 2D box blur
|
||||
void blur2D(uint8_t blur_x, uint8_t blur_y, bool smear = false) const;
|
||||
void moveX(int delta, bool wrap = false) const;
|
||||
@@ -772,12 +764,10 @@ class Segment {
|
||||
void drawCircle(uint16_t cx, uint16_t cy, uint8_t radius, uint32_t c, bool soft = false) const;
|
||||
void fillCircle(uint16_t cx, uint16_t cy, uint8_t radius, uint32_t c, bool soft = false) const;
|
||||
void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint32_t c, bool soft = false) const;
|
||||
void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color, uint32_t col2 = 0, int8_t rotate = 0) const;
|
||||
void wu_pixel(uint32_t x, uint32_t y, CRGB c) const;
|
||||
inline void drawCircle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB c, bool soft = false) const { drawCircle(cx, cy, radius, RGBW32(c.r,c.g,c.b,0), soft); }
|
||||
inline void fillCircle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB c, bool soft = false) const { fillCircle(cx, cy, radius, RGBW32(c.r,c.g,c.b,0), soft); }
|
||||
inline void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, CRGB c, bool soft = false) const { drawLine(x0, y0, x1, y1, RGBW32(c.r,c.g,c.b,0), soft); } // automatic inline
|
||||
inline void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, CRGB c, CRGB c2 = CRGB::Black, int8_t rotate = 0) const { drawCharacter(chr, x, y, w, h, RGBW32(c.r,c.g,c.b,0), RGBW32(c2.r,c2.g,c2.b,0), rotate); } // automatic inline
|
||||
inline void fill_solid(CRGB c) const { fill(RGBW32(c.r,c.g,c.b,0)); }
|
||||
#else
|
||||
inline bool is2D() const { return false; }
|
||||
@@ -791,18 +781,18 @@ class Segment {
|
||||
inline void setPixelColorXY(float x, float y, byte r, byte g, byte b, byte w = 0, bool aa = true) { setPixelColor(x, RGBW32(r,g,b,w), aa); }
|
||||
inline void setPixelColorXY(float x, float y, CRGB c, bool aa = true) const { setPixelColor(x, RGBW32(c.r,c.g,c.b,0), aa); }
|
||||
#endif
|
||||
inline bool isPixelXYClipped(int x, int y) const { return isPixelClipped(x); }
|
||||
inline uint32_t getPixelColorXY(int x, int y) const { return getPixelColor(x); }
|
||||
inline void blendPixelColorXY(uint16_t x, uint16_t y, uint32_t c, uint8_t blend) const { blendPixelColor(x, c, blend); }
|
||||
inline void blendPixelColorXY(uint16_t x, uint16_t y, CRGB c, uint8_t blend) const { blendPixelColor(x, RGBW32(c.r,c.g,c.b,0), blend); }
|
||||
inline void addPixelColorXY(int x, int y, uint32_t color, bool saturate = false) const { addPixelColor(x, color, saturate); }
|
||||
inline void addPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0, bool saturate = false) const { addPixelColor(x, RGBW32(r,g,b,w), saturate); }
|
||||
inline void addPixelColorXY(int x, int y, CRGB c, bool saturate = false) const { addPixelColor(x, RGBW32(c.r,c.g,c.b,0), saturate); }
|
||||
inline void fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade) const { fadePixelColor(x, fade); }
|
||||
//inline void box_blur(unsigned i, bool vertical, fract8 blur_amount) {}
|
||||
inline bool isPixelXYClipped(int x, int y) { return isPixelClipped(x); }
|
||||
inline uint32_t getPixelColorXY(int x, int y) { return getPixelColor(x); }
|
||||
inline void blendPixelColorXY(uint16_t x, uint16_t y, uint32_t c, uint8_t blend) { blendPixelColor(x, c, blend); }
|
||||
inline void blendPixelColorXY(uint16_t x, uint16_t y, CRGB c, uint8_t blend) { blendPixelColor(x, RGBW32(c.r,c.g,c.b,0), blend); }
|
||||
inline void addPixelColorXY(int x, int y, uint32_t color, bool preserveCR = true) { addPixelColor(x, color, preserveCR); }
|
||||
inline void addPixelColorXY(int x, int y, byte r, byte g, byte b, byte w = 0, bool preserveCR = true) { addPixelColor(x, RGBW32(r,g,b,w), preserveCR); }
|
||||
inline void addPixelColorXY(int x, int y, CRGB c, bool preserveCR = true) { addPixelColor(x, RGBW32(c.r,c.g,c.b,0), preserveCR); }
|
||||
inline void fadePixelColorXY(uint16_t x, uint16_t y, uint8_t fade) { fadePixelColor(x, fade); }
|
||||
//inline void box_blur(unsigned i, bool vertical, uint8_t blur_amount) {}
|
||||
inline void blur2D(uint8_t blur_x, uint8_t blur_y, bool smear = false) {}
|
||||
inline void blurCols(fract8 blur_amount, bool smear = false) { blur(blur_amount, smear); } // blur all columns (50% faster than full 2D blur)
|
||||
inline void blurRows(fract8 blur_amount, bool smear = false) {}
|
||||
inline void blurRows(uint8_t blur_amount, bool smear = false) {}
|
||||
inline void blurCols(uint8_t blur_amount, bool smear = false) {}
|
||||
inline void moveX(int delta, bool wrap = false) {}
|
||||
inline void moveY(int delta, bool wrap = false) {}
|
||||
inline void move(uint8_t dir, uint8_t delta, bool wrap = false) {}
|
||||
@@ -812,8 +802,6 @@ class Segment {
|
||||
inline void fillCircle(uint16_t cx, uint16_t cy, uint8_t radius, CRGB c, bool soft = false) {}
|
||||
inline void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint32_t c, bool soft = false) {}
|
||||
inline void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, CRGB c, bool soft = false) {}
|
||||
inline void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color, uint32_t = 0, int8_t = 0) {}
|
||||
inline void drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, CRGB c, CRGB c2, int8_t rotate = 0) {}
|
||||
inline void wu_pixel(uint32_t x, uint32_t y, CRGB c) {}
|
||||
#endif
|
||||
friend class WS2812FX;
|
||||
@@ -823,19 +811,18 @@ class Segment {
|
||||
|
||||
// main "strip" class (108 bytes)
|
||||
class WS2812FX {
|
||||
typedef uint16_t (*mode_ptr)(); // pointer to mode function
|
||||
typedef void (*mode_ptr)(); // pointer to mode function
|
||||
typedef void (*show_callback)(); // pre show callback
|
||||
typedef struct ModeData {
|
||||
uint8_t _id; // mode (effect) id
|
||||
mode_ptr _fcn; // mode (effect) function
|
||||
const char *_data; // mode (effect) name and its UI control data
|
||||
ModeData(uint8_t id, uint16_t (*fcn)(void), const char *data) : _id(id), _fcn(fcn), _data(data) {}
|
||||
ModeData(uint8_t id, void (*fcn)(void), const char *data) : _id(id), _fcn(fcn), _data(data) {}
|
||||
} mode_data_t;
|
||||
|
||||
public:
|
||||
|
||||
WS2812FX() :
|
||||
paletteBlend(0),
|
||||
now(millis()),
|
||||
timebase(0),
|
||||
isMatrix(false),
|
||||
@@ -937,7 +924,7 @@ class WS2812FX {
|
||||
inline bool isSuspended() const { return _suspend; } // returns true if strip.service() execution is suspended
|
||||
inline bool needsUpdate() const { return _triggered; } // returns true if strip received a trigger() request
|
||||
|
||||
uint8_t paletteBlend;
|
||||
// uint8_t paletteBlend; // obsolete - use global paletteBlend instead of strip.paletteBlend
|
||||
uint8_t getActiveSegmentsNum() const;
|
||||
uint8_t getFirstSelectedSegId() const;
|
||||
uint8_t getLastActiveSegmentId() const;
|
||||
|
||||
+12
-52
@@ -74,7 +74,7 @@ void WS2812FX::setUpMatrix() {
|
||||
size_t gapSize = 0;
|
||||
int8_t *gapTable = nullptr;
|
||||
|
||||
if (isFile && requestJSONBufferLock(20)) {
|
||||
if (isFile && requestJSONBufferLock(JSON_LOCK_LEDGAP)) {
|
||||
DEBUG_PRINT(F("Reading LED gap from "));
|
||||
DEBUG_PRINTLN(fileName);
|
||||
// read the array into global JSON buffer
|
||||
@@ -120,6 +120,9 @@ void WS2812FX::setUpMatrix() {
|
||||
for (unsigned i=0; i<customMappingSize; i++) {
|
||||
if (!(i%Segment::maxWidth)) DEBUG_PRINTLN();
|
||||
DEBUG_PRINTF_P(PSTR("%4d,"), customMappingTable[i]);
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32S2)
|
||||
delay(1); // on S2 the CDC output can crash without a delay
|
||||
#endif
|
||||
}
|
||||
DEBUG_PRINTLN();
|
||||
#endif
|
||||
@@ -146,14 +149,14 @@ void WS2812FX::setUpMatrix() {
|
||||
// pixel is clipped if it falls outside clipping range
|
||||
// if clipping start > stop the clipping range is inverted
|
||||
bool Segment::isPixelXYClipped(int x, int y) const {
|
||||
if (blendingStyle != BLEND_STYLE_FADE && isInTransition() && _clipStart != _clipStop) {
|
||||
if (blendingStyle != TRANSITION_FADE && isInTransition() && _clipStart != _clipStop) {
|
||||
const bool invertX = _clipStart > _clipStop;
|
||||
const bool invertY = _clipStartY > _clipStopY;
|
||||
const int cStartX = invertX ? _clipStop : _clipStart;
|
||||
const int cStopX = invertX ? _clipStart : _clipStop;
|
||||
const int cStartY = invertY ? _clipStopY : _clipStartY;
|
||||
const int cStopY = invertY ? _clipStartY : _clipStopY;
|
||||
if (blendingStyle == BLEND_STYLE_FAIRY_DUST) {
|
||||
if (blendingStyle == TRANSITION_FAIRY_DUST) {
|
||||
const unsigned width = cStopX - cStartX; // assumes full segment width (faster than virtualWidth())
|
||||
const unsigned len = width * (cStopY - cStartY); // assumes full segment height (faster than virtualHeight())
|
||||
if (len < 2) return false;
|
||||
@@ -161,10 +164,10 @@ bool Segment::isPixelXYClipped(int x, int y) const {
|
||||
const unsigned pos = (shuffled * 0xFFFFU) / len;
|
||||
return progress() <= pos;
|
||||
}
|
||||
if (blendingStyle == BLEND_STYLE_CIRCULAR_IN || blendingStyle == BLEND_STYLE_CIRCULAR_OUT) {
|
||||
if (blendingStyle == TRANSITION_CIRCULAR_IN || blendingStyle == TRANSITION_CIRCULAR_OUT) {
|
||||
const int cx = (cStopX-cStartX+1) / 2;
|
||||
const int cy = (cStopY-cStartY+1) / 2;
|
||||
const bool out = (blendingStyle == BLEND_STYLE_CIRCULAR_OUT);
|
||||
const bool out = (blendingStyle == TRANSITION_CIRCULAR_OUT);
|
||||
const unsigned prog = out ? progress() : 0xFFFFU - progress();
|
||||
int radius2 = max(cx, cy) * prog / 0xFFFF;
|
||||
radius2 = 2 * radius2 * radius2;
|
||||
@@ -176,7 +179,7 @@ bool Segment::isPixelXYClipped(int x, int y) const {
|
||||
}
|
||||
bool xInside = (x >= cStartX && x < cStopX); if (invertX) xInside = !xInside;
|
||||
bool yInside = (y >= cStartY && y < cStopY); if (invertY) yInside = !yInside;
|
||||
const bool clip = blendingStyle == BLEND_STYLE_OUTSIDE_IN ? xInside || yInside : xInside && yInside;
|
||||
const bool clip = blendingStyle == TRANSITION_OUTSIDE_IN ? xInside || yInside : xInside && yInside;
|
||||
return !clip;
|
||||
}
|
||||
return false;
|
||||
@@ -559,51 +562,6 @@ void Segment::drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint3
|
||||
}
|
||||
}
|
||||
|
||||
#include "src/font/console_font_4x6.h"
|
||||
#include "src/font/console_font_5x8.h"
|
||||
#include "src/font/console_font_5x12.h"
|
||||
#include "src/font/console_font_6x8.h"
|
||||
#include "src/font/console_font_7x9.h"
|
||||
|
||||
// draws a raster font character on canvas
|
||||
// only supports: 4x6=24, 5x8=40, 5x12=60, 6x8=48 and 7x9=63 fonts ATM
|
||||
void Segment::drawCharacter(unsigned char chr, int16_t x, int16_t y, uint8_t w, uint8_t h, uint32_t color, uint32_t col2, int8_t rotate) const {
|
||||
if (!isActive()) return; // not active
|
||||
if (chr < 32 || chr > 126) return; // only ASCII 32-126 supported
|
||||
chr -= 32; // align with font table entries
|
||||
const int font = w*h;
|
||||
|
||||
// if col2 == BLACK then use currently selected palette for gradient otherwise create gradient from color and col2
|
||||
CRGBPalette16 grad = col2 ? CRGBPalette16(CRGB(color), CRGB(col2)) : SEGPALETTE; // selected palette as gradient
|
||||
|
||||
for (int i = 0; i<h; i++) { // character height
|
||||
uint8_t bits = 0;
|
||||
switch (font) {
|
||||
case 24: bits = pgm_read_byte_near(&console_font_4x6[(chr * h) + i]); break; // 4x6 font
|
||||
case 40: bits = pgm_read_byte_near(&console_font_5x8[(chr * h) + i]); break; // 5x8 font
|
||||
case 48: bits = pgm_read_byte_near(&console_font_6x8[(chr * h) + i]); break; // 6x8 font
|
||||
case 63: bits = pgm_read_byte_near(&console_font_7x9[(chr * h) + i]); break; // 7x9 font
|
||||
case 60: bits = pgm_read_byte_near(&console_font_5x12[(chr * h) + i]); break; // 5x12 font
|
||||
default: return;
|
||||
}
|
||||
CRGBW c = ColorFromPalette(grad, (i+1)*255/h, 255, LINEARBLEND_NOWRAP); // NOBLEND is faster
|
||||
for (int j = 0; j<w; j++) { // character width
|
||||
int x0, y0;
|
||||
switch (rotate) {
|
||||
case -1: x0 = x + (h-1) - i; y0 = y + (w-1) - j; break; // -90 deg
|
||||
case -2:
|
||||
case 2: x0 = x + j; y0 = y + (h-1) - i; break; // 180 deg
|
||||
case 1: x0 = x + i; y0 = y + j; break; // +90 deg
|
||||
default: x0 = x + (w-1) - j; y0 = y + i; break; // no rotation
|
||||
}
|
||||
if (x0 < 0 || x0 >= (int)vWidth() || y0 < 0 || y0 >= (int)vHeight()) continue; // drawing off-screen
|
||||
if (((bits>>(j+(8-w))) & 0x01)) { // bit set
|
||||
setPixelColorXYRaw(x0, y0, c.color32);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#define WU_WEIGHT(a,b) ((uint8_t) (((a)*(b)+(a)+(b))>>8))
|
||||
void Segment::wu_pixel(uint32_t x, uint32_t y, CRGB c) const { //awesome wu_pixel procedure by reddit u/sutaburosu
|
||||
if (!isActive()) return; // not active
|
||||
@@ -626,4 +584,6 @@ void Segment::wu_pixel(uint32_t x, uint32_t y, CRGB c) const { //awesome wu
|
||||
}
|
||||
#undef WU_WEIGHT
|
||||
|
||||
#endif // WLED_DISABLE_2D
|
||||
|
||||
|
||||
#endif // WLED_DISABLE_2D
|
||||
+187
-154
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
#include "wled.h"
|
||||
#include "FXparticleSystem.h" // TODO: better define the required function (mem service) in FX.h?
|
||||
#include "colors.h"
|
||||
|
||||
/*
|
||||
Custom per-LED mapping has moved!
|
||||
@@ -43,7 +44,7 @@ unsigned Segment::_vLength = 0;
|
||||
unsigned Segment::_vWidth = 0;
|
||||
unsigned Segment::_vHeight = 0;
|
||||
uint32_t Segment::_currentColors[NUM_COLORS] = {0,0,0};
|
||||
CRGBPalette16 Segment::_currentPalette = CRGBPalette16(CRGB::Black);
|
||||
CRGBPalette16 Segment::_currentPalette = CRGBPalette16();
|
||||
CRGBPalette16 Segment::_randomPalette = generateRandomPalette(); // was CRGBPalette16(DEFAULT_COLOR);
|
||||
CRGBPalette16 Segment::_newRandomPalette = generateRandomPalette(); // was CRGBPalette16(DEFAULT_COLOR);
|
||||
uint16_t Segment::_lastPaletteChange = 0; // in seconds; perhaps it should be per segment
|
||||
@@ -100,12 +101,12 @@ Segment& Segment::operator= (const Segment &orig) {
|
||||
if (_t) stopTransition(); // also erases _t
|
||||
deallocateData();
|
||||
p_free(pixels);
|
||||
pixels = nullptr;
|
||||
// copy source
|
||||
memcpy((void*)this, (void*)&orig, sizeof(Segment));
|
||||
// erase pointers to allocated data
|
||||
data = nullptr;
|
||||
_dataLen = 0;
|
||||
pixels = nullptr;
|
||||
if (!stop) return *this; // nothing to do if segment is inactive/invalid
|
||||
// copy source data
|
||||
if (orig.pixels) {
|
||||
@@ -217,15 +218,15 @@ void Segment::resetIfRequired() {
|
||||
DEBUG_PRINTF_P(PSTR("-- Segment %p reset, data cleared\n"), this);
|
||||
}
|
||||
if (pixels) for (size_t i = 0; i < length(); i++) pixels[i] = BLACK; // clear pixel buffer
|
||||
next_time = 0; step = 0; call = 0; aux0 = 0; aux1 = 0;
|
||||
step = 0; call = 0; aux0 = 0; aux1 = 0;
|
||||
reset = false;
|
||||
#ifdef WLED_ENABLE_GIF
|
||||
endImagePlayback(this);
|
||||
#endif
|
||||
}
|
||||
|
||||
CRGBPalette16 &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) {
|
||||
// there is one randomy generated palette (1) followed by 4 palettes created from segment colors (2-5)
|
||||
void Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) {
|
||||
// there is one randomly generated palette (1) followed by 4 palettes created from segment colors (2-5)
|
||||
// those are followed by 7 fastled palettes (6-12) and 59 gradient palettes (13-71)
|
||||
// then come the custom palettes (255,254,...) growing downwards from 255 (255 being 1st custom palette)
|
||||
// palette 0 is a varying palette depending on effect and may be replaced by segment's color if so
|
||||
@@ -235,7 +236,7 @@ CRGBPalette16 &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) {
|
||||
if (pal == 0) pal = _default_palette; // _default_palette is set in setMode()
|
||||
switch (pal) {
|
||||
case 0: //default palette. Exceptions for specific effects above
|
||||
targetPalette = PartyColors_p;
|
||||
targetPalette = PartyColors_gc22;
|
||||
break;
|
||||
case 1: //randomly generated palette
|
||||
targetPalette = _randomPalette; //random palette is generated at intervals in handleRandomPalette()
|
||||
@@ -277,7 +278,6 @@ CRGBPalette16 &Segment::loadPalette(CRGBPalette16 &targetPalette, uint8_t pal) {
|
||||
}
|
||||
break;
|
||||
}
|
||||
return targetPalette;
|
||||
}
|
||||
|
||||
// starting a transition has to occur before change so we get current values 1st
|
||||
@@ -343,7 +343,7 @@ void Segment::updateTransitionProgress() const {
|
||||
uint8_t Segment::currentCCT() const {
|
||||
unsigned prog = progress();
|
||||
if (prog < 0xFFFFU) {
|
||||
if (blendingStyle == BLEND_STYLE_FADE) return (cct * prog + (_t->_cct * (0xFFFFU - prog))) / 0xFFFFU;
|
||||
if (blendingStyle == TRANSITION_FADE) return (cct * prog + (_t->_cct * (0xFFFFU - prog))) / 0xFFFFU;
|
||||
//else return Segment::isPreviousMode() ? _t->_cct : cct;
|
||||
}
|
||||
return cct;
|
||||
@@ -355,7 +355,7 @@ uint8_t Segment::currentBri() const {
|
||||
unsigned curBri = on ? opacity : 0;
|
||||
if (prog < 0xFFFFU) {
|
||||
// this will blend opacity in new mode if style is FADE (single effect call)
|
||||
if (blendingStyle == BLEND_STYLE_FADE) curBri = (prog * curBri + _t->_bri * (0xFFFFU - prog)) / 0xFFFFU;
|
||||
if (blendingStyle == TRANSITION_FADE) curBri = (prog * curBri + _t->_bri * (0xFFFFU - prog)) / 0xFFFFU;
|
||||
else curBri = Segment::isPreviousMode() ? _t->_bri : curBri;
|
||||
}
|
||||
return curBri;
|
||||
@@ -371,7 +371,7 @@ void Segment::beginDraw(uint16_t prog) {
|
||||
for (unsigned i = 0; i < NUM_COLORS; i++) _currentColors[i] = colors[i];
|
||||
// load palette into _currentPalette
|
||||
loadPalette(Segment::_currentPalette, palette);
|
||||
if (isInTransition() && prog < 0xFFFFU && blendingStyle == BLEND_STYLE_FADE) {
|
||||
if (isInTransition() && prog < 0xFFFFU && blendingStyle == TRANSITION_FADE) {
|
||||
// blend colors
|
||||
for (unsigned i = 0; i < NUM_COLORS; i++) _currentColors[i] = color_blend16(_t->_colors[i], colors[i], prog);
|
||||
// blend palettes
|
||||
@@ -379,7 +379,7 @@ void Segment::beginDraw(uint16_t prog) {
|
||||
// minimum blend time is 100ms maximum is 65535ms
|
||||
#ifndef WLED_SAVE_RAM
|
||||
unsigned noOfBlends = ((255U * prog) / 0xFFFFU) - _t->_prevPaletteBlends;
|
||||
if(noOfBlends > 255) noOfBlends = 255; // safety check
|
||||
if (noOfBlends > 255) noOfBlends = 255; // safety check
|
||||
for (unsigned i = 0; i < noOfBlends; i++, _t->_prevPaletteBlends++) nblendPaletteTowardPalette(_t->_palT, Segment::_currentPalette, 48);
|
||||
Segment::_currentPalette = _t->_palT; // copy transitioning/temporary palette
|
||||
#else
|
||||
@@ -506,7 +506,7 @@ Segment &Segment::setColor(uint8_t slot, uint32_t c) {
|
||||
if (slot == 1 && c != BLACK) return *this; // on/off segment cannot have secondary color non black
|
||||
}
|
||||
//DEBUG_PRINTF_P(PSTR("- Starting color transition: %d [0x%X]\n"), slot, c);
|
||||
startTransition(strip.getTransition(), blendingStyle != BLEND_STYLE_FADE); // start transition prior to change
|
||||
startTransition(strip.getTransition(), blendingStyle != TRANSITION_FADE); // start transition prior to change
|
||||
colors[slot] = c;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
return *this;
|
||||
@@ -530,7 +530,7 @@ Segment &Segment::setCCT(uint16_t k) {
|
||||
Segment &Segment::setOpacity(uint8_t o) {
|
||||
if (opacity != o) {
|
||||
//DEBUG_PRINTF_P(PSTR("- Starting opacity transition: %d\n"), o);
|
||||
startTransition(strip.getTransition(), blendingStyle != BLEND_STYLE_FADE); // start transition prior to change
|
||||
startTransition(strip.getTransition(), blendingStyle != TRANSITION_FADE); // start transition prior to change
|
||||
opacity = o;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
}
|
||||
@@ -541,7 +541,7 @@ Segment &Segment::setOption(uint8_t n, bool val) {
|
||||
bool prev = (options >> n) & 0x01;
|
||||
if (val == prev) return *this;
|
||||
//DEBUG_PRINTF_P(PSTR("- Starting option transition: %d\n"), n);
|
||||
if (n == SEG_OPTION_ON) startTransition(strip.getTransition(), blendingStyle != BLEND_STYLE_FADE); // start transition prior to change
|
||||
if (n == SEG_OPTION_ON) startTransition(strip.getTransition(), blendingStyle != TRANSITION_FADE); // start transition prior to change
|
||||
if (val) options |= 0x01 << n;
|
||||
else options &= ~(0x01 << n);
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
@@ -577,7 +577,7 @@ Segment &Segment::setMode(uint8_t fx, bool loadDefaults) {
|
||||
sOpt = extractModeDefaults(fx, "pal"); // always extract 'pal' to set _default_palette
|
||||
if (sOpt >= 0 && loadDefaults) setPalette(sOpt);
|
||||
if (sOpt <= 0) sOpt = 6; // partycolors if zero or not set
|
||||
_default_palette = sOpt; // _deault_palette is loaded into pal0 in loadPalette() (if selected)
|
||||
_default_palette = sOpt; // _default_palette is loaded into pal0 in loadPalette() (if selected)
|
||||
markForReset();
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
}
|
||||
@@ -588,7 +588,7 @@ Segment &Segment::setPalette(uint8_t pal) {
|
||||
if (pal <= 255-customPalettes.size() && pal > FIXED_PALETTE_COUNT) pal = 0; // not built in palette or custom palette
|
||||
if (pal != palette) {
|
||||
//DEBUG_PRINTF_P(PSTR("- Starting palette transition: %d\n"), pal);
|
||||
startTransition(strip.getTransition(), blendingStyle != BLEND_STYLE_FADE); // start transition prior to change (no need to copy segment)
|
||||
startTransition(strip.getTransition(), blendingStyle != TRANSITION_FADE); // start transition prior to change (no need to copy segment)
|
||||
palette = pal;
|
||||
stateChanged = true; // send UDP/WS broadcast
|
||||
}
|
||||
@@ -692,11 +692,11 @@ uint16_t Segment::maxMappingLength() const {
|
||||
// pixel is clipped if it falls outside clipping range
|
||||
// if clipping start > stop the clipping range is inverted
|
||||
bool Segment::isPixelClipped(int i) const {
|
||||
if (blendingStyle != BLEND_STYLE_FADE && isInTransition() && _clipStart != _clipStop) {
|
||||
if (blendingStyle != TRANSITION_FADE && isInTransition() && _clipStart != _clipStop) {
|
||||
bool invert = _clipStart > _clipStop; // ineverted start & stop
|
||||
int start = invert ? _clipStop : _clipStart;
|
||||
int stop = invert ? _clipStart : _clipStop;
|
||||
if (blendingStyle == BLEND_STYLE_FAIRY_DUST) {
|
||||
if (blendingStyle == TRANSITION_FAIRY_DUST) {
|
||||
unsigned len = stop - start;
|
||||
if (len < 2) return false;
|
||||
unsigned shuffled = hashInt(i) % len;
|
||||
@@ -1104,9 +1104,9 @@ void Segment::blur(uint8_t blur_amount, bool smear) const {
|
||||
uint32_t Segment::color_wheel(uint8_t pos) const {
|
||||
if (palette) return color_from_palette(pos, false, false, 0); // only wrap if "always wrap" is set
|
||||
uint8_t w = W(getCurrentColor(0));
|
||||
uint32_t rgb;
|
||||
hsv2rgb(CHSV32(static_cast<uint16_t>(pos << 8), 255, 255), rgb);
|
||||
return rgb | (w << 24); // add white channel
|
||||
CRGBW rgb;
|
||||
rgb = CHSV32(static_cast<uint16_t>(pos << 8), 255, 255);
|
||||
return rgb.color32 | (w << 24); // add white channel
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -1159,66 +1159,74 @@ void WS2812FX::finalizeInit() {
|
||||
|
||||
_hasWhiteChannel = _isOffRefreshRequired = false;
|
||||
BusManager::removeAll();
|
||||
|
||||
// TODO: ideally we would free everything segment related here to reduce fragmentation (pixel buffers, ledamp, segments, etc) but that somehow leads to heap corruption if touchig any of the buffers.
|
||||
unsigned digitalCount = 0;
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
// determine if it is sensible to use parallel I2S outputs on ESP32 (i.e. more than 5 outputs = 1 I2S + 4 RMT)
|
||||
unsigned maxLedsOnBus = 0;
|
||||
unsigned busType = 0;
|
||||
// validate the bus config: count I2S buses and check if they meet requirements
|
||||
unsigned i2sBusCount = 0;
|
||||
|
||||
for (const auto &bus : busConfigs) {
|
||||
if (Bus::isDigital(bus.type) && !Bus::is2Pin(bus.type)) {
|
||||
digitalCount++;
|
||||
if (busType == 0) busType = bus.type; // remember first bus type
|
||||
if (busType != bus.type) {
|
||||
DEBUG_PRINTF_P(PSTR("Mixed digital bus types detected! Forcing single I2S output.\n"));
|
||||
useParallelI2S = false; // mixed bus types, no parallel I2S
|
||||
}
|
||||
if (bus.count > maxLedsOnBus) maxLedsOnBus = bus.count;
|
||||
if (bus.driverType == 1)
|
||||
i2sBusCount++;
|
||||
}
|
||||
}
|
||||
DEBUG_PRINTF_P(PSTR("Maximum LEDs on a bus: %u\nDigital buses: %u\n"), maxLedsOnBus, digitalCount);
|
||||
// we may remove 600 LEDs per bus limit when NeoPixelBus is updated beyond 2.8.3
|
||||
if (maxLedsOnBus <= 600 && useParallelI2S) BusManager::useParallelOutput(); // must call before creating buses
|
||||
else useParallelI2S = false; // enforce single I2S
|
||||
digitalCount = 0;
|
||||
DEBUG_PRINTF_P(PSTR("Digital buses: %u, I2S buses: %u\n"), digitalCount, i2sBusCount);
|
||||
|
||||
// Determine parallel vs single I2S usage (used for memory calculation only)
|
||||
bool useParallelI2S = false;
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
// ESP32-S3 always uses parallel LCD driver for I2S
|
||||
if (i2sBusCount > 0) {
|
||||
useParallelI2S = true;
|
||||
}
|
||||
#else
|
||||
if (i2sBusCount > 1) {
|
||||
useParallelI2S = true;
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
DEBUG_PRINTF_P(PSTR("Heap before buses: %d\n"), getFreeHeapSize());
|
||||
// create buses/outputs
|
||||
unsigned mem = 0;
|
||||
unsigned maxI2S = 0;
|
||||
for (const auto &bus : busConfigs) {
|
||||
unsigned memB = bus.memUsage(Bus::isDigital(bus.type) && !Bus::is2Pin(bus.type) ? digitalCount++ : 0); // does not include DMA/RMT buffer
|
||||
mem += memB;
|
||||
// estimate maximum I2S memory usage (only relevant for digital non-2pin busses)
|
||||
unsigned mem = 0; // memory estimation including DMA buffer for I2S and pixel buffers
|
||||
unsigned I2SdmaMem = 0;
|
||||
for (auto &bus : busConfigs) {
|
||||
// assign bus types: call to getI() determines bus types/drivers, allocates and tracks polybus channels
|
||||
// store the result in iType for later use during bus creation (getI() must only be called once per BusConfig)
|
||||
// note: this needs to be determined for all buses prior to creating them as it also determines parallel I2S usage
|
||||
bus.iType = BusManager::getI(bus.type, bus.pins, bus.driverType);
|
||||
}
|
||||
for (auto &bus : busConfigs) {
|
||||
bool use_placeholder = false;
|
||||
unsigned busMemUsage = bus.memUsage(); // does not include DMA/RMT buffer but includes pixel buffers (segment buffer + global buffer)
|
||||
mem += busMemUsage;
|
||||
// estimate maximum I2S memory usage (only relevant for digital non-2pin busses when I2S is enabled)
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(ESP8266)
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32) || defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
const bool usesI2S = ((useParallelI2S && digitalCount <= 8) || (!useParallelI2S && digitalCount == 1));
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S2)
|
||||
const bool usesI2S = (useParallelI2S && digitalCount <= 8);
|
||||
#else
|
||||
const bool usesI2S = false;
|
||||
#endif
|
||||
bool usesI2S = (bus.iType & 0x01) == 0; // I2S bus types are even numbered, can't use bus.driverType == 1 as getI() may have defaulted to RMT
|
||||
if (Bus::isDigital(bus.type) && !Bus::is2Pin(bus.type) && usesI2S) {
|
||||
#ifdef NPB_CONF_4STEP_CADENCE
|
||||
constexpr unsigned stepFactor = 4; // 4 step cadence (4 bits per pixel bit)
|
||||
#else
|
||||
constexpr unsigned stepFactor = 3; // 3 step cadence (3 bits per pixel bit)
|
||||
#endif
|
||||
unsigned i2sCommonSize = stepFactor * bus.count * (3*Bus::hasRGB(bus.type)+Bus::hasWhite(bus.type)+Bus::hasCCT(bus.type)) * (Bus::is16bit(bus.type)+1);
|
||||
if (i2sCommonSize > maxI2S) maxI2S = i2sCommonSize;
|
||||
unsigned i2sCommonMem = (stepFactor * bus.count * (3*Bus::hasRGB(bus.type)+Bus::hasWhite(bus.type)+Bus::hasCCT(bus.type)) * (Bus::is16bit(bus.type)+1));
|
||||
if (useParallelI2S) i2sCommonMem *= 8; // parallel I2S uses 8 channels, requiring 8x the DMA buffer size (common buffer shared between all parallel busses)
|
||||
if (i2sCommonMem > I2SdmaMem) I2SdmaMem = i2sCommonMem;
|
||||
}
|
||||
#endif
|
||||
if (mem + maxI2S <= MAX_LED_MEMORY) {
|
||||
BusManager::add(bus);
|
||||
DEBUG_PRINTF_P(PSTR("Bus memory: %uB\n"), memB);
|
||||
} else {
|
||||
errorFlag = ERR_NORAM_PX; // alert UI
|
||||
DEBUG_PRINTF_P(PSTR("Out of LED memory! Bus %d (%d) #%u not created."), (int)bus.type, (int)bus.count, digitalCount);
|
||||
break;
|
||||
if (mem + I2SdmaMem > MAX_LED_MEMORY + 1024) { // +1k to allow some margin to not drop buses that are allowed in UI (calculation here includes bus overhead)
|
||||
DEBUG_PRINTF_P(PSTR("Bus %d with %d LEDS memory usage exceeds limit\n"), (int)bus.type, bus.count);
|
||||
errorFlag = ERR_NORAM; // alert UI TODO: make this a distinct error: not enough memory for bus
|
||||
use_placeholder = true;
|
||||
}
|
||||
if (BusManager::add(bus, use_placeholder) != -1) {
|
||||
mem += BusManager::busses.back()->getBusSize();
|
||||
if (Bus::isDigital(bus.type) && !Bus::is2Pin(bus.type) && BusManager::busses.back()->isPlaceholder()) digitalCount--; // remove placeholder from digital count
|
||||
}
|
||||
}
|
||||
DEBUG_PRINTF_P(PSTR("LED buffer size: %uB/%uB\n"), mem + maxI2S, BusManager::memUsage());
|
||||
DEBUG_PRINTF_P(PSTR("Estimated buses + pixel-buffers size: %uB\n"), mem + I2SdmaMem);
|
||||
busConfigs.clear();
|
||||
busConfigs.shrink_to_fit();
|
||||
|
||||
@@ -1258,62 +1266,56 @@ void WS2812FX::finalizeInit() {
|
||||
|
||||
void WS2812FX::service() {
|
||||
unsigned long nowUp = millis(); // Be aware, millis() rolls over every 49 days
|
||||
now = nowUp + timebase;
|
||||
unsigned long elapsed = nowUp - _lastServiceShow;
|
||||
if (_suspend || elapsed <= MIN_FRAME_DELAY) return; // keep wifi alive - no matter if triggered or unlimited
|
||||
if (!_triggered && (_targetFps != FPS_UNLIMITED)) { // unlimited mode = no frametime
|
||||
if (elapsed < _frametime) return; // too early for service
|
||||
}
|
||||
bool timeToShow = (elapsed >= _frametime); // all segments are running at the same speed
|
||||
if (_triggered || _targetFps == FPS_UNLIMITED) timeToShow = true; // unlimited mode = no frametime; strip.trigger() can overrule timing
|
||||
|
||||
bool doShow = false;
|
||||
now = nowUp + timebase; // common time base for all effects
|
||||
if (!timeToShow) return; // too early for service
|
||||
if (_suspend || elapsed <= MIN_FRAME_DELAY) return; // keep wifi alive - no matter if triggered or unlimited
|
||||
|
||||
_isServicing = true;
|
||||
_segment_index = 0;
|
||||
|
||||
for (Segment &seg : _segments) {
|
||||
if (_suspend) break; // immediately stop processing segments if suspend requested during service()
|
||||
bool doShow = _triggered; // true if ≥1 active segment was processed (and strip was not suspended mid-loop), or trigger received → triggers show()
|
||||
for (size_t i = 0; i < _segments.size(); i++) {
|
||||
Segment &seg = _segments[i];
|
||||
_segment_index = i;
|
||||
if (_suspend) break; // abort processing segments if suspend requested during service()
|
||||
|
||||
// process transition (also pre-calculates progress value)
|
||||
seg.handleTransition();
|
||||
// reset the segment runtime data if needed
|
||||
seg.resetIfRequired();
|
||||
|
||||
if (!seg.isActive()) continue;
|
||||
|
||||
// last condition ensures all solid segments are updated at the same time
|
||||
if (nowUp > seg.next_time || _triggered || (doShow && seg.mode == FX_MODE_STATIC))
|
||||
{
|
||||
if (seg.isActive()) {
|
||||
// current segment is active -> re-run effect, and remember that show() call is necessary
|
||||
// if we arrive here, its always showtime (timeToShow == true)
|
||||
doShow = true;
|
||||
unsigned frameDelay = FRAMETIME;
|
||||
|
||||
if (!seg.freeze) { //only run effect function if not frozen
|
||||
// Effect blending
|
||||
uint16_t prog = seg.progress();
|
||||
seg.beginDraw(prog); // set up parameters for get/setPixelColor() (will also blend colors and palette if blend style is FADE)
|
||||
_currentSegment = &seg; // set current segment for effect functions (SEGMENT & SEGENV)
|
||||
// workaround for on/off transition to respect blending style
|
||||
frameDelay = (*_mode[seg.mode])(); // run new/current mode (needed for bri workaround)
|
||||
_mode[seg.mode](); // run new/current mode (needed for bri workaround)
|
||||
seg.call++;
|
||||
// if segment is in transition and no old segment exists we don't need to run the old mode
|
||||
// (blendSegments() takes care of On/Off transitions and clipping)
|
||||
Segment *segO = seg.getOldSegment();
|
||||
if (segO && segO->isActive() && (seg.mode != segO->mode || blendingStyle != BLEND_STYLE_FADE ||
|
||||
if (segO && segO->isActive() && (seg.mode != segO->mode || blendingStyle != TRANSITION_FADE ||
|
||||
(segO->name != seg.name && segO->name && seg.name && strncmp(segO->name, seg.name, WLED_MAX_SEGNAME_LEN) != 0))) {
|
||||
Segment::modeBlend(true); // set semaphore for beginDraw() to blend colors and palette
|
||||
Segment::modeBlend(true); // set flag for beginDraw() to blend colors and palette
|
||||
segO->beginDraw(prog); // set up palette & colors (also sets draw dimensions), parent segment has transition progress
|
||||
_currentSegment = segO; // set current segment
|
||||
// workaround for on/off transition to respect blending style
|
||||
frameDelay = min(frameDelay, (unsigned)(*_mode[segO->mode])()); // run old mode (needed for bri workaround; semaphore!!)
|
||||
_mode[segO->mode](); // run old mode (needed for bri workaround; semaphore!!)
|
||||
segO->call++; // increment old mode run counter
|
||||
Segment::modeBlend(false); // unset semaphore
|
||||
Segment::modeBlend(false); // unset flag
|
||||
}
|
||||
if (seg.isInTransition() && frameDelay > FRAMETIME) frameDelay = FRAMETIME; // force faster updates during transition
|
||||
}
|
||||
|
||||
seg.next_time = nowUp + frameDelay;
|
||||
}
|
||||
_segment_index++;
|
||||
}
|
||||
_segment_index = 0; // segment index is only valid while effects are serviced
|
||||
_currentSegment = &_segments[0]; // safe fallback to prevent stale pointer - SEGMENT/SEGENV should not be used outside of the service loop
|
||||
|
||||
#ifdef WLED_DEBUG
|
||||
if ((_targetFps != FPS_UNLIMITED) && (millis() - nowUp > _frametime)) DEBUG_PRINTF_P(PSTR("Slow effects %u/%d.\n"), (unsigned)(millis()-nowUp), (int)_frametime);
|
||||
@@ -1328,14 +1330,14 @@ void WS2812FX::service() {
|
||||
if ((_targetFps != FPS_UNLIMITED) && (millis() - nowUp > _frametime)) DEBUG_PRINTF_P(PSTR("Slow strip %u/%d.\n"), (unsigned)(millis()-nowUp), (int)_frametime);
|
||||
#endif
|
||||
|
||||
_triggered = false;
|
||||
if (!_suspend) _triggered = false; // avoid losing "trigger" events if suspend requested during effect service()
|
||||
_isServicing = false;
|
||||
}
|
||||
|
||||
// https://en.wikipedia.org/wiki/Blend_modes but using a for top layer & b for bottom layer
|
||||
static uint8_t _top (uint8_t a, uint8_t b) { return a; }
|
||||
static uint8_t _bottom (uint8_t a, uint8_t b) { return b; }
|
||||
static uint8_t _add (uint8_t a, uint8_t b) { unsigned t = a + b; return t > 255 ? 255 : t; }
|
||||
static uint8_t _top (uint8_t a, uint8_t b) { return a; } // function unused
|
||||
static uint8_t _bottom (uint8_t a, uint8_t b) { return b; } // function unused
|
||||
static uint8_t _add (uint8_t a, uint8_t b) { unsigned t = a + b; return t > 255 ? 255 : t; } // function unused
|
||||
static uint8_t _subtract (uint8_t a, uint8_t b) { return b > a ? (b - a) : 0; }
|
||||
static uint8_t _difference(uint8_t a, uint8_t b) { return b > a ? (b - a) : (a - b); }
|
||||
static uint8_t _average (uint8_t a, uint8_t b) { return (a + b) >> 1; }
|
||||
@@ -1357,24 +1359,41 @@ static uint8_t _softlight (uint8_t a, uint8_t b) { return (b * b * (255 - 2 * a)
|
||||
#endif
|
||||
static uint8_t _dodge (uint8_t a, uint8_t b) { return _divide(~a,b); }
|
||||
static uint8_t _burn (uint8_t a, uint8_t b) { return ~_divide(a,~b); }
|
||||
static uint8_t _stencil (uint8_t a, uint8_t b) { return a ? a : b; } // function unused
|
||||
static uint8_t _dummy (uint8_t a, uint8_t b) { return a; } // dummy (same as _top) to fill the function list and make it safe from OOB access
|
||||
|
||||
#define BLENDMODES 17 // number of blend modes must match "bm" in index.js, all cases must be handled in segblend() @ blendSegment()
|
||||
|
||||
void WS2812FX::blendSegment(const Segment &topSegment) const {
|
||||
|
||||
typedef uint8_t(*FuncType)(uint8_t, uint8_t);
|
||||
// function pointer array: fill with _dummy if using special case: avoid OOB access and always provide a valid path
|
||||
FuncType funcs[] = {
|
||||
_top, _bottom,
|
||||
_add, _subtract, _difference, _average,
|
||||
_multiply, _divide, _lighten, _darken, _screen, _overlay,
|
||||
_hardlight, _softlight, _dodge, _burn
|
||||
_dummy, _dummy, _dummy, _subtract,
|
||||
_difference, _average, _dummy, _divide,
|
||||
_lighten, _darken, _screen, _overlay,
|
||||
_hardlight, _softlight, _dodge, _burn,
|
||||
_dummy
|
||||
};
|
||||
|
||||
const size_t blendMode = topSegment.blendMode < (sizeof(funcs) / sizeof(FuncType)) ? topSegment.blendMode : 0;
|
||||
const auto func = funcs[blendMode]; // blendMode % (sizeof(funcs) / sizeof(FuncType))
|
||||
const auto blend = [&](uint32_t top, uint32_t bottom){ return RGBW32(func(R(top),R(bottom)), func(G(top),G(bottom)), func(B(top),B(bottom)), func(W(top),W(bottom))); };
|
||||
const size_t blendMode = topSegment.blendMode < BLENDMODES ? topSegment.blendMode : 0; // default to top if unsupported mode
|
||||
const auto segblend = [&](uint32_t t, uint32_t b){
|
||||
// use direct calculations/returns for simple/frequent modes (faster)
|
||||
switch (blendMode) {
|
||||
case 0 : return t; // top
|
||||
case 1 : return b; // bottom
|
||||
case 2 : return color_add(t,b,true); // add with preserve color ratio to avoid color clipping
|
||||
case 6 : return RGBW32(_multiply(R(t),R(b)), _multiply(G(t),G(b)), _multiply(B(t),B(b)), _multiply(W(t),W(b))); // multiply (7% faster than lambda at 100bytes flash cost)
|
||||
case 16: return t ? t : b; // stencil (use top layer if not black, else bottom)
|
||||
}
|
||||
// default: use function pointer from array
|
||||
const auto func = funcs[blendMode];
|
||||
return RGBW32(func(R(t),R(b)), func(G(t),G(b)), func(B(t),B(b)), func(W(t),W(b)));
|
||||
};
|
||||
|
||||
const int length = topSegment.length(); // physical segment length (counts all pixels in 2D segment)
|
||||
const int width = topSegment.width();
|
||||
const int height = topSegment.height();
|
||||
//const uint32_t bgColor = topSegment.colors[1]; // background color (unused, could add it to stencil mode if requested)
|
||||
const auto XY = [](int x, int y){ return x + y*Segment::maxWidth; };
|
||||
const size_t matrixSize = Segment::maxWidth * Segment::maxHeight;
|
||||
const size_t startIndx = XY(topSegment.start, topSegment.startY);
|
||||
@@ -1383,61 +1402,62 @@ void WS2812FX::blendSegment(const Segment &topSegment) const {
|
||||
const unsigned progInv = 0xFFFFU - progress;
|
||||
uint8_t opacity = topSegment.currentBri(); // returns transitioned opacity for style FADE
|
||||
uint8_t cct = topSegment.currentCCT();
|
||||
if (gammaCorrectCol) opacity = gamma8inv(opacity); // use inverse gamma on brightness for correct color scaling after gamma correction (see #5343 for details)
|
||||
|
||||
Segment::setClippingRect(0, 0); // disable clipping by default
|
||||
|
||||
const unsigned dw = (blendingStyle==BLEND_STYLE_OUTSIDE_IN ? progInv : progress) * width / 0xFFFFU + 1;
|
||||
const unsigned dh = (blendingStyle==BLEND_STYLE_OUTSIDE_IN ? progInv : progress) * height / 0xFFFFU + 1;
|
||||
const unsigned dw = (blendingStyle==TRANSITION_OUTSIDE_IN ? progInv : progress) * width / 0xFFFFU + 1;
|
||||
const unsigned dh = (blendingStyle==TRANSITION_OUTSIDE_IN ? progInv : progress) * height / 0xFFFFU + 1;
|
||||
const unsigned orgBS = blendingStyle;
|
||||
if (width*height == 1) blendingStyle = BLEND_STYLE_FADE; // disable style for single pixel segments (use fade instead)
|
||||
if (width*height == 1) blendingStyle = TRANSITION_FADE; // disable style for single pixel segments (use fade instead)
|
||||
switch (blendingStyle) {
|
||||
case BLEND_STYLE_CIRCULAR_IN: // (must set entire segment, see isPixelXYClipped())
|
||||
case BLEND_STYLE_CIRCULAR_OUT:// (must set entire segment, see isPixelXYClipped())
|
||||
case BLEND_STYLE_FAIRY_DUST: // fairy dust (must set entire segment, see isPixelXYClipped())
|
||||
case TRANSITION_CIRCULAR_IN: // (must set entire segment, see isPixelXYClipped())
|
||||
case TRANSITION_CIRCULAR_OUT:// (must set entire segment, see isPixelXYClipped())
|
||||
case TRANSITION_FAIRY_DUST: // fairy dust (must set entire segment, see isPixelXYClipped())
|
||||
Segment::setClippingRect(0, width, 0, height);
|
||||
break;
|
||||
case BLEND_STYLE_SWIPE_RIGHT: // left-to-right
|
||||
case BLEND_STYLE_PUSH_RIGHT: // left-to-right
|
||||
case TRANSITION_SWIPE_RIGHT: // left-to-right
|
||||
case TRANSITION_PUSH_RIGHT: // left-to-right
|
||||
Segment::setClippingRect(0, dw, 0, height);
|
||||
break;
|
||||
case BLEND_STYLE_SWIPE_LEFT: // right-to-left
|
||||
case BLEND_STYLE_PUSH_LEFT: // right-to-left
|
||||
case TRANSITION_SWIPE_LEFT: // right-to-left
|
||||
case TRANSITION_PUSH_LEFT: // right-to-left
|
||||
Segment::setClippingRect(width - dw, width, 0, height);
|
||||
break;
|
||||
case BLEND_STYLE_OUTSIDE_IN: // corners
|
||||
case TRANSITION_OUTSIDE_IN: // corners
|
||||
Segment::setClippingRect((width + dw)/2, (width - dw)/2, (height + dh)/2, (height - dh)/2); // inverted!!
|
||||
break;
|
||||
case BLEND_STYLE_INSIDE_OUT: // outward
|
||||
case TRANSITION_INSIDE_OUT: // outward
|
||||
Segment::setClippingRect((width - dw)/2, (width + dw)/2, (height - dh)/2, (height + dh)/2);
|
||||
break;
|
||||
case BLEND_STYLE_SWIPE_DOWN: // top-to-bottom (2D)
|
||||
case BLEND_STYLE_PUSH_DOWN: // top-to-bottom (2D)
|
||||
case TRANSITION_SWIPE_DOWN: // top-to-bottom (2D)
|
||||
case TRANSITION_PUSH_DOWN: // top-to-bottom (2D)
|
||||
Segment::setClippingRect(0, width, 0, dh);
|
||||
break;
|
||||
case BLEND_STYLE_SWIPE_UP: // bottom-to-top (2D)
|
||||
case BLEND_STYLE_PUSH_UP: // bottom-to-top (2D)
|
||||
case TRANSITION_SWIPE_UP: // bottom-to-top (2D)
|
||||
case TRANSITION_PUSH_UP: // bottom-to-top (2D)
|
||||
Segment::setClippingRect(0, width, height - dh, height);
|
||||
break;
|
||||
case BLEND_STYLE_OPEN_H: // horizontal-outward (2D) same look as INSIDE_OUT on 1D
|
||||
case TRANSITION_OPEN_H: // horizontal-outward (2D) same look as INSIDE_OUT on 1D
|
||||
Segment::setClippingRect((width - dw)/2, (width + dw)/2, 0, height);
|
||||
break;
|
||||
case BLEND_STYLE_OPEN_V: // vertical-outward (2D)
|
||||
case TRANSITION_OPEN_V: // vertical-outward (2D)
|
||||
Segment::setClippingRect(0, width, (height - dh)/2, (height + dh)/2);
|
||||
break;
|
||||
case BLEND_STYLE_SWIPE_TL: // TL-to-BR (2D)
|
||||
case BLEND_STYLE_PUSH_TL: // TL-to-BR (2D)
|
||||
case TRANSITION_SWIPE_TL: // TL-to-BR (2D)
|
||||
case TRANSITION_PUSH_TL: // TL-to-BR (2D)
|
||||
Segment::setClippingRect(0, dw, 0, dh);
|
||||
break;
|
||||
case BLEND_STYLE_SWIPE_TR: // TR-to-BL (2D)
|
||||
case BLEND_STYLE_PUSH_TR: // TR-to-BL (2D)
|
||||
case TRANSITION_SWIPE_TR: // TR-to-BL (2D)
|
||||
case TRANSITION_PUSH_TR: // TR-to-BL (2D)
|
||||
Segment::setClippingRect(width - dw, width, 0, dh);
|
||||
break;
|
||||
case BLEND_STYLE_SWIPE_BR: // BR-to-TL (2D)
|
||||
case BLEND_STYLE_PUSH_BR: // BR-to-TL (2D)
|
||||
case TRANSITION_SWIPE_BR: // BR-to-TL (2D)
|
||||
case TRANSITION_PUSH_BR: // BR-to-TL (2D)
|
||||
Segment::setClippingRect(width - dw, width, height - dh, height);
|
||||
break;
|
||||
case BLEND_STYLE_SWIPE_BL: // BL-to-TR (2D)
|
||||
case BLEND_STYLE_PUSH_BL: // BL-to-TR (2D)
|
||||
case TRANSITION_SWIPE_BL: // BL-to-TR (2D)
|
||||
case TRANSITION_PUSH_BL: // BL-to-TR (2D)
|
||||
Segment::setClippingRect(0, dw, height - dh, height);
|
||||
break;
|
||||
}
|
||||
@@ -1454,18 +1474,18 @@ void WS2812FX::blendSegment(const Segment &topSegment) const {
|
||||
const int baseX = topSegment.start + x;
|
||||
const int baseY = topSegment.startY + y;
|
||||
size_t indx = XY(baseX, baseY); // absolute address on strip
|
||||
_pixels[indx] = color_blend(_pixels[indx], blend(c, _pixels[indx]), o);
|
||||
_pixels[indx] = color_blend(_pixels[indx], segblend(c, _pixels[indx]), o);
|
||||
if (_pixelCCT) _pixelCCT[indx] = cct;
|
||||
// Apply mirroring
|
||||
// Apply mirroring if enabled
|
||||
if (topSegment.mirror || topSegment.mirror_y) {
|
||||
const int mirrorX = topSegment.start + width - x - 1;
|
||||
const int mirrorY = topSegment.startY + height - y - 1;
|
||||
const size_t idxMX = XY(topSegment.transpose ? baseX : mirrorX, topSegment.transpose ? mirrorY : baseY);
|
||||
const size_t idxMY = XY(topSegment.transpose ? mirrorX : baseX, topSegment.transpose ? baseY : mirrorY);
|
||||
const size_t idxMM = XY(mirrorX, mirrorY);
|
||||
if (topSegment.mirror) _pixels[idxMX] = color_blend(_pixels[idxMX], blend(c, _pixels[idxMX]), o);
|
||||
if (topSegment.mirror_y) _pixels[idxMY] = color_blend(_pixels[idxMY], blend(c, _pixels[idxMY]), o);
|
||||
if (topSegment.mirror && topSegment.mirror_y) _pixels[idxMM] = color_blend(_pixels[idxMM], blend(c, _pixels[idxMM]), o);
|
||||
if (topSegment.mirror) _pixels[idxMX] = color_blend(_pixels[idxMX], segblend(c, _pixels[idxMX]), o);
|
||||
if (topSegment.mirror_y) _pixels[idxMY] = color_blend(_pixels[idxMY], segblend(c, _pixels[idxMY]), o);
|
||||
if (topSegment.mirror && topSegment.mirror_y) _pixels[idxMM] = color_blend(_pixels[idxMM], segblend(c, _pixels[idxMM]), o);
|
||||
if (_pixelCCT) {
|
||||
if (topSegment.mirror) _pixelCCT[idxMX] = cct;
|
||||
if (topSegment.mirror_y) _pixelCCT[idxMY] = cct;
|
||||
@@ -1475,9 +1495,22 @@ void WS2812FX::blendSegment(const Segment &topSegment) const {
|
||||
};
|
||||
|
||||
// if we blend using "push" style we need to "shift" canvas to left/right/up/down
|
||||
unsigned offsetX = (blendingStyle == BLEND_STYLE_PUSH_UP || blendingStyle == BLEND_STYLE_PUSH_DOWN) ? 0 : progInv * nCols / 0xFFFFU;
|
||||
unsigned offsetY = (blendingStyle == BLEND_STYLE_PUSH_LEFT || blendingStyle == BLEND_STYLE_PUSH_RIGHT) ? 0 : progInv * nRows / 0xFFFFU;
|
||||
|
||||
unsigned offsetX = (blendingStyle == TRANSITION_PUSH_UP || blendingStyle == TRANSITION_PUSH_DOWN) ? 0 : progInv * nCols / 0xFFFFU;
|
||||
unsigned offsetY = (blendingStyle == TRANSITION_PUSH_LEFT || blendingStyle == TRANSITION_PUSH_RIGHT) ? 0 : progInv * nRows / 0xFFFFU;
|
||||
const unsigned groupLen = topSegment.groupLength();
|
||||
bool applyReverse = topSegment.reverse || topSegment.reverse_y || topSegment.transpose;
|
||||
int pushOffsetX = 0, pushOffsetY = 0;
|
||||
// if we blend using "push" style we need to "shift" canvas to left/right/up/down
|
||||
switch (blendingStyle) {
|
||||
case TRANSITION_PUSH_RIGHT: pushOffsetX = offsetX; break;
|
||||
case TRANSITION_PUSH_LEFT: pushOffsetX = -offsetX + nCols; break;
|
||||
case TRANSITION_PUSH_DOWN: pushOffsetY = offsetY; break;
|
||||
case TRANSITION_PUSH_UP: pushOffsetY = -offsetY + nRows; break;
|
||||
case TRANSITION_PUSH_TL: pushOffsetX = offsetX; pushOffsetY = offsetY; break; // unused
|
||||
case TRANSITION_PUSH_TR: pushOffsetX = -offsetX + nCols; pushOffsetY = offsetY; break; // unused
|
||||
case TRANSITION_PUSH_BR: pushOffsetX = -offsetX + nCols; pushOffsetY = -offsetY + nRows; break; // unused
|
||||
case TRANSITION_PUSH_BL: pushOffsetX = offsetX; pushOffsetY = -offsetY + nRows; break; // unused
|
||||
}
|
||||
// we only traverse new segment, not old one
|
||||
for (int r = 0; r < nRows; r++) for (int c = 0; c < nCols; c++) {
|
||||
const bool clipped = topSegment.isPixelXYClipped(c, r);
|
||||
@@ -1487,21 +1520,16 @@ void WS2812FX::blendSegment(const Segment &topSegment) const {
|
||||
int vRows = seg == segO ? oRows : nRows; // old segment may have different dimensions
|
||||
int x = c;
|
||||
int y = r;
|
||||
// if we blend using "push" style we need to "shift" canvas to left/right/up/down
|
||||
switch (blendingStyle) {
|
||||
case BLEND_STYLE_PUSH_RIGHT: x = (x + offsetX) % nCols; break;
|
||||
case BLEND_STYLE_PUSH_LEFT: x = (x - offsetX + nCols) % nCols; break;
|
||||
case BLEND_STYLE_PUSH_DOWN: y = (y + offsetY) % nRows; break;
|
||||
case BLEND_STYLE_PUSH_UP: y = (y - offsetY + nRows) % nRows; break;
|
||||
}
|
||||
if (pushOffsetX != 0) x = (x + pushOffsetX) % nCols;
|
||||
if (pushOffsetY != 0) y = (y + pushOffsetY) % nRows;
|
||||
uint32_t c_a = BLACK;
|
||||
if (x < vCols && y < vRows) c_a = seg->getPixelColorRaw(x + y*vCols); // will get clipped pixel from old segment or unclipped pixel from new segment
|
||||
if (segO && blendingStyle == BLEND_STYLE_FADE
|
||||
if (segO && blendingStyle == TRANSITION_FADE
|
||||
&& (topSegment.mode != segO->mode || (segO->name != topSegment.name && segO->name && topSegment.name && strncmp(segO->name, topSegment.name, WLED_MAX_SEGNAME_LEN) != 0))
|
||||
&& x < oCols && y < oRows) {
|
||||
// we need to blend old segment using fade as pixels are not clipped
|
||||
c_a = color_blend16(c_a, segO->getPixelColorRaw(x + y*oCols), progInv);
|
||||
} else if (blendingStyle != BLEND_STYLE_FADE) {
|
||||
} else if (blendingStyle != TRANSITION_FADE) {
|
||||
// if we have global brightness change (not On/Off change) we will ignore transition style and just fade brightness (see led.cpp)
|
||||
// workaround for On/Off transition
|
||||
// (bri != briT) && !bri => from On to Off
|
||||
@@ -1511,11 +1539,12 @@ void WS2812FX::blendSegment(const Segment &topSegment) const {
|
||||
// map it into frame buffer
|
||||
x = c; // restore coordiates if we were PUSHing
|
||||
y = r;
|
||||
if (topSegment.reverse ) x = nCols - x - 1;
|
||||
if (topSegment.reverse_y) y = nRows - y - 1;
|
||||
if (topSegment.transpose) std::swap(x,y); // swap X & Y if segment transposed
|
||||
if (applyReverse) {
|
||||
if (topSegment.reverse ) x = nCols - x - 1;
|
||||
if (topSegment.reverse_y) y = nRows - y - 1;
|
||||
if (topSegment.transpose) std::swap(x,y); // swap X & Y if segment transposed
|
||||
}
|
||||
// expand pixel
|
||||
const unsigned groupLen = topSegment.groupLength();
|
||||
if (groupLen == 1) {
|
||||
setMirroredPixel(x, y, c_a, opacity);
|
||||
} else {
|
||||
@@ -1544,12 +1573,12 @@ void WS2812FX::blendSegment(const Segment &topSegment) const {
|
||||
unsigned indxM = topSegment.stop - i - 1;
|
||||
indxM += topSegment.offset; // offset/phase
|
||||
if (indxM >= topSegment.stop) indxM -= length; // wrap
|
||||
_pixels[indxM] = color_blend(_pixels[indxM], blend(c, _pixels[indxM]), o);
|
||||
_pixels[indxM] = color_blend(_pixels[indxM], segblend(c, _pixels[indxM]), o);
|
||||
if (_pixelCCT) _pixelCCT[indxM] = cct;
|
||||
}
|
||||
indx += topSegment.offset; // offset/phase
|
||||
if (indx >= topSegment.stop) indx -= length; // wrap
|
||||
_pixels[indx] = color_blend(_pixels[indx], blend(c, _pixels[indx]), o);
|
||||
_pixels[indx] = color_blend(_pixels[indx], segblend(c, _pixels[indx]), o);
|
||||
if (_pixelCCT) _pixelCCT[indx] = cct;
|
||||
};
|
||||
|
||||
@@ -1564,15 +1593,15 @@ void WS2812FX::blendSegment(const Segment &topSegment) const {
|
||||
int i = k;
|
||||
// if we blend using "push" style we need to "shift" canvas to left or right
|
||||
switch (blendingStyle) {
|
||||
case BLEND_STYLE_PUSH_RIGHT: i = (i + offsetI) % nLen; break;
|
||||
case BLEND_STYLE_PUSH_LEFT: i = (i - offsetI + nLen) % nLen; break;
|
||||
case TRANSITION_PUSH_RIGHT: i = (i + offsetI) % nLen; break;
|
||||
case TRANSITION_PUSH_LEFT: i = (i - offsetI + nLen) % nLen; break;
|
||||
}
|
||||
uint32_t c_a = BLACK;
|
||||
if (i < vLen) c_a = seg->getPixelColorRaw(i); // will get clipped pixel from old segment or unclipped pixel from new segment
|
||||
if (segO && blendingStyle == BLEND_STYLE_FADE && topSegment.mode != segO->mode && i < oLen) {
|
||||
if (segO && blendingStyle == TRANSITION_FADE && topSegment.mode != segO->mode && i < oLen) {
|
||||
// we need to blend old segment using fade as pixels are not clipped
|
||||
c_a = color_blend16(c_a, segO->getPixelColorRaw(i), progInv);
|
||||
} else if (blendingStyle != BLEND_STYLE_FADE) {
|
||||
} else if (blendingStyle != TRANSITION_FADE) {
|
||||
// if we have global brightness change (not On/Off change) we will ignore transition style and just fade brightness (see led.cpp)
|
||||
// workaround for On/Off transition
|
||||
// (bri != briT) && !bri => from On to Off
|
||||
@@ -1637,7 +1666,7 @@ void WS2812FX::show() {
|
||||
}
|
||||
|
||||
uint32_t c = _pixels[i]; // need a copy, do not modify _pixels directly (no byte access allowed on ESP32)
|
||||
if(c > 0 && !(realtimeMode && arlsDisableGammaCorrection))
|
||||
if (c > 0 && !(realtimeMode && arlsDisableGammaCorrection))
|
||||
c = gamma32(c); // apply gamma correction if enabled note: applying gamma after brightness has too much color loss
|
||||
BusManager::setPixelColor(getMappedPixelIndex(i), c);
|
||||
}
|
||||
@@ -1723,7 +1752,7 @@ void WS2812FX::setBrightness(uint8_t b, bool direct) {
|
||||
BusManager::setBrightness(scaledBri(b));
|
||||
if (!direct) {
|
||||
unsigned long t = millis();
|
||||
if (_segments[0].next_time > t + 22 && t - _lastShow > MIN_SHOW_DELAY) trigger(); //apply brightness change immediately if no refresh soon
|
||||
if (t - _lastShow > min(_frametime, uint16_t(FRAMETIME_FIXED))) trigger(); //apply brightness change immediately if no refresh soon, but don't speed up above 42fps
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1824,6 +1853,10 @@ void WS2812FX::resetSegments() {
|
||||
if (isServicing()) return;
|
||||
_segments.clear(); // destructs all Segment as part of clearing
|
||||
_segments.emplace_back(0, isMatrix ? Segment::maxWidth : _length, 0, isMatrix ? Segment::maxHeight : 1);
|
||||
if(_segments.size() == 0) {
|
||||
_segments.emplace_back(); // if out of heap, create a default segment
|
||||
errorFlag = ERR_NORAM_PX;
|
||||
}
|
||||
_segments.shrink_to_fit(); // just in case ...
|
||||
_mainSegment = 0;
|
||||
}
|
||||
@@ -1846,7 +1879,7 @@ void WS2812FX::makeAutoSegments(bool forceReset) {
|
||||
|
||||
for (size_t i = s; i < BusManager::getNumBusses(); i++) {
|
||||
const Bus *bus = BusManager::getBus(i);
|
||||
if (!bus || !bus->isOk()) break;
|
||||
if (!bus) break;
|
||||
|
||||
segStarts[s] = bus->getStart();
|
||||
segStops[s] = segStarts[s] + bus->getLength();
|
||||
@@ -1982,7 +2015,7 @@ bool WS2812FX::deserializeMap(unsigned n) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isFile || !requestJSONBufferLock(7)) return false;
|
||||
if (!isFile || !requestJSONBufferLock(JSON_LOCK_LEDMAP)) return false;
|
||||
|
||||
StaticJsonDocument<64> filter;
|
||||
filter[F("width")] = true;
|
||||
|
||||
+22
-18
@@ -48,6 +48,7 @@ ParticleSystem2D::ParticleSystem2D(uint32_t width, uint32_t height, uint32_t num
|
||||
sources[i].source.ttl = 1; //set source alive
|
||||
sources[i].sourceFlags.asByte = 0; // all flags disabled
|
||||
}
|
||||
perParticleSize = isadvanced; // enable per particle size by default if using advanced properties (FX can disable if needed)
|
||||
|
||||
}
|
||||
|
||||
@@ -79,9 +80,8 @@ void ParticleSystem2D::update(void) {
|
||||
}
|
||||
|
||||
// update function for fire animation
|
||||
void ParticleSystem2D::updateFire(const uint8_t intensity,const bool renderonly) {
|
||||
if (!renderonly)
|
||||
fireParticleupdate();
|
||||
void ParticleSystem2D::updateFire(const uint8_t intensity) {
|
||||
fireParticleupdate();
|
||||
fireIntesity = intensity > 0 ? intensity : 1; // minimum of 1, zero checking is used in render function
|
||||
render();
|
||||
}
|
||||
@@ -595,16 +595,15 @@ void ParticleSystem2D::render() {
|
||||
if (fireIntesity) { // fire mode
|
||||
brightness = (uint32_t)particles[i].ttl * (3 + (fireIntesity >> 5)) + 5;
|
||||
brightness = min(brightness, (uint32_t)255);
|
||||
baseRGB = ColorFromPaletteWLED(SEGPALETTE, brightness, 255, LINEARBLEND_NOWRAP); // map hue to brightness for fire effect
|
||||
baseRGB = ColorFromPalette(SEGPALETTE, brightness, 255, LINEARBLEND_NOWRAP);
|
||||
}
|
||||
else {
|
||||
brightness = min((particles[i].ttl << 1), (int)255);
|
||||
baseRGB = ColorFromPaletteWLED(SEGPALETTE, particles[i].hue, 255, blend);
|
||||
baseRGB = ColorFromPalette(SEGPALETTE, particles[i].hue, 255, blend);
|
||||
if (particles[i].sat < 255) {
|
||||
CHSV32 baseHSV;
|
||||
rgb2hsv(baseRGB.color32, baseHSV); // convert to HSV
|
||||
CHSV32 baseHSV = baseRGB;
|
||||
baseHSV.s = min(baseHSV.s, particles[i].sat); // set the saturation but don't increase it
|
||||
hsv2rgb(baseHSV, baseRGB.color32); // convert back to RGB
|
||||
hsv2rgb_spectrum(baseHSV, baseRGB); // convert back to RGB
|
||||
}
|
||||
}
|
||||
if (gammaCorrectCol) brightness = gamma8(brightness); // apply gamma correction, used for gamma-inverted brightness distribution
|
||||
@@ -805,7 +804,6 @@ void WLED_O2_ATTR ParticleSystem2D::renderLargeParticle(const uint32_t size, con
|
||||
if (gammaCorrectCol) {
|
||||
pixel_brightness = gamma8inv(pixel_brightness); // invert brigthess so brightness distribution is linear after gamma correction
|
||||
}
|
||||
|
||||
// Render pixel
|
||||
uint32_t idx = render_x + (maxYpixel - render_y) * matrixX; // flip y coordinate (0,0 is bottom left in PS but top left in framebuffer)
|
||||
framebuffer[idx] = fast_color_scaleAdd(framebuffer[idx], color, pixel_brightness);
|
||||
@@ -1096,7 +1094,11 @@ bool allocateParticleSystemMemory2D(uint32_t numparticles, uint32_t numsources,
|
||||
// initialize Particle System, allocate additional bytes if needed (pointer to those bytes can be read from particle system class: PSdataEnd)
|
||||
bool initParticleSystem2D(ParticleSystem2D *&PartSys, uint32_t requestedsources, uint32_t additionalbytes, bool advanced, bool sizecontrol) {
|
||||
PSPRINT("PS 2D init ");
|
||||
if (!strip.isMatrix) return false; // only for 2D
|
||||
if (!strip.isMatrix) {
|
||||
errorFlag = ERR_NOT_IMPL; // TODO: need a better error code if more codes are added
|
||||
SEGMENT.deallocateData(); // deallocate any data to make sure data is null (there is no valid PS in data and data can only be checked for null)
|
||||
return false; // only for 2D
|
||||
}
|
||||
uint32_t cols = SEGMENT.virtualWidth();
|
||||
uint32_t rows = SEGMENT.virtualHeight();
|
||||
uint32_t pixels = cols * rows;
|
||||
@@ -1156,7 +1158,7 @@ ParticleSystem1D::ParticleSystem1D(uint32_t length, uint32_t numberofparticles,
|
||||
sources[i].source.ttl = 1; //set source alive
|
||||
sources[i].sourceFlags.asByte = 0; // all flags disabled
|
||||
}
|
||||
|
||||
perParticleSize = isadvanced; // enable per particle size by default so FX do not need to set this explicitly. FX can disable by setting global size.
|
||||
if (isadvanced) {
|
||||
for (uint32_t i = 0; i < numParticles; i++) {
|
||||
advPartProps[i].sat = 255; // set full saturation
|
||||
@@ -1453,14 +1455,12 @@ void ParticleSystem1D::render() {
|
||||
|
||||
// generate RGB values for particle
|
||||
brightness = min(particles[i].ttl << 1, (int)255);
|
||||
baseRGB = ColorFromPaletteWLED(SEGPALETTE, particles[i].hue, 255, blend);
|
||||
|
||||
baseRGB = ColorFromPalette(SEGPALETTE, particles[i].hue, 255, blend);
|
||||
if (advPartProps != nullptr) { //saturation is advanced property in 1D system
|
||||
if (advPartProps[i].sat < 255) {
|
||||
CHSV32 baseHSV;
|
||||
rgb2hsv(baseRGB.color32, baseHSV); // convert to HSV
|
||||
baseHSV.s = min(baseHSV.s, advPartProps[i].sat); // set the saturation but don't increase it
|
||||
hsv2rgb(baseHSV, baseRGB.color32); // convert back to RGB
|
||||
CHSV32 baseHSV = baseRGB;
|
||||
baseHSV.s = advPartProps[i].sat; // set the saturation
|
||||
hsv2rgb_spectrum(baseHSV, baseRGB); // convert back to RGB
|
||||
}
|
||||
}
|
||||
if (gammaCorrectCol) brightness = gamma8(brightness); // apply gamma correction, used for gamma-inverted brightness distribution
|
||||
@@ -1844,7 +1844,11 @@ bool allocateParticleSystemMemory1D(const uint32_t numparticles, const uint32_t
|
||||
// initialize Particle System, allocate additional bytes if needed (pointer to those bytes can be read from particle system class: PSdataEnd)
|
||||
// note: percentofparticles is in uint8_t, for example 191 means 75%, (deafaults to 255 or 100% meaning one particle per pixel), can be more than 100% (but not recommended, can cause out of memory)
|
||||
bool initParticleSystem1D(ParticleSystem1D *&PartSys, const uint32_t requestedsources, const uint8_t fractionofparticles, const uint32_t additionalbytes, const bool advanced) {
|
||||
if (SEGLEN == 1) return false; // single pixel not supported
|
||||
if (SEGLEN == 1) {
|
||||
errorFlag = ERR_NOT_IMPL; // TODO: need a better error code if more codes are added
|
||||
SEGMENT.deallocateData(); // deallocate any data to make sure data is null (there is no valid PS in data and data can only be checked for null)
|
||||
return false; // single pixel not supported
|
||||
}
|
||||
uint32_t numparticles = calculateNumberOfParticles1D(fractionofparticles, advanced);
|
||||
uint32_t numsources = calculateNumberOfSources1D(requestedsources);
|
||||
bool allocsuccess = false;
|
||||
|
||||
@@ -143,7 +143,7 @@ public:
|
||||
ParticleSystem2D(const uint32_t width, const uint32_t height, const uint32_t numberofparticles, const uint32_t numberofsources, const bool isadvanced = false, const bool sizecontrol = false); // constructor
|
||||
// note: memory is allcated in the FX function, no deconstructor needed
|
||||
void update(void); //update the particles according to set options and render to the matrix
|
||||
void updateFire(const uint8_t intensity, const bool renderonly); // update function for fire, if renderonly is set, particles are not updated (required to fix transitions with frameskips)
|
||||
void updateFire(const uint8_t intensity); // update function for fire
|
||||
void updateSystem(void); // call at the beginning of every FX, updates pointers and dimensions
|
||||
void particleMoveUpdate(PSparticle &part, PSparticleFlags &partFlags, PSsettings2D *options = NULL, PSadvancedParticle *advancedproperties = NULL); // move function
|
||||
// particle emitters
|
||||
|
||||
@@ -15,6 +15,22 @@
|
||||
#define NODE_TYPE_ID_ESP32S3 34
|
||||
#define NODE_TYPE_ID_ESP32C3 35
|
||||
|
||||
// updated node types from the ESP Easy project
|
||||
// https://github.com/letscontrolit/ESPEasy/blob/mega/src/src/DataTypes/NodeTypeID.h
|
||||
//#define NODE_TYPE_ID_ESP32 33
|
||||
//#define NODE_TYPE_ID_ESP32S2 34
|
||||
//#define NODE_TYPE_ID_ESP32C3 35
|
||||
//#define NODE_TYPE_ID_ESP32S3 36
|
||||
#define NODE_TYPE_ID_ESP32C2 37
|
||||
#define NODE_TYPE_ID_ESP32H2 38
|
||||
#define NODE_TYPE_ID_ESP32C6 39
|
||||
#define NODE_TYPE_ID_ESP32C61 40
|
||||
#define NODE_TYPE_ID_ESP32C5 41
|
||||
#define NODE_TYPE_ID_ESP32P4 42
|
||||
#define NODE_TYPE_ID_ESP32P4r3 45
|
||||
#define NODE_TYPE_ID_ESP32H21 43
|
||||
#define NODE_TYPE_ID_ESP32H4 44
|
||||
|
||||
/*********************************************************************************************\
|
||||
* NodeStruct
|
||||
\*********************************************************************************************/
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
/*
|
||||
asyncDNS.h - wrapper class for asynchronous DNS lookups using lwIP
|
||||
by @dedehai, C++ improvements & hardening by @willmmiles
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <lwip/dns.h>
|
||||
#include <lwip/err.h>
|
||||
|
||||
class AsyncDNS {
|
||||
|
||||
// C++14 shim
|
||||
#if __cplusplus < 201402L
|
||||
// Really simple C++11 shim for non-array case; implementation from cppreference.com
|
||||
template<class T, class... Args>
|
||||
static std::unique_ptr<T>
|
||||
make_unique(Args&&... args)
|
||||
{
|
||||
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
|
||||
}
|
||||
#endif
|
||||
|
||||
public:
|
||||
// note: passing the IP as a pointer to query() is not implemented because it is not thread-safe without mutexes
|
||||
// with the IDF V4 bug external error handling is required anyway or dns can just stay stuck
|
||||
enum class result { Idle, Busy, Success, Error };
|
||||
|
||||
// non-blocking query function to start DNS lookup
|
||||
static std::shared_ptr<AsyncDNS> query(const char* hostname, std::shared_ptr<AsyncDNS> current = {}) {
|
||||
if (!current || (current->_status == result::Busy)) {
|
||||
current.reset(new AsyncDNS());
|
||||
}
|
||||
|
||||
#if __cplusplus >= 201402L
|
||||
using std::make_unique;
|
||||
#endif
|
||||
|
||||
std::unique_ptr<std::shared_ptr<AsyncDNS>> callback_state = make_unique<std::shared_ptr<AsyncDNS> >(current);
|
||||
if (!callback_state) return {};
|
||||
|
||||
current->_status = result::Busy;
|
||||
err_t err = dns_gethostbyname(hostname, ¤t->_raw_addr, _dns_callback, callback_state.get());
|
||||
if (err == ERR_OK) {
|
||||
current->_status = result::Success; // result already in cache
|
||||
} else if (err == ERR_INPROGRESS) {
|
||||
callback_state.release(); // belongs to the callback now
|
||||
} else {
|
||||
current->_status = result::Error;
|
||||
current->_errorcount++;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
// get the IP once Success is returned
|
||||
const IPAddress getIP() {
|
||||
if (_status != result::Success) return IPAddress(0,0,0,0);
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
return IPAddress(_raw_addr.u_addr.ip4.addr);
|
||||
#else
|
||||
return IPAddress(_raw_addr.addr);
|
||||
#endif
|
||||
}
|
||||
|
||||
void reset() { _errorcount = 0; } // reset status and error count
|
||||
const result status() { return _status; }
|
||||
const uint16_t getErrorCount() { return _errorcount; }
|
||||
|
||||
private:
|
||||
ip_addr_t _raw_addr;
|
||||
std::atomic<result> _status { result::Idle };
|
||||
uint16_t _errorcount = 0;
|
||||
|
||||
AsyncDNS(){}; // may not be explicitly instantiated - use query()
|
||||
|
||||
// callback for dns_gethostbyname(), called when lookup is complete or timed out
|
||||
static void _dns_callback(const char *name, const ip_addr_t *ipaddr, void *arg) {
|
||||
std::shared_ptr<AsyncDNS>* instance_ptr = reinterpret_cast<std::shared_ptr<AsyncDNS>*>(arg);
|
||||
AsyncDNS& instance = **instance_ptr;
|
||||
if (ipaddr) {
|
||||
instance._raw_addr = *ipaddr;
|
||||
instance._status = result::Success;
|
||||
} else {
|
||||
instance._status = result::Error; // note: if query timed out (~5s), DNS lookup is broken until WiFi connection is reset (IDF V4 bug)
|
||||
instance._errorcount++;
|
||||
}
|
||||
delete instance_ptr;
|
||||
}
|
||||
};
|
||||
+174
-137
@@ -9,14 +9,6 @@
|
||||
#include "src/dependencies/network/Network.h" // for isConnected() (& WiFi)
|
||||
#include "driver/ledc.h"
|
||||
#include "soc/ledc_struct.h"
|
||||
#if !(defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3))
|
||||
#define LEDC_MUTEX_LOCK() do {} while (xSemaphoreTake(_ledc_sys_lock, portMAX_DELAY) != pdPASS)
|
||||
#define LEDC_MUTEX_UNLOCK() xSemaphoreGive(_ledc_sys_lock)
|
||||
extern xSemaphoreHandle _ledc_sys_lock;
|
||||
#else
|
||||
#define LEDC_MUTEX_LOCK()
|
||||
#define LEDC_MUTEX_UNLOCK()
|
||||
#endif
|
||||
#endif
|
||||
#ifdef ESP8266
|
||||
#include "core_esp8266_waveform.h"
|
||||
@@ -25,21 +17,17 @@
|
||||
#include "bus_wrapper.h"
|
||||
#include "wled.h"
|
||||
|
||||
extern char cmDNS[];
|
||||
extern bool cctICused;
|
||||
extern bool useParallelI2S;
|
||||
|
||||
// functions to get/set bits in an array - based on functions created by Brandon for GOL
|
||||
// toDo : make this a class that's completely defined in a header file
|
||||
// note: these functions are automatically inline by the compiler
|
||||
bool getBitFromArray(const uint8_t* byteArray, size_t position) { // get bit value
|
||||
static inline bool getBitFromArray(const uint8_t* byteArray, size_t position) { // get bit value
|
||||
size_t byteIndex = position >> 3; // divide by 8
|
||||
unsigned bitIndex = position & 0x07; // modulo 8
|
||||
uint8_t byteValue = byteArray[byteIndex];
|
||||
return (byteValue >> bitIndex) & 1;
|
||||
}
|
||||
|
||||
void setBitInArray(uint8_t* byteArray, size_t position, bool value) { // set bit - with error handling for nullptr
|
||||
static inline void setBitInArray(uint8_t* byteArray, size_t position, bool value) { // set bit - with error handling for nullptr
|
||||
//if (byteArray == nullptr) return;
|
||||
size_t byteIndex = position >> 3; // divide by 8
|
||||
unsigned bitIndex = position & 0x07; // modulo 8
|
||||
@@ -49,11 +37,11 @@ void setBitInArray(uint8_t* byteArray, size_t position, bool value) { // set bi
|
||||
byteArray[byteIndex] &= ~(1 << bitIndex);
|
||||
}
|
||||
|
||||
size_t getBitArrayBytes(size_t num_bits) { // number of bytes needed for an array with num_bits bits
|
||||
static inline size_t getBitArrayBytes(size_t num_bits) { // number of bytes needed for an array with num_bits bits
|
||||
return (num_bits + 7) >> 3;
|
||||
}
|
||||
|
||||
void setBitArray(uint8_t* byteArray, size_t numBits, bool value) { // set all bits to same value
|
||||
static inline void setBitArray(uint8_t* byteArray, size_t numBits, bool value) { // set all bits to same value
|
||||
if (byteArray == nullptr) return;
|
||||
size_t len = getBitArrayBytes(numBits);
|
||||
if (value) memset(byteArray, 0xFF, len);
|
||||
@@ -90,42 +78,67 @@ void Bus::calculateCCT(uint32_t c, uint8_t &ww, uint8_t &cw) {
|
||||
cct = (approximateKelvinFromRGB(c) - 1900) >> 5; // convert K (from RGB value) to relative format
|
||||
}
|
||||
|
||||
//0 - linear (CCT 127 = 50% warm, 50% cold), 127 - additive CCT blending (CCT 127 = 100% warm, 100% cold)
|
||||
if (cct < _cctBlend) ww = 255;
|
||||
else ww = ((255-cct) * 255) / (255 - _cctBlend);
|
||||
if ((255-cct) < _cctBlend) cw = 255;
|
||||
else cw = (cct * 255) / (255 - _cctBlend);
|
||||
// CCT blending modes (_cctBlend):
|
||||
// blend<0: ww: ▓▓▒░__ | blend=0: ww: ▓▒▒░░ | blend>0 ww: ▓▓▓▒░
|
||||
// cw: __░▒▓▓ | cw: ░░▒▒▓ | cw: ░▒▓▓▓
|
||||
int32_t ww_val, cw_val;
|
||||
if (_cctBlend < 0) {
|
||||
uint16_t range = 255 - 2 * (uint16_t)(-_cctBlend);
|
||||
if (range > 255) range = 255; // prevent overflow
|
||||
ww_val = range ? ((int32_t)(255 + _cctBlend - cct) * 255) / range : (cct < 128 ? 255 : 0); // exclusive blending
|
||||
cw_val = 255 - ww_val;
|
||||
} else {
|
||||
ww_val = _cctBlend ? ((int32_t)(255 - cct) * 255) / (255 - _cctBlend) : 255 - cct; // additive blending
|
||||
cw_val = _cctBlend ? ((int32_t) cct * 255) / (255 - _cctBlend) : cct;
|
||||
}
|
||||
ww = (uint8_t)(ww_val < 0 ? 0 : ww_val > 255 ? 255 : ww_val);
|
||||
cw = (uint8_t)(cw_val < 0 ? 0 : cw_val > 255 ? 255 : cw_val);
|
||||
|
||||
ww = (w * ww) / 255; //brightness scaling
|
||||
cw = (w * cw) / 255;
|
||||
}
|
||||
|
||||
uint32_t Bus::autoWhiteCalc(uint32_t c) const {
|
||||
// calculates white channel and CCT values based on given settings
|
||||
uint32_t Bus::autoWhiteCalc(uint32_t c, uint8_t &ww, uint8_t &cw) const {
|
||||
unsigned aWM = _autoWhiteMode;
|
||||
if (_gAWM < AW_GLOBAL_DISABLED) aWM = _gAWM;
|
||||
if (aWM == RGBW_MODE_MANUAL_ONLY) return c;
|
||||
CRGBW cIn = c; // save original color for CCT calculation
|
||||
unsigned w = W(c);
|
||||
//ignore auto-white calculation if w>0 and mode DUAL (DUAL behaves as BRIGHTER if w==0)
|
||||
if (w > 0 && aWM == RGBW_MODE_DUAL) return c;
|
||||
unsigned r = R(c);
|
||||
unsigned g = G(c);
|
||||
unsigned b = B(c);
|
||||
if (aWM == RGBW_MODE_MAX) return RGBW32(r, g, b, r > g ? (r > b ? r : b) : (g > b ? g : b)); // brightest RGB channel
|
||||
w = r < g ? (r < b ? r : b) : (g < b ? g : b);
|
||||
if (aWM == RGBW_MODE_AUTO_ACCURATE) { r -= w; g -= w; b -= w; } //subtract w in ACCURATE mode
|
||||
return RGBW32(r, g, b, w);
|
||||
if (aWM != RGBW_MODE_MANUAL_ONLY) {
|
||||
unsigned r = R(c); // note: using uint8_t generates larger code
|
||||
unsigned g = G(c);
|
||||
unsigned b = B(c);
|
||||
if (aWM == RGBW_MODE_DUAL && w > 0) {
|
||||
//ignore auto-white calculation if w>0 and mode DUAL (DUAL behaves as BRIGHTER if w==0)
|
||||
} else if (aWM == RGBW_MODE_MAX) {
|
||||
w = r > g ? (r > b ? r : b) : (g > b ? g : b); // brightest RGB channel
|
||||
} else {
|
||||
w = r < g ? (r < b ? r : b) : (g < b ? g : b); // darkest RGB channel
|
||||
if (aWM == RGBW_MODE_AUTO_ACCURATE) { r -= w; g -= w; b -= w; } //subtract w in ACCURATE mode
|
||||
}
|
||||
c = RGBW32(r, g, b, w);
|
||||
}
|
||||
if (_hasCCT) {
|
||||
cIn.w = w; // need original rgb values in case CCT is derived from RGB
|
||||
calculateCCT(cIn, ww, cw);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
BusDigital::BusDigital(const BusConfig &bc, uint8_t nr)
|
||||
BusDigital::BusDigital(const BusConfig &bc)
|
||||
: Bus(bc.type, bc.start, bc.autoWhite, bc.count, bc.reversed, (bc.refreshReq || bc.type == TYPE_TM1814))
|
||||
, _skip(bc.skipAmount) //sacrificial pixels
|
||||
, _colorOrder(bc.colorOrder)
|
||||
, _milliAmpsPerLed(bc.milliAmpsPerLed)
|
||||
, _milliAmpsMax(bc.milliAmpsMax)
|
||||
, _driverType(bc.driverType) // Store driver preference (0=RMT, 1=I2S)
|
||||
{
|
||||
DEBUGBUS_PRINTLN(F("Bus: Creating digital bus."));
|
||||
if (!isDigital(bc.type) || !bc.count) { DEBUGBUS_PRINTLN(F("Not digial or empty bus!")); return; }
|
||||
_iType = bc.iType; // reuse the iType that was determined by polyBus in getI() in finalizeInit()
|
||||
if (_iType == I_NONE) { DEBUGBUS_PRINTLN(F("Incorrect iType!")); return; }
|
||||
|
||||
if (!PinManager::allocatePin(bc.pins[0], true, PinOwner::BusDigital)) { DEBUGBUS_PRINTLN(F("Pin 0 allocated!")); return; }
|
||||
_frequencykHz = 0U;
|
||||
_colorSum = 0;
|
||||
@@ -139,28 +152,30 @@ BusDigital::BusDigital(const BusConfig &bc, uint8_t nr)
|
||||
_pins[1] = bc.pins[1];
|
||||
_frequencykHz = bc.frequency ? bc.frequency : 2000U; // 2MHz clock if undefined
|
||||
}
|
||||
_iType = PolyBus::getI(bc.type, _pins, nr);
|
||||
if (_iType == I_NONE) { DEBUGBUS_PRINTLN(F("Incorrect iType!")); return; }
|
||||
|
||||
_hasRgb = hasRGB(bc.type);
|
||||
_hasWhite = hasWhite(bc.type);
|
||||
_hasCCT = hasCCT(bc.type);
|
||||
uint16_t lenToCreate = bc.count;
|
||||
if (bc.type == TYPE_WS2812_1CH_X3) lenToCreate = NUM_ICS_WS2812_1CH_3X(bc.count); // only needs a third of "RGB" LEDs for NeoPixelBus
|
||||
_busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip, nr);
|
||||
_busPtr = PolyBus::create(_iType, _pins, lenToCreate + _skip);
|
||||
_valid = (_busPtr != nullptr) && bc.count > 0;
|
||||
// fix for wled#4759
|
||||
if (_valid) for (unsigned i = 0; i < _skip; i++) {
|
||||
PolyBus::setPixelColor(_busPtr, _iType, i, 0, COL_ORDER_GRB); // set sacrificial pixels to black (CO does not matter here)
|
||||
}
|
||||
DEBUGBUS_PRINTF_P(PSTR("Bus: %successfully inited #%u (len:%u, type:%u (RGB:%d, W:%d, CCT:%d), pins:%u,%u [itype:%u] mA=%d/%d)\n"),
|
||||
_valid?"S":"Uns",
|
||||
(int)nr,
|
||||
else {
|
||||
cleanup();
|
||||
}
|
||||
DEBUGBUS_PRINTF_P(PSTR("Bus len:%u, type:%u (RGB:%d, W:%d, CCT:%d), pins:%u,%u [itype:%u, driver:%s] mA=%d/%d %s\n"),
|
||||
(int)bc.count,
|
||||
(int)bc.type,
|
||||
(int)_hasRgb, (int)_hasWhite, (int)_hasCCT,
|
||||
(unsigned)_pins[0], is2Pin(bc.type)?(unsigned)_pins[1]:255U,
|
||||
(unsigned)_iType,
|
||||
(int)_milliAmpsPerLed, (int)_milliAmpsMax
|
||||
isI2S() ? "I2S" : "RMT",
|
||||
(int)_milliAmpsPerLed, (int)_milliAmpsMax,
|
||||
_valid ? " " : "FAILED"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -211,15 +226,20 @@ void BusDigital::applyBriLimit(uint8_t newBri) {
|
||||
|
||||
if (newBri < 255) {
|
||||
_NPBbri = newBri; // store value so it can be updated in show() (must be updated even if ABL is not used)
|
||||
uint8_t cctWW = 0, cctCW = 0;
|
||||
uint16_t wwcw = 0;
|
||||
unsigned hwLen = _len;
|
||||
if (_type == TYPE_WS2812_1CH_X3) hwLen = NUM_ICS_WS2812_1CH_3X(_len); // only needs a third of "RGB" LEDs for NeoPixelBus
|
||||
for (unsigned i = 0; i < hwLen; i++) {
|
||||
uint8_t co = _colorOrderMap.getPixelColorOrder(i+_start, _colorOrder); // need to revert color order for correct color scaling and CCT calc in case white is swapped
|
||||
uint32_t c = PolyBus::getPixelColor(_busPtr, _iType, i, co);
|
||||
uint32_t c = PolyBus::getPixelColor(_busPtr, _iType, i, co); // Note: if ABL would be calculated as a seperate loop (as it was before) it is slower but could use original color, making it more color-accurate
|
||||
if (hasCCT()) {
|
||||
uint8_t cctWW, cctCW;
|
||||
Bus::calculateCCT(c, cctWW, cctCW); // calculate CCT before fade (more accurate) | Note: if using "accurate" white calculation mode, approximateKelvinFromRGB can be very inaccurate (white is subtracted)
|
||||
wwcw = ((cctCW + 1) * newBri) & 0xFF00; // apply brightness to CCT (leave it in upper byte for 16bit NeoPixelBus value)
|
||||
wwcw |= ((cctWW + 1) * newBri) >> 8;
|
||||
}
|
||||
c = color_fade(c, newBri, true); // apply additional dimming note: using inline version is a bit faster but overhead of getPixelColor() dominates the speed impact by far
|
||||
if (hasCCT()) Bus::calculateCCT(c, cctWW, cctCW);
|
||||
PolyBus::setPixelColor(_busPtr, _iType, i, c, co, (cctCW<<8) | cctWW); // repaint all pixels with new brightness
|
||||
PolyBus::setPixelColor(_busPtr, _iType, i, c, co, wwcw); // repaint all pixels with new brightness
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,12 +266,21 @@ void BusDigital::setStatusPixel(uint32_t c) {
|
||||
}
|
||||
}
|
||||
|
||||
// note: using WLED_O2_ATTR makes this function ~7% faster at the expense of 600 bytes of flash
|
||||
void IRAM_ATTR BusDigital::setPixelColor(unsigned pix, uint32_t c) {
|
||||
if (!_valid) return;
|
||||
if (hasWhite()) c = autoWhiteCalc(c);
|
||||
if (Bus::_cct >= 1900) c = colorBalanceFromKelvin(Bus::_cct, c); //color correction from CCT
|
||||
uint8_t cctWW = 0, cctCW = 0;
|
||||
uint16_t wwcw = 0;
|
||||
if (hasWhite()) c = autoWhiteCalc(c, cctWW, cctCW);
|
||||
c = color_fade(c, _bri, true); // apply brightness
|
||||
|
||||
if (hasCCT()) {
|
||||
wwcw = ((cctCW + 1) * _bri) & 0xFF00; // apply brightness to CCT (store CW in upper byte)
|
||||
wwcw |= ((cctWW + 1) * _bri) >> 8;
|
||||
if (_type == TYPE_WS2812_WWA) c = RGBW32(wwcw, wwcw >> 8, 0, W(c)); // ww,cw, 0, w
|
||||
}
|
||||
|
||||
if (BusManager::_useABL) {
|
||||
// if using ABL, sum all color channels to estimate current and limit brightness in show()
|
||||
uint8_t r = R(c), g = G(c), b = B(c);
|
||||
@@ -275,13 +304,7 @@ void IRAM_ATTR BusDigital::setPixelColor(unsigned pix, uint32_t c) {
|
||||
case 2: c = RGBW32(R(cOld), G(cOld), W(c) , 0); break;
|
||||
}
|
||||
}
|
||||
uint16_t wwcw = 0;
|
||||
if (hasCCT()) {
|
||||
uint8_t cctWW = 0, cctCW = 0;
|
||||
Bus::calculateCCT(c, cctWW, cctCW);
|
||||
wwcw = (cctCW<<8) | cctWW;
|
||||
if (_type == TYPE_WS2812_WWA) c = RGBW32(cctWW, cctCW, 0, W(c));
|
||||
}
|
||||
|
||||
PolyBus::setPixelColor(_busPtr, _iType, pix, c, co, wwcw);
|
||||
}
|
||||
|
||||
@@ -351,6 +374,10 @@ std::vector<LEDType> BusDigital::getLEDTypes() {
|
||||
};
|
||||
}
|
||||
|
||||
bool BusDigital::isI2S() {
|
||||
return (_iType & 0x01) == 0; // I2S types have even iType values
|
||||
}
|
||||
|
||||
void BusDigital::begin() {
|
||||
if (!_valid) return;
|
||||
PolyBus::begin(_busPtr, _iType, _pins, _frequencykHz);
|
||||
@@ -443,11 +470,13 @@ BusPwm::BusPwm(const BusConfig &bc)
|
||||
|
||||
void BusPwm::setPixelColor(unsigned pix, uint32_t c) {
|
||||
if (pix != 0 || !_valid) return; //only react to first pixel
|
||||
if (_type != TYPE_ANALOG_3CH) c = autoWhiteCalc(c);
|
||||
if (Bus::_cct >= 1900 && (_type == TYPE_ANALOG_3CH || _type == TYPE_ANALOG_4CH)) {
|
||||
c = colorBalanceFromKelvin(Bus::_cct, c); //color correction from CCT
|
||||
}
|
||||
uint8_t cctWW, cctCW;
|
||||
if (_type != TYPE_ANALOG_3CH) c = autoWhiteCalc(c, cctWW, cctCW);
|
||||
uint8_t r = R(c), g = G(c), b = B(c), w = W(c);
|
||||
// note: no color scaling, brightness is applied in show()
|
||||
|
||||
switch (_type) {
|
||||
case TYPE_ANALOG_1CH: //one channel (white), relies on auto white calculation
|
||||
@@ -458,14 +487,18 @@ void BusPwm::setPixelColor(unsigned pix, uint32_t c) {
|
||||
_data[0] = w;
|
||||
_data[1] = Bus::_cct < 0 || Bus::_cct > 255 ? 127 : Bus::_cct;
|
||||
} else {
|
||||
Bus::calculateCCT(c, _data[0], _data[1]);
|
||||
_data[0] = cctWW;
|
||||
_data[1] = cctCW;
|
||||
}
|
||||
break;
|
||||
case TYPE_ANALOG_5CH: //RGB + warm white + cold white
|
||||
if (cctICused)
|
||||
_data[4] = Bus::_cct < 0 || Bus::_cct > 255 ? 127 : Bus::_cct;
|
||||
else
|
||||
Bus::calculateCCT(c, w, _data[4]);
|
||||
else {
|
||||
w = cctWW;
|
||||
_data[4] = cctCW;
|
||||
}
|
||||
// fall through to set RGBW channels
|
||||
case TYPE_ANALOG_4CH: //RGBW
|
||||
_data[3] = w;
|
||||
case TYPE_ANALOG_3CH: //standard dumb RGB
|
||||
@@ -532,7 +565,7 @@ void BusPwm::show() {
|
||||
unsigned duty = (_data[i] * pwmBri) / 255;
|
||||
unsigned deadTime = 0;
|
||||
|
||||
if (_type == TYPE_ANALOG_2CH && Bus::_cctBlend == 0) {
|
||||
if (_type == TYPE_ANALOG_2CH && Bus::_cctBlend <= 0) {
|
||||
// add dead time between signals (when using dithering, two full 8bit pulses are required)
|
||||
deadTime = (1+dithering) << bitShift;
|
||||
// we only need to take care of shortening the signal at (almost) full brightness otherwise pulses may overlap
|
||||
@@ -621,9 +654,7 @@ BusOnOff::BusOnOff(const BusConfig &bc)
|
||||
|
||||
void BusOnOff::setPixelColor(unsigned pix, uint32_t c) {
|
||||
if (pix != 0 || !_valid) return; //only react to first pixel
|
||||
c = autoWhiteCalc(c);
|
||||
uint8_t r = R(c), g = G(c), b = B(c), w = W(c);
|
||||
_data = bool(r|g|b|w) && bool(_bri) ? 0xFF : 0;
|
||||
_data = (c > 0) && bool(_bri) ? 0xFF : 0; // if any color channel is on and brightness is not zero, set to on
|
||||
}
|
||||
|
||||
uint32_t BusOnOff::getPixelColor(unsigned pix) const {
|
||||
@@ -683,7 +714,8 @@ BusNetwork::BusNetwork(const BusConfig &bc)
|
||||
|
||||
void BusNetwork::setPixelColor(unsigned pix, uint32_t c) {
|
||||
if (!_valid || pix >= _len) return;
|
||||
if (_hasWhite) c = autoWhiteCalc(c);
|
||||
uint8_t ww, cw; // dummy, unused
|
||||
if (_hasWhite) c = autoWhiteCalc(c, ww, cw);
|
||||
if (Bus::_cct >= 1900) c = colorBalanceFromKelvin(Bus::_cct, c); //color correction from CCT
|
||||
unsigned offset = pix * _UDPchannels;
|
||||
_data[offset] = R(c);
|
||||
@@ -712,13 +744,23 @@ size_t BusNetwork::getPins(uint8_t* pinArray) const {
|
||||
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
void BusNetwork::resolveHostname() {
|
||||
static unsigned long nextResolve = 0;
|
||||
if (Network.isConnected() && millis() > nextResolve && _hostname.length() > 0) {
|
||||
nextResolve = millis() + 600000; // resolve only every 10 minutes
|
||||
static std::shared_ptr<AsyncDNS> DNSlookup; // TODO: make this dynamic? requires to handle the callback properly
|
||||
if (Network.isConnected()) {
|
||||
IPAddress clnt;
|
||||
if (strlen(cmDNS) > 0) clnt = MDNS.queryHost(_hostname);
|
||||
else WiFi.hostByName(_hostname.c_str(), clnt);
|
||||
if (clnt != IPAddress()) _client = clnt;
|
||||
if (strlen(cmDNS) > 0) {
|
||||
clnt = MDNS.queryHost(_hostname);
|
||||
if (clnt != IPAddress()) _client = clnt; // update client IP if not null
|
||||
}
|
||||
else {
|
||||
int timeout = 5000; // 5 seconds timeout
|
||||
DNSlookup = AsyncDNS::query(_hostname.c_str(), DNSlookup); // start async DNS query
|
||||
while (DNSlookup->status() == AsyncDNS::result::Busy && timeout-- > 0) {
|
||||
delay(1);
|
||||
}
|
||||
if (DNSlookup->status() == AsyncDNS::result::Success) {
|
||||
_client = DNSlookup->getIP(); // update client IP
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1105,50 +1147,44 @@ size_t BusHub75Matrix::getPins(uint8_t* pinArray) const {
|
||||
#endif
|
||||
// ***************************************************************************
|
||||
|
||||
//utility to get the approx. memory usage of a given BusConfig
|
||||
size_t BusConfig::memUsage(unsigned nr) const {
|
||||
BusPlaceholder::BusPlaceholder(const BusConfig &bc)
|
||||
: Bus(bc.type, bc.start, bc.autoWhite, bc.count, bc.reversed, bc.refreshReq)
|
||||
, _colorOrder(bc.colorOrder)
|
||||
, _skipAmount(bc.skipAmount)
|
||||
, _driverType(bc.driverType)
|
||||
, _frequency(bc.frequency)
|
||||
, _milliAmpsPerLed(bc.milliAmpsPerLed)
|
||||
, _milliAmpsMax(bc.milliAmpsMax)
|
||||
, _text(bc.text)
|
||||
{
|
||||
memcpy(_pins, bc.pins, sizeof(_pins));
|
||||
}
|
||||
|
||||
size_t BusPlaceholder::getPins(uint8_t* pinArray) const {
|
||||
size_t nPins = Bus::getNumberOfPins(_type);
|
||||
if (pinArray) {
|
||||
for (size_t i = 0; i < nPins; i++) pinArray[i] = _pins[i];
|
||||
}
|
||||
return nPins;
|
||||
}
|
||||
|
||||
//utility to get the approx. memory usage of a given BusConfig inclduding segmentbuffer and global buffer (4 bytes per pixel)
|
||||
size_t BusConfig::memUsage() const {
|
||||
size_t mem = (count + skipAmount) * 8; // 8 bytes per pixel for segment + global buffer
|
||||
if (Bus::isVirtual(type)) {
|
||||
return sizeof(BusNetwork) + (count * Bus::getNumberOfChannels(type));
|
||||
mem += sizeof(BusNetwork) + (count * Bus::getNumberOfChannels(type)); // note: getNumberOfChannels() includes CCT channel if applicable but virtual buses do not use CCT channel buffer
|
||||
} else if (Bus::isDigital(type)) {
|
||||
// if any of digital buses uses I2S, there is additional common I2S DMA buffer not accounted for here
|
||||
return sizeof(BusDigital) + PolyBus::memUsage(count + skipAmount, PolyBus::getI(type, pins, nr));
|
||||
mem += sizeof(BusDigital) + PolyBus::memUsage(count + skipAmount, iType);
|
||||
} else if (Bus::isOnOff(type)) {
|
||||
return sizeof(BusOnOff);
|
||||
mem += sizeof(BusOnOff);
|
||||
} else {
|
||||
return sizeof(BusPwm);
|
||||
mem += sizeof(BusPwm);
|
||||
}
|
||||
return mem;
|
||||
}
|
||||
|
||||
|
||||
size_t BusManager::memUsage() {
|
||||
// when ESP32, S2 & S3 use parallel I2S only the largest bus determines the total memory requirements for back buffers
|
||||
// front buffers are always allocated per bus
|
||||
unsigned size = 0;
|
||||
unsigned maxI2S = 0;
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(ESP8266)
|
||||
unsigned digitalCount = 0;
|
||||
#endif
|
||||
for (const auto &bus : busses) {
|
||||
size += bus->getBusSize();
|
||||
#if !defined(CONFIG_IDF_TARGET_ESP32C3) && !defined(ESP8266)
|
||||
if (bus->isDigital() && !bus->is2Pin()) {
|
||||
digitalCount++;
|
||||
if ((PolyBus::isParallelI2S1Output() && digitalCount <= 8) || (!PolyBus::isParallelI2S1Output() && digitalCount == 1)) {
|
||||
#ifdef NPB_CONF_4STEP_CADENCE
|
||||
constexpr unsigned stepFactor = 4; // 4 step cadence (4 bits per pixel bit)
|
||||
#else
|
||||
constexpr unsigned stepFactor = 3; // 3 step cadence (3 bits per pixel bit)
|
||||
#endif
|
||||
unsigned i2sCommonSize = stepFactor * bus->getLength() * bus->getNumberOfChannels() * (bus->is16bit()+1);
|
||||
if (i2sCommonSize > maxI2S) maxI2S = i2sCommonSize;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
return size + maxI2S;
|
||||
}
|
||||
|
||||
int BusManager::add(const BusConfig &bc) {
|
||||
int BusManager::add(const BusConfig &bc, bool placeholder) {
|
||||
DEBUGBUS_PRINTF_P(PSTR("Bus: Adding bus (p:%d v:%d)\n"), getNumBusses(), getNumVirtualBusses());
|
||||
unsigned digital = 0;
|
||||
unsigned analog = 0;
|
||||
@@ -1158,15 +1194,19 @@ int BusManager::add(const BusConfig &bc) {
|
||||
if (bus->isDigital() && !bus->is2Pin()) digital++;
|
||||
if (bus->is2Pin()) twoPin++;
|
||||
}
|
||||
if (digital > WLED_MAX_DIGITAL_CHANNELS || analog > WLED_MAX_ANALOG_CHANNELS) return -1;
|
||||
if (Bus::isVirtual(bc.type)) {
|
||||
digital += (Bus::isDigital(bc.type) && !Bus::is2Pin(bc.type));
|
||||
analog += (Bus::isPWM(bc.type) ? Bus::numPWMPins(bc.type) : 0);
|
||||
if (digital > WLED_MAX_DIGITAL_CHANNELS || analog > WLED_MAX_ANALOG_CHANNELS) placeholder = true; // TODO: add errorFlag here
|
||||
if (placeholder) {
|
||||
busses.push_back(make_unique<BusPlaceholder>(bc));
|
||||
} else if (Bus::isVirtual(bc.type)) {
|
||||
busses.push_back(make_unique<BusNetwork>(bc));
|
||||
#ifdef WLED_ENABLE_HUB75MATRIX
|
||||
} else if (Bus::isHub75(bc.type)) {
|
||||
busses.push_back(make_unique<BusHub75Matrix>(bc));
|
||||
#endif
|
||||
} else if (Bus::isDigital(bc.type)) {
|
||||
busses.push_back(make_unique<BusDigital>(bc, Bus::is2Pin(bc.type) ? twoPin : digital));
|
||||
busses.push_back(make_unique<BusDigital>(bc));
|
||||
} else if (Bus::isOnOff(bc.type)) {
|
||||
busses.push_back(make_unique<BusOnOff>(bc));
|
||||
} else {
|
||||
@@ -1204,49 +1244,35 @@ String BusManager::getLEDTypesJSONString() {
|
||||
return json;
|
||||
}
|
||||
|
||||
void BusManager::useParallelOutput() {
|
||||
DEBUGBUS_PRINTLN(F("Bus: Enabling parallel I2S."));
|
||||
PolyBus::setParallelI2S1Output();
|
||||
uint8_t BusManager::getI(uint8_t busType, const uint8_t* pins, uint8_t driverPreference) {
|
||||
return PolyBus::getI(busType, pins, driverPreference);
|
||||
}
|
||||
|
||||
bool BusManager::hasParallelOutput() {
|
||||
return PolyBus::isParallelI2S1Output();
|
||||
}
|
||||
|
||||
//do not call this method from system context (network callback)
|
||||
void BusManager::removeAll() {
|
||||
DEBUGBUS_PRINTLN(F("Removing all."));
|
||||
//prevents crashes due to deleting busses while in use.
|
||||
while (!canAllShow()) yield();
|
||||
busses.clear();
|
||||
PolyBus::setParallelI2S1Output(false);
|
||||
#ifndef ESP8266
|
||||
// Reset channel tracking for fresh allocation
|
||||
PolyBus::resetChannelTracking();
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
// #2478
|
||||
// If enabled, RMT idle level is set to HIGH when off
|
||||
// to prevent leakage current when using an N-channel MOSFET to toggle LED power
|
||||
// since I2S outputs are known only during config of buses, lets just assume RMT is used for digital buses
|
||||
// unused RMT channels should have no effect
|
||||
void BusManager::esp32RMTInvertIdle() {
|
||||
bool idle_out;
|
||||
unsigned rmt = 0;
|
||||
unsigned u = 0;
|
||||
for (auto &bus : busses) {
|
||||
if (bus->getLength()==0 || !bus->isDigital() || bus->is2Pin()) continue;
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C3) // 2 RMT, only has 1 I2S but NPB does not support it ATM
|
||||
if (u > 1) return;
|
||||
rmt = u;
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S2) // 4 RMT, only has 1 I2S bus, supported in NPB
|
||||
if (u > 3) return;
|
||||
rmt = u;
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S3) // 4 RMT, has 2 I2S but NPB does not support them ATM
|
||||
if (u > 3) return;
|
||||
rmt = u;
|
||||
#else
|
||||
unsigned numI2S = !PolyBus::isParallelI2S1Output(); // if using parallel I2S, RMT is used 1st
|
||||
if (numI2S > u) continue;
|
||||
if (u > 7 + numI2S) return;
|
||||
rmt = u - numI2S;
|
||||
#endif
|
||||
if (static_cast<BusDigital*>(bus.get())->isI2S()) continue;
|
||||
if (u >= WLED_MAX_RMT_CHANNELS) return;
|
||||
//assumes that bus number to rmt channel mapping stays 1:1
|
||||
rmt_channel_t ch = static_cast<rmt_channel_t>(rmt);
|
||||
rmt_idle_level_t lvl;
|
||||
@@ -1266,7 +1292,7 @@ void BusManager::on() {
|
||||
if (PinManager::getPinOwner(LED_BUILTIN) == PinOwner::BusDigital) {
|
||||
for (auto &bus : busses) {
|
||||
uint8_t pins[2] = {255,255};
|
||||
if (bus->isDigital() && bus->getPins(pins)) {
|
||||
if (bus->isDigital() && bus->getPins(pins) && bus->isOk()) {
|
||||
if (pins[0] == LED_BUILTIN || pins[1] == LED_BUILTIN) {
|
||||
BusDigital &b = static_cast<BusDigital&>(*bus);
|
||||
b.begin();
|
||||
@@ -1276,12 +1302,17 @@ void BusManager::on() {
|
||||
}
|
||||
}
|
||||
#else
|
||||
static uint32_t nextResolve = 0; // initial resolve is done on bus creation
|
||||
bool resolveNow = (millis() - nextResolve >= 600000); // wait at least 10 minutes between hostname resolutions (blocking call)
|
||||
for (auto &bus : busses) if (bus->isVirtual()) {
|
||||
// virtual/network bus should check for IP change if hostname is specified
|
||||
// otherwise there are no endpoints to force DNS resolution
|
||||
BusNetwork &b = static_cast<BusNetwork&>(*bus);
|
||||
b.resolveHostname();
|
||||
if (resolveNow)
|
||||
b.resolveHostname();
|
||||
}
|
||||
if (resolveNow)
|
||||
nextResolve = millis();
|
||||
#endif
|
||||
#ifdef ESP32_DATA_IDLE_HIGH
|
||||
esp32RMTInvertIdle();
|
||||
@@ -1361,7 +1392,7 @@ void BusManager::initializeABL() {
|
||||
_useABL = true; // at least one bus has ABL set
|
||||
uint32_t ESPshare = MA_FOR_ESP / numABLbuses; // share of ESP current per ABL bus
|
||||
for (auto &bus : busses) {
|
||||
if (bus->isDigital()) {
|
||||
if (bus->isDigital() && bus->isOk()) {
|
||||
BusDigital &busd = static_cast<BusDigital&>(*bus);
|
||||
uint32_t busLength = busd.getLength();
|
||||
uint32_t busDemand = busLength * busd.getLEDCurrent();
|
||||
@@ -1421,12 +1452,18 @@ void BusManager::applyABL() {
|
||||
|
||||
ColorOrderMap& BusManager::getColorOrderMap() { return _colorOrderMap; }
|
||||
|
||||
|
||||
#ifndef ESP8266
|
||||
// PolyBus channel tracking for dynamic allocation
|
||||
bool PolyBus::_useParallelI2S = false;
|
||||
|
||||
uint8_t PolyBus::_rmtChannelsAssigned = 0; // number of RMT channels assigned durig getI() check
|
||||
uint8_t PolyBus::_rmtChannel = 0; // number of RMT channels actually used during bus creation in create()
|
||||
uint8_t PolyBus::_i2sChannelsAssigned = 0; // number of I2S channels assigned durig getI() check
|
||||
uint8_t PolyBus::_parallelBusItype = 0; // type I_NONE
|
||||
uint8_t PolyBus::_2PchannelsAssigned = 0;
|
||||
#endif
|
||||
// Bus static member definition
|
||||
int16_t Bus::_cct = -1;
|
||||
uint8_t Bus::_cctBlend = 0; // 0 - 127
|
||||
int16_t Bus::_cct = -1; // -1 means use approximateKelvinFromRGB(), 0-255 is standard, >1900 use colorBalanceFromKelvin()
|
||||
int8_t Bus::_cctBlend = 0; // -128 to +127
|
||||
uint8_t Bus::_gAWM = 255;
|
||||
|
||||
uint16_t BusDigital::_milliAmpsTotal = 0;
|
||||
|
||||
+66
-19
@@ -6,7 +6,7 @@
|
||||
|
||||
#include <ESP32-HUB75-MatrixPanel-I2S-DMA.h>
|
||||
#include <ESP32-VirtualMatrixPanel-I2S-DMA.h>
|
||||
#include <FastLED.h>
|
||||
#include "src/dependencies/fastled_slim/fastled_slim.h"
|
||||
|
||||
#endif
|
||||
/*
|
||||
@@ -17,6 +17,9 @@
|
||||
#include "pin_manager.h"
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
#include "asyncDNS.h"
|
||||
#endif
|
||||
|
||||
#if __cplusplus >= 201402L
|
||||
using std::make_unique;
|
||||
@@ -133,14 +136,15 @@ class Bus {
|
||||
virtual void setColorOrder(uint8_t co) {}
|
||||
virtual uint32_t getPixelColor(unsigned pix) const { return 0; }
|
||||
virtual size_t getPins(uint8_t* pinArray = nullptr) const { return 0; }
|
||||
virtual uint16_t getLength() const { return isOk() ? _len : 0; }
|
||||
virtual uint16_t getLength() const { return _len; }
|
||||
virtual uint8_t getColorOrder() const { return COL_ORDER_RGB; }
|
||||
virtual unsigned skippedLeds() const { return 0; }
|
||||
virtual uint16_t getFrequency() const { return 0U; }
|
||||
virtual uint16_t getLEDCurrent() const { return 0; }
|
||||
virtual uint16_t getUsedCurrent() const { return 0; }
|
||||
virtual uint16_t getMaxCurrent() const { return 0; }
|
||||
virtual size_t getBusSize() const { return sizeof(Bus); }
|
||||
virtual uint8_t getDriverType() const { return 0; } // Default to RMT (0) for non-digital buses
|
||||
virtual size_t getBusSize() const { return sizeof(Bus); } // currently unused
|
||||
virtual const String getCustomText() const { return String(); }
|
||||
|
||||
inline bool hasRGB() const { return _hasRgb; }
|
||||
@@ -152,6 +156,7 @@ class Bus {
|
||||
inline bool isPWM() const { return isPWM(_type); }
|
||||
inline bool isVirtual() const { return isVirtual(_type); }
|
||||
inline bool is16bit() const { return is16bit(_type); }
|
||||
virtual bool isPlaceholder() const { return false; }
|
||||
inline bool mustRefresh() const { return mustRefresh(_type); }
|
||||
inline void setReversed(bool reversed) { _reversed = reversed; }
|
||||
inline void setStart(uint16_t start) { _start = start; }
|
||||
@@ -199,9 +204,9 @@ class Bus {
|
||||
static inline void setGlobalAWMode(uint8_t m) { if (m < 5) _gAWM = m; else _gAWM = AW_GLOBAL_DISABLED; }
|
||||
static inline uint8_t getGlobalAWMode() { return _gAWM; }
|
||||
static inline void setCCT(int16_t cct) { _cct = cct; }
|
||||
static inline uint8_t getCCTBlend() { return (_cctBlend * 100 + 64) / 127; } // returns 0-100, 100% = 127. +64 for rounding
|
||||
static inline void setCCTBlend(uint8_t b) { // input is 0-100
|
||||
_cctBlend = (std::min((int)b,100) * 127 + 50) / 100; // +50 for rounding, b=100% -> 127
|
||||
static inline int8_t getCCTBlend() { return (_cctBlend * 100 + (_cctBlend >= 0 ? 64 : -64)) / 127; } // returns -100 to +100, +/-100% = +/-127. +/-64 for rounding
|
||||
static inline void setCCTBlend(int8_t b) { // input is -100 to +100
|
||||
_cctBlend = (std::max(-100, std::min(100, (int)b)) * 127 + (b >= 0 ? 50 : -50)) / 100; // +/-50 for rounding, b=+/-100% -> +/-127
|
||||
//compile-time limiter for hardware that can't power both white channels at max
|
||||
#ifdef WLED_MAX_CCT_BLEND
|
||||
if (_cctBlend > WLED_MAX_CCT_BLEND) _cctBlend = WLED_MAX_CCT_BLEND;
|
||||
@@ -230,19 +235,20 @@ class Bus {
|
||||
// [0,255] is the exact CCT value where 0 means warm and 255 cold
|
||||
// [1900,10060] only for color correction expressed in K (colorBalanceFromKelvin())
|
||||
static int16_t _cct;
|
||||
// _cctBlend determines WW/CW blending:
|
||||
// _cctBlend determines WW/CW blending, see calculateCCT()
|
||||
// < 0 - linear blending in center, single white at both ends, single white zone extends with decreased value (-127 min)
|
||||
// 0 - linear (CCT 127 => 50% warm, 50% cold)
|
||||
// 63 - semi additive/nonlinear (CCT 127 => 66% warm, 66% cold)
|
||||
// 127 - additive CCT blending (CCT 127 => 100% warm, 100% cold)
|
||||
static uint8_t _cctBlend;
|
||||
static int8_t _cctBlend;
|
||||
|
||||
uint32_t autoWhiteCalc(uint32_t c) const;
|
||||
uint32_t autoWhiteCalc(uint32_t c, uint8_t &ww, uint8_t &cw) const;
|
||||
};
|
||||
|
||||
|
||||
class BusDigital : public Bus {
|
||||
public:
|
||||
BusDigital(const BusConfig &bc, uint8_t nr);
|
||||
BusDigital(const BusConfig &bc);
|
||||
~BusDigital() { cleanup(); }
|
||||
|
||||
void show() override;
|
||||
@@ -258,10 +264,12 @@ class BusDigital : public Bus {
|
||||
uint16_t getLEDCurrent() const override { return _milliAmpsPerLed; }
|
||||
uint16_t getUsedCurrent() const override { return _milliAmpsTotal; }
|
||||
uint16_t getMaxCurrent() const override { return _milliAmpsMax; }
|
||||
uint8_t getDriverType() const override { return _driverType; }
|
||||
void setCurrentLimit(uint16_t milliAmps) { _milliAmpsLimit = milliAmps; }
|
||||
void estimateCurrent(); // estimate used current from summed colors
|
||||
void applyBriLimit(uint8_t newBri);
|
||||
size_t getBusSize() const override;
|
||||
bool isI2S(); // true if this bus uses I2S driver
|
||||
void begin() override;
|
||||
void cleanup();
|
||||
|
||||
@@ -272,6 +280,7 @@ class BusDigital : public Bus {
|
||||
uint8_t _colorOrder;
|
||||
uint8_t _pins[2];
|
||||
uint8_t _iType;
|
||||
uint8_t _driverType; // 0=RMT (default), 1=I2S
|
||||
uint16_t _frequencykHz;
|
||||
uint16_t _milliAmpsMax;
|
||||
uint8_t _milliAmpsPerLed;
|
||||
@@ -372,6 +381,41 @@ class BusNetwork : public Bus {
|
||||
#endif
|
||||
};
|
||||
|
||||
// Placeholder for buses that we can't construct due to resource limitations
|
||||
// This preserves the configuration so it can be read back to the settings pages
|
||||
// Function calls "mimic" the replaced bus, isPlaceholder() can be used to identify a placeholder
|
||||
class BusPlaceholder : public Bus {
|
||||
public:
|
||||
BusPlaceholder(const BusConfig &bc);
|
||||
|
||||
// Actual calls are stubbed out
|
||||
void setPixelColor(unsigned pix, uint32_t c) override {};
|
||||
void show() override {};
|
||||
|
||||
// Accessors
|
||||
uint8_t getColorOrder() const override { return _colorOrder; }
|
||||
size_t getPins(uint8_t* pinArray) const override;
|
||||
unsigned skippedLeds() const override { return _skipAmount; }
|
||||
uint16_t getFrequency() const override { return _frequency; }
|
||||
uint16_t getLEDCurrent() const override { return _milliAmpsPerLed; }
|
||||
uint16_t getMaxCurrent() const override { return _milliAmpsMax; }
|
||||
uint8_t getDriverType() const override { return _driverType; }
|
||||
const String getCustomText() const override { return _text; }
|
||||
bool isPlaceholder() const override { return true; }
|
||||
|
||||
size_t getBusSize() const override { return sizeof(BusPlaceholder); }
|
||||
|
||||
private:
|
||||
uint8_t _colorOrder;
|
||||
uint8_t _skipAmount;
|
||||
uint8_t _pins[OUTPUT_MAX_PINS];
|
||||
uint8_t _driverType;
|
||||
uint16_t _frequency;
|
||||
uint8_t _milliAmpsPerLed;
|
||||
uint16_t _milliAmpsMax;
|
||||
String _text;
|
||||
};
|
||||
|
||||
#ifdef WLED_ENABLE_HUB75MATRIX
|
||||
class BusHub75Matrix : public Bus {
|
||||
public:
|
||||
@@ -421,9 +465,11 @@ struct BusConfig {
|
||||
uint16_t frequency;
|
||||
uint8_t milliAmpsPerLed;
|
||||
uint16_t milliAmpsMax;
|
||||
uint8_t driverType; // 0=RMT (default), 1=I2S
|
||||
uint8_t iType; // internal bus type (I_*) determined during memory estimation, used for bus creation
|
||||
String text;
|
||||
|
||||
BusConfig(uint8_t busType, uint8_t* ppins, uint16_t pstart, uint16_t len = 1, uint8_t pcolorOrder = COL_ORDER_GRB, bool rev = false, uint8_t skip = 0, byte aw=RGBW_MODE_MANUAL_ONLY, uint16_t clock_kHz=0U, uint8_t maPerLed=LED_MILLIAMPS_DEFAULT, uint16_t maMax=ABL_MILLIAMPS_DEFAULT, String sometext = "")
|
||||
BusConfig(uint8_t busType, uint8_t* ppins, uint16_t pstart, uint16_t len = 1, uint8_t pcolorOrder = COL_ORDER_GRB, bool rev = false, uint8_t skip = 0, byte aw=RGBW_MODE_MANUAL_ONLY, uint16_t clock_kHz=0U, uint8_t maPerLed=LED_MILLIAMPS_DEFAULT, uint16_t maMax=ABL_MILLIAMPS_DEFAULT, uint8_t driver=0, String sometext = "")
|
||||
: count(std::max(len,(uint16_t)1))
|
||||
, start(pstart)
|
||||
, colorOrder(pcolorOrder)
|
||||
@@ -433,13 +479,15 @@ struct BusConfig {
|
||||
, frequency(clock_kHz)
|
||||
, milliAmpsPerLed(maPerLed)
|
||||
, milliAmpsMax(maMax)
|
||||
, driverType(driver)
|
||||
, iType(0) // default to I_NONE
|
||||
, text(sometext)
|
||||
{
|
||||
refreshReq = (bool) GET_BIT(busType,7);
|
||||
type = busType & 0x7F; // bit 7 may be/is hacked to include refresh info (1=refresh in off state, 0=no refresh)
|
||||
size_t nPins = Bus::getNumberOfPins(type);
|
||||
for (size_t i = 0; i < nPins; i++) pins[i] = ppins[i];
|
||||
DEBUGBUS_PRINTF_P(PSTR("Bus: Config (%d-%d, type:%d, CO:%d, rev:%d, skip:%d, AW:%d kHz:%d, mA:%d/%d)\n"),
|
||||
DEBUGBUS_PRINTF_P(PSTR("Bus: Config (%d-%d, type:%d, CO:%d, rev:%d, skip:%d, AW:%d kHz:%d, mA:%d/%d, driver:%s)\n"),
|
||||
(int)start, (int)(start+len),
|
||||
(int)type,
|
||||
(int)colorOrder,
|
||||
@@ -447,14 +495,15 @@ struct BusConfig {
|
||||
(int)skipAmount,
|
||||
(int)autoWhite,
|
||||
(int)frequency,
|
||||
(int)milliAmpsPerLed, (int)milliAmpsMax
|
||||
(int)milliAmpsPerLed, (int)milliAmpsMax,
|
||||
driverType == 0 ? "RMT" : "I2S"
|
||||
);
|
||||
}
|
||||
|
||||
//validates start and length and extends total if needed
|
||||
bool adjustBounds(uint16_t& total) {
|
||||
if (!count) count = 1;
|
||||
if (count > MAX_LEDS_PER_BUS) count = MAX_LEDS_PER_BUS;
|
||||
if (!Bus::isVirtual(type) && count > MAX_LEDS_PER_BUS) count = MAX_LEDS_PER_BUS;
|
||||
if (start >= MAX_LEDS) return false;
|
||||
//limit length of strip if it would exceed total permissible LEDs
|
||||
if (start + count > MAX_LEDS) count = MAX_LEDS - start;
|
||||
@@ -463,7 +512,7 @@ struct BusConfig {
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t memUsage(unsigned nr = 0) const;
|
||||
size_t memUsage() const;
|
||||
};
|
||||
|
||||
|
||||
@@ -494,7 +543,6 @@ namespace BusManager {
|
||||
return j;
|
||||
}
|
||||
|
||||
size_t memUsage();
|
||||
inline uint16_t currentMilliamps() { return _gMilliAmpsUsed + MA_FOR_ESP; }
|
||||
//inline uint16_t ablMilliampsMax() { unsigned sum = 0; for (auto &bus : busses) sum += bus->getMaxCurrent(); return sum; }
|
||||
inline uint16_t ablMilliampsMax() { return _gMilliAmpsMax; } // used for compatibility reasons (and enabling virtual global ABL)
|
||||
@@ -502,12 +550,11 @@ namespace BusManager {
|
||||
void initializeABL(); // setup automatic brightness limiter parameters, call once after buses are initialized
|
||||
void applyABL(); // apply automatic brightness limiter, global or per bus
|
||||
|
||||
void useParallelOutput(); // workaround for inaccessible PolyBus
|
||||
bool hasParallelOutput(); // workaround for inaccessible PolyBus
|
||||
uint8_t getI(uint8_t busType, const uint8_t* pins, uint8_t driverPreference); // workaround for access to PolyBus function from FX_fcn.cpp
|
||||
|
||||
//do not call this method from system context (network callback)
|
||||
void removeAll();
|
||||
int add(const BusConfig &bc);
|
||||
int add(const BusConfig &bc, bool placeholder);
|
||||
|
||||
void on();
|
||||
void off();
|
||||
|
||||
+116
-122
@@ -339,11 +339,17 @@
|
||||
//handles pointer type conversion for all possible bus types
|
||||
class PolyBus {
|
||||
private:
|
||||
static bool _useParallelI2S;
|
||||
|
||||
#ifndef ESP8266
|
||||
static bool _useParallelI2S; // use parallel I2S/LCD (8 channels)
|
||||
static uint8_t _rmtChannelsAssigned; // RMT channel tracking for dynamic allocation
|
||||
static uint8_t _rmtChannel; // physical RMT channel to use during bus creation
|
||||
static uint8_t _i2sChannelsAssigned; // I2S channel tracking for dynamic allocation
|
||||
static uint8_t _parallelBusItype; // parallel output does not allow mixed LED types, track I_Type
|
||||
static uint8_t _2PchannelsAssigned; // 2-Pin (SPI) channel assigned: first one gets the hardware SPI, others use bit-banged SPI
|
||||
// note on 2-Pin Types: all supported types except WS2801 use start/stop or latch frames, speed is not critical. WS2801 uses a 500us timeout and is prone to flickering if bit-banged too slow.
|
||||
// TODO: according to #4863 using more than one bit-banged output can cause glitches even in APA102. This needs investigation as from a hardware perspective all but WS2801 should be immune to timing issues.
|
||||
#endif
|
||||
public:
|
||||
static inline void setParallelI2S1Output(bool b = true) { _useParallelI2S = b; }
|
||||
static inline bool isParallelI2S1Output(void) { return _useParallelI2S; }
|
||||
|
||||
// initialize SPI bus speed for DotStar methods
|
||||
template <class T>
|
||||
@@ -476,21 +482,7 @@ class PolyBus {
|
||||
}
|
||||
}
|
||||
|
||||
static void* create(uint8_t busType, uint8_t* pins, uint16_t len, uint8_t channel) {
|
||||
// NOTE: "channel" is only used on ESP32 (and its variants) for RMT channel allocation
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
if (_useParallelI2S && (channel >= 8)) {
|
||||
// Parallel I2S channels are to be used first, so subtract 8 to get the RMT channel number
|
||||
channel -= 8;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !(defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32C3))
|
||||
// since 0.15.0-b3 I2S1 is favoured for classic ESP32 and moved to position 0 (channel 0) so we need to subtract 1 for correct RMT allocation
|
||||
if (!_useParallelI2S && channel > 0) channel--; // accommodate I2S1 which is used as 1st bus on classic ESP32
|
||||
#endif
|
||||
|
||||
static void* create(uint8_t busType, uint8_t* pins, uint16_t len) {
|
||||
void* busPtr = nullptr;
|
||||
switch (busType) {
|
||||
case I_NONE: break;
|
||||
@@ -546,18 +538,18 @@ class PolyBus {
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses
|
||||
case I_32_RN_NEO_3: busPtr = new B_32_RN_NEO_3(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_NEO_4: busPtr = new B_32_RN_NEO_4(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_400_3: busPtr = new B_32_RN_400_3(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_TM1_4: busPtr = new B_32_RN_TM1_4(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_TM2_3: busPtr = new B_32_RN_TM2_3(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_UCS_3: busPtr = new B_32_RN_UCS_3(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_UCS_4: busPtr = new B_32_RN_UCS_4(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_APA106_3: busPtr = new B_32_RN_APA106_3(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_FW6_5: busPtr = new B_32_RN_FW6_5(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_2805_5: busPtr = new B_32_RN_2805_5(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_TM1914_3: busPtr = new B_32_RN_TM1914_3(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_SM16825_5: busPtr = new B_32_RN_SM16825_5(len, pins[0], (NeoBusChannel)channel); break;
|
||||
case I_32_RN_NEO_3: busPtr = new B_32_RN_NEO_3(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_NEO_4: busPtr = new B_32_RN_NEO_4(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_400_3: busPtr = new B_32_RN_400_3(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_TM1_4: busPtr = new B_32_RN_TM1_4(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_TM2_3: busPtr = new B_32_RN_TM2_3(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_UCS_3: busPtr = new B_32_RN_UCS_3(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_UCS_4: busPtr = new B_32_RN_UCS_4(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_APA106_3: busPtr = new B_32_RN_APA106_3(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_FW6_5: busPtr = new B_32_RN_FW6_5(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_2805_5: busPtr = new B_32_RN_2805_5(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_TM1914_3: busPtr = new B_32_RN_TM1914_3(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
case I_32_RN_SM16825_5: busPtr = new B_32_RN_SM16825_5(len, pins[0], (NeoBusChannel)_rmtChannel++); break;
|
||||
// I2S1 bus or paralell buses
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32C3
|
||||
case I_32_I2_NEO_3: if (_useParallelI2S) busPtr = new B_32_IP_NEO_3(len, pins[0]); else busPtr = new B_32_I2_NEO_3(len, pins[0]); break;
|
||||
@@ -1118,6 +1110,9 @@ class PolyBus {
|
||||
|
||||
static unsigned getDataSize(void* busPtr, uint8_t busType) {
|
||||
unsigned size = 0;
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
size = 100; // ~100bytes for NPB internal structures (measured for both I2S and RMT, much smaller and more variable on ESP8266)
|
||||
#endif
|
||||
switch (busType) {
|
||||
case I_NONE: break;
|
||||
#ifdef ESP8266
|
||||
@@ -1172,32 +1167,32 @@ class PolyBus {
|
||||
#endif
|
||||
#ifdef ARDUINO_ARCH_ESP32
|
||||
// RMT buses (front + back + small system managed RMT)
|
||||
case I_32_RN_NEO_3: size = (static_cast<B_32_RN_NEO_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_NEO_4: size = (static_cast<B_32_RN_NEO_4*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_400_3: size = (static_cast<B_32_RN_400_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_TM1_4: size = (static_cast<B_32_RN_TM1_4*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_TM2_3: size = (static_cast<B_32_RN_TM2_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_UCS_3: size = (static_cast<B_32_RN_UCS_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_UCS_4: size = (static_cast<B_32_RN_UCS_4*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_APA106_3: size = (static_cast<B_32_RN_APA106_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_FW6_5: size = (static_cast<B_32_RN_FW6_5*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_2805_5: size = (static_cast<B_32_RN_2805_5*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_TM1914_3: size = (static_cast<B_32_RN_TM1914_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_SM16825_5: size = (static_cast<B_32_RN_SM16825_5*>(busPtr))->PixelsSize()*2; break;
|
||||
// I2S1 bus or paralell buses (front + DMA; DMA = front * cadence, aligned to 4 bytes)
|
||||
case I_32_RN_NEO_3: size += (static_cast<B_32_RN_NEO_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_NEO_4: size += (static_cast<B_32_RN_NEO_4*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_400_3: size += (static_cast<B_32_RN_400_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_TM1_4: size += (static_cast<B_32_RN_TM1_4*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_TM2_3: size += (static_cast<B_32_RN_TM2_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_UCS_3: size += (static_cast<B_32_RN_UCS_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_UCS_4: size += (static_cast<B_32_RN_UCS_4*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_APA106_3: size += (static_cast<B_32_RN_APA106_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_FW6_5: size += (static_cast<B_32_RN_FW6_5*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_2805_5: size += (static_cast<B_32_RN_2805_5*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_TM1914_3: size += (static_cast<B_32_RN_TM1914_3*>(busPtr))->PixelsSize()*2; break;
|
||||
case I_32_RN_SM16825_5: size += (static_cast<B_32_RN_SM16825_5*>(busPtr))->PixelsSize()*2; break;
|
||||
// I2S1 bus or paralell buses (front + DMA; DMA = front * cadence, aligned to 4 bytes) not: for parallel I2S only the largest bus counts for DMA memory, this is not done correctly here, also assumes 3-step cadence
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32C3
|
||||
case I_32_I2_NEO_3: size = (_useParallelI2S) ? (static_cast<B_32_IP_NEO_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_NEO_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_NEO_4: size = (_useParallelI2S) ? (static_cast<B_32_IP_NEO_4*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_NEO_4*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_400_3: size = (_useParallelI2S) ? (static_cast<B_32_IP_400_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_400_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_TM1_4: size = (_useParallelI2S) ? (static_cast<B_32_IP_TM1_4*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_TM1_4*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_TM2_3: size = (_useParallelI2S) ? (static_cast<B_32_IP_TM2_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_TM2_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_UCS_3: size = (_useParallelI2S) ? (static_cast<B_32_IP_UCS_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_UCS_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_UCS_4: size = (_useParallelI2S) ? (static_cast<B_32_IP_UCS_4*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_UCS_4*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_APA106_3: size = (_useParallelI2S) ? (static_cast<B_32_IP_APA106_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_APA106_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_FW6_5: size = (_useParallelI2S) ? (static_cast<B_32_IP_FW6_5*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_FW6_5*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_2805_5: size = (_useParallelI2S) ? (static_cast<B_32_IP_2805_5*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_2805_5*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_TM1914_3: size = (_useParallelI2S) ? (static_cast<B_32_IP_TM1914_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_TM1914_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_SM16825_5: size = (_useParallelI2S) ? (static_cast<B_32_IP_SM16825_5*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_SM16825_5*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_NEO_3: size += (_useParallelI2S) ? (static_cast<B_32_IP_NEO_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_NEO_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_NEO_4: size += (_useParallelI2S) ? (static_cast<B_32_IP_NEO_4*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_NEO_4*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_400_3: size += (_useParallelI2S) ? (static_cast<B_32_IP_400_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_400_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_TM1_4: size += (_useParallelI2S) ? (static_cast<B_32_IP_TM1_4*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_TM1_4*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_TM2_3: size += (_useParallelI2S) ? (static_cast<B_32_IP_TM2_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_TM2_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_UCS_3: size += (_useParallelI2S) ? (static_cast<B_32_IP_UCS_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_UCS_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_UCS_4: size += (_useParallelI2S) ? (static_cast<B_32_IP_UCS_4*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_UCS_4*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_APA106_3: size += (_useParallelI2S) ? (static_cast<B_32_IP_APA106_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_APA106_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_FW6_5: size += (_useParallelI2S) ? (static_cast<B_32_IP_FW6_5*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_FW6_5*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_2805_5: size += (_useParallelI2S) ? (static_cast<B_32_IP_2805_5*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_2805_5*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_TM1914_3: size += (_useParallelI2S) ? (static_cast<B_32_IP_TM1914_3*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_TM1914_3*>(busPtr))->PixelsSize()*4; break;
|
||||
case I_32_I2_SM16825_5: size += (_useParallelI2S) ? (static_cast<B_32_IP_SM16825_5*>(busPtr))->PixelsSize()*4 : (static_cast<B_32_I2_SM16825_5*>(busPtr))->PixelsSize()*4; break;
|
||||
#endif
|
||||
#endif
|
||||
case I_HS_DOT_3: size = (static_cast<B_HS_DOT_3*>(busPtr))->PixelsSize()*2; break;
|
||||
@@ -1255,6 +1250,7 @@ class PolyBus {
|
||||
case I_8266_DM_2805_5 : size = (size + 2*count)*5; break;
|
||||
case I_8266_DM_SM16825_5: size = (size + 2*count)*2*5; break;
|
||||
#else
|
||||
// note: RMT and I2S buses use ~100 bytes of internal NPB memory each, not included here for simplicity
|
||||
// RMT buses (1x front and 1x back buffer, does not include small RMT buffer)
|
||||
case I_32_RN_NEO_4 : // fallthrough
|
||||
case I_32_RN_TM1_4 : size = (size + count)*2; break; // 4 channels
|
||||
@@ -1263,7 +1259,7 @@ class PolyBus {
|
||||
case I_32_RN_FW6_5 : // fallthrough
|
||||
case I_32_RN_2805_5 : size = (size + 2*count)*2; break; // 5 channels
|
||||
case I_32_RN_SM16825_5: size = (size + 2*count)*2*2; break; // 16bit, 5 channels
|
||||
// I2S1 bus or paralell I2S1 buses (1x front, does not include DMA buffer which is front*cadence, a bit(?) more for LCD)
|
||||
// I2S bus or paralell I2S buses (1x front, does not include DMA buffer which is front*cadence, a bit(?) more for LCD)
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32C3
|
||||
case I_32_I2_NEO_3 : // fallthrough
|
||||
case I_32_I2_400_3 : // fallthrough
|
||||
@@ -1282,30 +1278,37 @@ class PolyBus {
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
//gives back the internal type index (I_XX_XXX_X above) for the input
|
||||
static uint8_t getI(uint8_t busType, const uint8_t* pins, uint8_t num = 0) {
|
||||
#ifndef ESP8266
|
||||
// Reset channel tracking (call before adding buses)
|
||||
static void resetChannelTracking() {
|
||||
_useParallelI2S = false;
|
||||
_rmtChannelsAssigned = 0;
|
||||
_rmtChannel = 0;
|
||||
_i2sChannelsAssigned = 0;
|
||||
_parallelBusItype = I_NONE;
|
||||
_2PchannelsAssigned = 0;
|
||||
}
|
||||
#endif
|
||||
// reserves and gives back the internal type index (I_XX_XXX_X above) for the input based on bus type and pins
|
||||
static uint8_t getI(uint8_t busType, const uint8_t* pins, uint8_t driverPreference) {
|
||||
if (!Bus::isDigital(busType)) return I_NONE;
|
||||
uint8_t t = I_NONE;
|
||||
if (Bus::is2Pin(busType)) { //SPI LED chips
|
||||
bool isHSPI = false;
|
||||
#ifdef ESP8266
|
||||
if (pins[0] == P_8266_HS_MOSI && pins[1] == P_8266_HS_CLK) isHSPI = true;
|
||||
#else
|
||||
// temporary hack to limit use of hardware SPI to a single SPI peripheral (HSPI): only allow ESP32 hardware serial on segment 0
|
||||
// SPI global variable is normally linked to VSPI on ESP32 (or FSPI C3, S3)
|
||||
if (!num) isHSPI = true;
|
||||
if (_2PchannelsAssigned == 0) isHSPI = true; // first 2-pin channel uses hardware SPI
|
||||
_2PchannelsAssigned++;
|
||||
#endif
|
||||
uint8_t t = I_NONE;
|
||||
switch (busType) {
|
||||
case TYPE_APA102: t = I_SS_DOT_3; break;
|
||||
case TYPE_LPD8806: t = I_SS_LPD_3; break;
|
||||
case TYPE_LPD6803: t = I_SS_LPO_3; break;
|
||||
case TYPE_WS2801: t = I_SS_WS1_3; break;
|
||||
case TYPE_P9813: t = I_SS_P98_3; break;
|
||||
default: t=I_NONE;
|
||||
}
|
||||
if (t > I_NONE && isHSPI) t--; //hardware SPI has one smaller ID than software
|
||||
return t;
|
||||
} else {
|
||||
#ifdef ESP8266
|
||||
uint8_t offset = pins[0] -1; //for driver: 0 = uart0, 1 = uart1, 2 = dma, 3 = bitbang
|
||||
@@ -1315,96 +1318,87 @@ class PolyBus {
|
||||
case TYPE_WS2812_2CH_X3:
|
||||
case TYPE_WS2812_RGB:
|
||||
case TYPE_WS2812_WWA:
|
||||
return I_8266_U0_NEO_3 + offset;
|
||||
t = I_8266_U0_NEO_3 + offset; break;
|
||||
case TYPE_SK6812_RGBW:
|
||||
return I_8266_U0_NEO_4 + offset;
|
||||
t = I_8266_U0_NEO_4 + offset; break;
|
||||
case TYPE_WS2811_400KHZ:
|
||||
return I_8266_U0_400_3 + offset;
|
||||
t = I_8266_U0_400_3 + offset; break;
|
||||
case TYPE_TM1814:
|
||||
return I_8266_U0_TM1_4 + offset;
|
||||
t = I_8266_U0_TM1_4 + offset; break;
|
||||
case TYPE_TM1829:
|
||||
return I_8266_U0_TM2_3 + offset;
|
||||
t = I_8266_U0_TM2_3 + offset; break;
|
||||
case TYPE_UCS8903:
|
||||
return I_8266_U0_UCS_3 + offset;
|
||||
t = I_8266_U0_UCS_3 + offset; break;
|
||||
case TYPE_UCS8904:
|
||||
return I_8266_U0_UCS_4 + offset;
|
||||
t = I_8266_U0_UCS_4 + offset; break;
|
||||
case TYPE_APA106:
|
||||
return I_8266_U0_APA106_3 + offset;
|
||||
t = I_8266_U0_APA106_3 + offset; break;
|
||||
case TYPE_FW1906:
|
||||
return I_8266_U0_FW6_5 + offset;
|
||||
t = I_8266_U0_FW6_5 + offset; break;
|
||||
case TYPE_WS2805:
|
||||
return I_8266_U0_2805_5 + offset;
|
||||
t = I_8266_U0_2805_5 + offset; break;
|
||||
case TYPE_TM1914:
|
||||
return I_8266_U0_TM1914_3 + offset;
|
||||
t = I_8266_U0_TM1914_3 + offset; break;
|
||||
case TYPE_SM16825:
|
||||
return I_8266_U0_SM16825_5 + offset;
|
||||
t = I_8266_U0_SM16825_5 + offset; break;
|
||||
}
|
||||
#else //ESP32
|
||||
uint8_t offset = 0; // 0 = RMT (num 1-8), 1 = I2S1 [I2S0 is used by Audioreactive]
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32S2)
|
||||
// ESP32-S2 only has 4 RMT channels
|
||||
if (_useParallelI2S) {
|
||||
if (num > 11) return I_NONE;
|
||||
if (num < 8) offset = 1; // use x8 parallel I2S0 channels followed by RMT
|
||||
// Note: conflicts with AudioReactive if enabled
|
||||
// dynamic channel allocation based on driver preference
|
||||
// determine which driver to use based on preference and availability. First I2S bus locks the I2S type, all subsequent I2S buses are assigned the same type (hardware restriction)
|
||||
uint8_t offset = 0; // 0 = RMT, 1 = I2S/LCD
|
||||
if (driverPreference == 0 && _rmtChannelsAssigned < WLED_MAX_RMT_CHANNELS) {
|
||||
_rmtChannelsAssigned++;
|
||||
} else if (_i2sChannelsAssigned < WLED_MAX_I2S_CHANNELS) {
|
||||
offset = 1; // I2S requested or RMT full
|
||||
_i2sChannelsAssigned++;
|
||||
} else {
|
||||
if (num > 4) return I_NONE;
|
||||
if (num > 3) offset = 1; // only one I2S0 (use last to allow Audioreactive)
|
||||
return I_NONE; // No channels available
|
||||
}
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
// On ESP32-C3 only the first 2 RMT channels are usable for transmitting
|
||||
if (num > 1) return I_NONE;
|
||||
//if (num > 1) offset = 1; // I2S not supported yet (only 1 I2S)
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
// On ESP32-S3 only the first 4 RMT channels are usable for transmitting
|
||||
if (_useParallelI2S) {
|
||||
if (num > 11) return I_NONE;
|
||||
if (num < 8) offset = 1; // use x8 parallel I2S LCD channels, followed by RMT
|
||||
} else {
|
||||
if (num > 3) return I_NONE; // do not use single I2S (as it is not supported)
|
||||
}
|
||||
#else
|
||||
// standard ESP32 has 8 RMT and x1/x8 I2S1 channels
|
||||
if (_useParallelI2S) {
|
||||
if (num > 15) return I_NONE;
|
||||
if (num < 8) offset = 1; // 8 I2S followed by 8 RMT
|
||||
} else {
|
||||
if (num > 9) return I_NONE;
|
||||
if (num == 0) offset = 1; // prefer I2S1 for 1st bus (less flickering but more RAM needed)
|
||||
}
|
||||
#endif
|
||||
|
||||
// Now determine actual bus type with the chosen offset
|
||||
switch (busType) {
|
||||
case TYPE_WS2812_1CH_X3:
|
||||
case TYPE_WS2812_2CH_X3:
|
||||
case TYPE_WS2812_RGB:
|
||||
case TYPE_WS2812_WWA:
|
||||
return I_32_RN_NEO_3 + offset;
|
||||
t = I_32_RN_NEO_3 + offset; break;
|
||||
case TYPE_SK6812_RGBW:
|
||||
return I_32_RN_NEO_4 + offset;
|
||||
t = I_32_RN_NEO_4 + offset; break;
|
||||
case TYPE_WS2811_400KHZ:
|
||||
return I_32_RN_400_3 + offset;
|
||||
t = I_32_RN_400_3 + offset; break;
|
||||
case TYPE_TM1814:
|
||||
return I_32_RN_TM1_4 + offset;
|
||||
t = I_32_RN_TM1_4 + offset; break;
|
||||
case TYPE_TM1829:
|
||||
return I_32_RN_TM2_3 + offset;
|
||||
t = I_32_RN_TM2_3 + offset; break;
|
||||
case TYPE_UCS8903:
|
||||
return I_32_RN_UCS_3 + offset;
|
||||
t = I_32_RN_UCS_3 + offset; break;
|
||||
case TYPE_UCS8904:
|
||||
return I_32_RN_UCS_4 + offset;
|
||||
t = I_32_RN_UCS_4 + offset; break;
|
||||
case TYPE_APA106:
|
||||
return I_32_RN_APA106_3 + offset;
|
||||
t = I_32_RN_APA106_3 + offset; break;
|
||||
case TYPE_FW1906:
|
||||
return I_32_RN_FW6_5 + offset;
|
||||
t = I_32_RN_FW6_5 + offset; break;
|
||||
case TYPE_WS2805:
|
||||
return I_32_RN_2805_5 + offset;
|
||||
t = I_32_RN_2805_5 + offset; break;
|
||||
case TYPE_TM1914:
|
||||
return I_32_RN_TM1914_3 + offset;
|
||||
t = I_32_RN_TM1914_3 + offset; break;
|
||||
case TYPE_SM16825:
|
||||
return I_32_RN_SM16825_5 + offset;
|
||||
t = I_32_RN_SM16825_5 + offset; break;
|
||||
}
|
||||
// If using parallel I2S, set the type accordingly
|
||||
if (_i2sChannelsAssigned == 1 && offset == 1) { // first I2S channel request, lock the type
|
||||
_parallelBusItype = t;
|
||||
#ifdef CONFIG_IDF_TARGET_ESP32S3
|
||||
_useParallelI2S = true; // ESP32-S3 always uses parallel I2S (LCD method)
|
||||
#endif
|
||||
}
|
||||
else if (offset == 1) { // not first I2S channel, use locked type and enable parallel flag
|
||||
_useParallelI2S = true;
|
||||
t = _parallelBusItype;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
return I_NONE;
|
||||
return t;
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
+11
-6
@@ -367,24 +367,29 @@ void handleIO()
|
||||
|
||||
// if we want to control on-board LED (ESP8266) or relay we have to do it here as the final show() may not happen until
|
||||
// next loop() cycle
|
||||
if (strip.getBrightness()) {
|
||||
handleOnOff();
|
||||
}
|
||||
|
||||
void handleOnOff(bool forceOff)
|
||||
{
|
||||
if (strip.getBrightness() && !forceOff) {
|
||||
lastOnTime = millis();
|
||||
if (offMode) {
|
||||
BusManager::on();
|
||||
if (rlyPin>=0) {
|
||||
pinMode(rlyPin, rlyOpenDrain ? OUTPUT_OPEN_DRAIN : OUTPUT);
|
||||
digitalWrite(rlyPin, rlyMde);
|
||||
delay(50); // wait for relay to switch and power to stabilize
|
||||
// note: pinMode is set in first call to handleOnOff(true) in beginStrip()
|
||||
digitalWrite(rlyPin, rlyMde); // set to on state
|
||||
delay(RELAY_DELAY); // let power stabilize before sending LED data (#346 #812 #3581 #3955)
|
||||
}
|
||||
offMode = false;
|
||||
}
|
||||
} else if (millis() - lastOnTime > 600 && !strip.needsUpdate()) {
|
||||
} else if ((millis() - lastOnTime > 600 && !strip.needsUpdate()) || forceOff) {
|
||||
// for turning LED or relay off we need to wait until strip no longer needs updates (strip.trigger())
|
||||
if (!offMode) {
|
||||
BusManager::off();
|
||||
if (rlyPin>=0) {
|
||||
digitalWrite(rlyPin, !rlyMde); // set output before disabling high-z state to avoid output glitches
|
||||
pinMode(rlyPin, rlyOpenDrain ? OUTPUT_OPEN_DRAIN : OUTPUT);
|
||||
digitalWrite(rlyPin, !rlyMde);
|
||||
}
|
||||
offMode = true;
|
||||
}
|
||||
|
||||
+80
-74
@@ -38,7 +38,7 @@ static constexpr bool validatePinsAndTypes(const unsigned* types, unsigned numTy
|
||||
//simple macro for ArduinoJSON's or syntax
|
||||
#define CJSON(a,b) a = b | a
|
||||
|
||||
void getStringFromJson(char* dest, const char* src, size_t len) {
|
||||
static inline void getStringFromJson(char* dest, const char* src, size_t len) {
|
||||
if (src != nullptr) strlcpy(dest, src, len);
|
||||
}
|
||||
|
||||
@@ -84,7 +84,8 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
JsonArray nw_ins = nw["ins"];
|
||||
if (!nw_ins.isNull()) {
|
||||
// as password are stored separately in wsec.json when reading configuration vector resize happens there, but for dynamic config we need to resize if necessary
|
||||
if (nw_ins.size() > 1 && nw_ins.size() > multiWiFi.size()) multiWiFi.resize(nw_ins.size()); // resize constructs objects while resizing
|
||||
size_t newSize = min((size_t)WLED_MAX_WIFI_COUNT, nw_ins.size()); // cap at WLED_MAX_WIFI_COUNT (prevent oversizing when too many Wi-Fi entries)
|
||||
if (nw_ins.size() > 1 && newSize > multiWiFi.size()) multiWiFi.resize(newSize); // resize constructs objects while resizing
|
||||
for (JsonObject wifi : nw_ins) {
|
||||
JsonArray ip = wifi["ip"];
|
||||
JsonArray gw = wifi["gw"];
|
||||
@@ -107,6 +108,17 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
multiWiFi[n].staticIP = nIP;
|
||||
multiWiFi[n].staticGW = nGW;
|
||||
multiWiFi[n].staticSN = nSN;
|
||||
#ifdef WLED_ENABLE_WPA_ENTERPRISE
|
||||
byte encType = WIFI_ENCRYPTION_TYPE_PSK;
|
||||
char anonIdent[65] = "";
|
||||
char ident[65] = "";
|
||||
CJSON(encType, wifi[F("enc_type")]);
|
||||
getStringFromJson(anonIdent, wifi["e_anon_ident"], 65);
|
||||
getStringFromJson(ident, wifi["e_ident"], 65);
|
||||
multiWiFi[n].encryptionType = encType;
|
||||
strlcpy(multiWiFi[n].enterpriseAnonIdentity, anonIdent, 65);
|
||||
strlcpy(multiWiFi[n].enterpriseIdentity, ident, 65);
|
||||
#endif
|
||||
if (++n >= WLED_MAX_WIFI_COUNT) break;
|
||||
}
|
||||
}
|
||||
@@ -131,7 +143,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
getStringFromJson(apPass, ap["psk"] , 65); //normally not present due to security
|
||||
//int ap_pskl = ap[F("pskl")];
|
||||
CJSON(apChannel, ap[F("chan")]);
|
||||
if (apChannel > 13 || apChannel < 1) apChannel = 1;
|
||||
if (apChannel > 13 || apChannel < 1) apChannel = 6; // reset to default if invalid
|
||||
CJSON(apHide, ap[F("hide")]);
|
||||
if (apHide > 1) apHide = 1;
|
||||
CJSON(apBehavior, ap[F("behav")]);
|
||||
@@ -165,10 +177,8 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
CJSON(cctICused, hw_led[F("ic")]);
|
||||
uint8_t cctBlending = hw_led[F("cb")] | Bus::getCCTBlend();
|
||||
Bus::setCCTBlend(cctBlending);
|
||||
strip.setTargetFps(hw_led["fps"]); //NOP if 0, default 42 FPS
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
CJSON(useParallelI2S, hw_led[F("prl")]);
|
||||
#endif
|
||||
unsigned targetFPS = hw_led["fps"] | WLED_FPS;
|
||||
strip.setTargetFps(targetFPS); //unlimited if 0, default 42 FPS
|
||||
|
||||
#ifndef WLED_DISABLE_2D
|
||||
// 2D Matrix Settings
|
||||
@@ -235,9 +245,10 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
maMax = 0;
|
||||
}
|
||||
ledType |= refresh << 7; // hack bit 7 to indicate strip requires off refresh
|
||||
uint8_t driverType = elm[F("drv")] | 0; // 0=RMT (default), 1=I2S note: polybus may override this if driver is not available
|
||||
|
||||
String host = elm[F("text")] | String();
|
||||
busConfigs.emplace_back(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz, maPerLed, maMax, host);
|
||||
busConfigs.emplace_back(ledType, pins, start, length, colorOrder, reversed, skipFirst, AWmode, freqkHz, maPerLed, maMax, driverType, host);
|
||||
doInitBusses = true; // finalization done in beginStrip()
|
||||
if (!Bus::isVirtual(ledType)) s++; // have as many virtual buses as you want
|
||||
}
|
||||
@@ -320,7 +331,7 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
unsigned start = 0;
|
||||
// analog always has length 1
|
||||
if (Bus::isPWM(dataType) || Bus::isOnOff(dataType)) count = 1;
|
||||
busConfigs.emplace_back(dataType, defPin, start, count, DEFAULT_LED_COLOR_ORDER, false, 0, RGBW_MODE_MANUAL_ONLY, 0);
|
||||
busConfigs.emplace_back(dataType, defPin, start, count, DEFAULT_LED_COLOR_ORDER, false, 0, RGBW_MODE_MANUAL_ONLY, 0, LED_MILLIAMPS_DEFAULT, ABL_MILLIAMPS_DEFAULT, 0); // driver=0 (RMT default)
|
||||
doInitBusses = true; // finalization done in beginStrip()
|
||||
}
|
||||
}
|
||||
@@ -509,11 +520,11 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
CJSON(gammaCorrectVal, light["gc"]["val"]); // default 2.2
|
||||
float light_gc_bri = light["gc"]["bri"] | 1.0f; // default to 1.0 (false)
|
||||
float light_gc_col = light["gc"]["col"] | gammaCorrectVal; // default to gammaCorrectVal (true)
|
||||
if (light_gc_bri > 1.0f) gammaCorrectBri = true;
|
||||
else gammaCorrectBri = false;
|
||||
if (light_gc_col > 1.0f) gammaCorrectCol = true;
|
||||
else gammaCorrectCol = false;
|
||||
if (gammaCorrectVal <= 1.0f || gammaCorrectVal > 3) {
|
||||
if (light_gc_bri != 1.0f) gammaCorrectBri = true;
|
||||
else gammaCorrectBri = false;
|
||||
if (light_gc_col != 1.0f) gammaCorrectCol = true;
|
||||
else gammaCorrectCol = false;
|
||||
if (gammaCorrectVal < 0.1f || gammaCorrectVal > 3) {
|
||||
gammaCorrectVal = 1.0f; // no gamma correction
|
||||
gammaCorrectBri = false;
|
||||
gammaCorrectCol = false;
|
||||
@@ -680,37 +691,28 @@ bool deserializeConfig(JsonObject doc, bool fromFS) {
|
||||
CJSON(macroCountdown, cntdwn["macro"]);
|
||||
setCountdown();
|
||||
|
||||
JsonArray timers = tm["ins"];
|
||||
uint8_t it = 0;
|
||||
for (JsonObject timer : timers) {
|
||||
if (it > 9) break;
|
||||
if (it<8 && timer[F("hour")]==255) it=8; // hour==255 -> sunrise/sunset
|
||||
CJSON(timerHours[it], timer[F("hour")]);
|
||||
CJSON(timerMinutes[it], timer["min"]);
|
||||
CJSON(timerMacro[it], timer["macro"]);
|
||||
|
||||
byte dowPrev = timerWeekday[it];
|
||||
//note: act is currently only 0 or 1.
|
||||
//the reason we are not using bool is that the on-disk type in 0.11.0 was already int
|
||||
int actPrev = timerWeekday[it] & 0x01;
|
||||
CJSON(timerWeekday[it], timer[F("dow")]);
|
||||
if (timerWeekday[it] != dowPrev) { //present in JSON
|
||||
timerWeekday[it] <<= 1; //add active bit
|
||||
int act = timer["en"] | actPrev;
|
||||
if (act) timerWeekday[it]++;
|
||||
JsonArray timersArray = tm["ins"];
|
||||
if (!timersArray.isNull()) {
|
||||
clearTimers();
|
||||
for (JsonObject timer : timersArray) {
|
||||
uint8_t h = timer[F("hour")] | 0;
|
||||
int8_t m = timer[F("min")] | 0;
|
||||
uint8_t p = timer[F("macro")] | 0;
|
||||
uint8_t dow = timer[F("dow")] | 127;
|
||||
uint8_t wd = (dow << 1) | ((timer[F("en")] | 0) ? 1 : 0);
|
||||
uint8_t ms = 1, me = 12, ds = 1, de = 31;
|
||||
JsonObject start = timer[F("start")];
|
||||
if (!start.isNull()) {
|
||||
ms = start[F("mon")] | 1;
|
||||
ds = start[F("day")] | 1;
|
||||
}
|
||||
JsonObject end = timer[F("end")];
|
||||
if (!end.isNull()) {
|
||||
me = end[F("mon")] | 12;
|
||||
de = end[F("day")] | 31;
|
||||
}
|
||||
addTimer(p, h, m, wd, ms, me, ds, de);
|
||||
}
|
||||
if (it<8) {
|
||||
JsonObject start = timer["start"];
|
||||
byte startm = start["mon"];
|
||||
if (startm) timerMonth[it] = (startm << 4);
|
||||
CJSON(timerDay[it], start["day"]);
|
||||
JsonObject end = timer["end"];
|
||||
CJSON(timerDayEnd[it], end["day"]);
|
||||
byte endm = end["mon"];
|
||||
if (startm) timerMonth[it] += endm & 0x0F;
|
||||
if (!(timerMonth[it] & 0x0F)) timerMonth[it] += 12; //default end month to 12
|
||||
}
|
||||
it++;
|
||||
}
|
||||
|
||||
JsonObject ota = doc["ota"];
|
||||
@@ -789,14 +791,14 @@ void resetConfig() {
|
||||
}
|
||||
|
||||
bool deserializeConfigFromFS() {
|
||||
[[maybe_unused]] bool success = deserializeConfigSec();
|
||||
(void) deserializeConfigSec(); // success/failure is ignored intentionally. We need to read cfg.json even when wsec.json has errors.
|
||||
|
||||
if (!requestJSONBufferLock(1)) return false;
|
||||
if (!requestJSONBufferLock(JSON_LOCK_CFG_DES)) return false;
|
||||
|
||||
DEBUG_PRINTLN(F("Reading settings from /cfg.json..."));
|
||||
|
||||
success = readObjectFromFile(s_cfg_json, nullptr, pDoc);
|
||||
|
||||
bool success = readObjectFromFile(s_cfg_json, nullptr, pDoc);
|
||||
if (!success || (pDoc->overflowed())) pDoc->clear(); // corrupted/too-large → same as missing: seed defaults
|
||||
// NOTE: This routine deserializes *and* applies the configuration
|
||||
// Therefore, must also initialize ethernet from this function
|
||||
JsonObject root = pDoc->as<JsonObject>();
|
||||
@@ -812,7 +814,7 @@ void serializeConfigToFS() {
|
||||
|
||||
DEBUG_PRINTLN(F("Writing settings to /cfg.json..."));
|
||||
|
||||
if (!requestJSONBufferLock(2)) return;
|
||||
if (!requestJSONBufferLock(JSON_LOCK_CFG_SER)) return;
|
||||
|
||||
JsonObject root = pDoc->to<JsonObject>();
|
||||
|
||||
@@ -866,6 +868,13 @@ void serializeConfig(JsonObject root) {
|
||||
wifi_gw.add(multiWiFi[n].staticGW[i]);
|
||||
wifi_sn.add(multiWiFi[n].staticSN[i]);
|
||||
}
|
||||
#ifdef WLED_ENABLE_WPA_ENTERPRISE
|
||||
wifi[F("enc_type")] = multiWiFi[n].encryptionType;
|
||||
if (multiWiFi[n].encryptionType == WIFI_ENCRYPTION_TYPE_ENTERPRISE) {
|
||||
wifi[F("e_anon_ident")] = multiWiFi[n].enterpriseAnonIdentity;
|
||||
wifi[F("e_ident")] = multiWiFi[n].enterpriseIdentity;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
JsonArray dns = nw.createNestedArray(F("dns"));
|
||||
@@ -929,9 +938,6 @@ void serializeConfig(JsonObject root) {
|
||||
hw_led[F("cb")] = Bus::getCCTBlend();
|
||||
hw_led["fps"] = strip.getTargetFps();
|
||||
hw_led[F("rgbwm")] = Bus::getGlobalAWMode(); // global auto white mode override
|
||||
#if defined(ARDUINO_ARCH_ESP32) && !defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
hw_led[F("prl")] = BusManager::hasParallelOutput();
|
||||
#endif
|
||||
|
||||
#ifndef WLED_DISABLE_2D
|
||||
// 2D Matrix Settings
|
||||
@@ -958,7 +964,7 @@ void serializeConfig(JsonObject root) {
|
||||
for (size_t s = 0; s < BusManager::getNumBusses(); s++) {
|
||||
DEBUG_PRINTF_P(PSTR("Cfg: Saving bus #%u\n"), s);
|
||||
const Bus *bus = BusManager::getBus(s);
|
||||
if (!bus || !bus->isOk()) break;
|
||||
if (!bus) break; // Memory corruption, iterator invalid
|
||||
DEBUG_PRINTF_P(PSTR(" (%d-%d, type:%d, CO:%d, rev:%d, skip:%d, AW:%d kHz:%d, mA:%d/%d)\n"),
|
||||
(int)bus->getStart(), (int)(bus->getStart()+bus->getLength()),
|
||||
(int)(bus->getType() & 0x7F),
|
||||
@@ -985,6 +991,7 @@ void serializeConfig(JsonObject root) {
|
||||
ins[F("freq")] = bus->getFrequency();
|
||||
ins[F("maxpwr")] = bus->getMaxCurrent();
|
||||
ins[F("ledma")] = bus->getLEDCurrent();
|
||||
ins[F("drv")] = bus->getDriverType();
|
||||
ins[F("text")] = bus->getCustomText();
|
||||
}
|
||||
|
||||
@@ -1202,23 +1209,21 @@ void serializeConfig(JsonObject root) {
|
||||
cntdwn["macro"] = macroCountdown;
|
||||
|
||||
JsonArray timers_ins = timers.createNestedArray("ins");
|
||||
|
||||
for (unsigned i = 0; i < 10; i++) {
|
||||
if (timerMacro[i] == 0 && timerHours[i] == 0 && timerMinutes[i] == 0) continue; // sunrise/sunset get saved always (timerHours=255)
|
||||
JsonObject timers_ins0 = timers_ins.createNestedObject();
|
||||
timers_ins0["en"] = (timerWeekday[i] & 0x01);
|
||||
timers_ins0[F("hour")] = timerHours[i];
|
||||
timers_ins0["min"] = timerMinutes[i];
|
||||
timers_ins0["macro"] = timerMacro[i];
|
||||
timers_ins0[F("dow")] = timerWeekday[i] >> 1;
|
||||
if (i<8) {
|
||||
JsonObject start = timers_ins0.createNestedObject("start");
|
||||
start["mon"] = (timerMonth[i] >> 4) & 0xF;
|
||||
start["day"] = timerDay[i];
|
||||
JsonObject end = timers_ins0.createNestedObject("end");
|
||||
end["mon"] = timerMonth[i] & 0xF;
|
||||
end["day"] = timerDayEnd[i];
|
||||
}
|
||||
for (size_t i = 0; i < ::timers.size(); i++) {
|
||||
const Timer& t = ::timers[i];
|
||||
if (t.preset == 0 && t.hour == 0 && t.minute == 0) continue;
|
||||
JsonObject ti = timers_ins.createNestedObject();
|
||||
ti[F("en")] = t.isEnabled() ? 1 : 0;
|
||||
ti[F("hour")] = t.hour;
|
||||
ti[F("min")] = t.minute;
|
||||
ti[F("macro")] = t.preset;
|
||||
ti[F("dow")] = t.weekdays >> 1;
|
||||
JsonObject start = ti.createNestedObject(F("start"));
|
||||
start[F("mon")] = t.monthStart;
|
||||
start[F("day")] = t.dayStart;
|
||||
JsonObject end = ti.createNestedObject(F("end"));
|
||||
end[F("mon")] = t.monthEnd;
|
||||
end[F("day")] = t.dayEnd;
|
||||
}
|
||||
|
||||
JsonObject ota = root.createNestedObject("ota");
|
||||
@@ -1256,10 +1261,10 @@ static const char s_wsec_json[] PROGMEM = "/wsec.json";
|
||||
bool deserializeConfigSec() {
|
||||
DEBUG_PRINTLN(F("Reading settings from /wsec.json..."));
|
||||
|
||||
if (!requestJSONBufferLock(3)) return false;
|
||||
if (!requestJSONBufferLock(JSON_LOCK_CFG_SEC_DES)) return false;
|
||||
|
||||
bool success = readObjectFromFile(s_wsec_json, nullptr, pDoc);
|
||||
if (!success) {
|
||||
if (!success || pDoc->overflowed() || pDoc->size() < 1) { // reject if overflowed (noMemory) or empty
|
||||
releaseJSONBufferLock();
|
||||
return false;
|
||||
}
|
||||
@@ -1269,7 +1274,8 @@ bool deserializeConfigSec() {
|
||||
size_t n = 0;
|
||||
JsonArray nw_ins = root["nw"]["ins"];
|
||||
if (!nw_ins.isNull()) {
|
||||
if (nw_ins.size() > 1 && nw_ins.size() > multiWiFi.size()) multiWiFi.resize(nw_ins.size()); // resize constructs objects while resizing
|
||||
size_t newSize = min((size_t)WLED_MAX_WIFI_COUNT, nw_ins.size()); // cap at WLED_MAX_WIFI_COUNT (prevent oversizing when too many Wi-Fi entries)
|
||||
if (nw_ins.size() > 1 && newSize > multiWiFi.size()) multiWiFi.resize(newSize); // resize constructs objects while resizing
|
||||
for (JsonObject wifi : nw_ins) {
|
||||
char pw[65] = "";
|
||||
getStringFromJson(pw, wifi["psk"], 65);
|
||||
@@ -1310,7 +1316,7 @@ bool deserializeConfigSec() {
|
||||
void serializeConfigSec() {
|
||||
DEBUG_PRINTLN(F("Writing settings to /wsec.json..."));
|
||||
|
||||
if (!requestJSONBufferLock(4)) return;
|
||||
if (!requestJSONBufferLock(JSON_LOCK_CFG_SEC_SER)) return;
|
||||
|
||||
JsonObject root = pDoc->to<JsonObject>();
|
||||
|
||||
|
||||
+135
-80
@@ -1,12 +1,21 @@
|
||||
#include "wled.h"
|
||||
#include "fcn_declare.h"
|
||||
#include "colors.h"
|
||||
|
||||
/*
|
||||
* Color conversion & utility methods
|
||||
*/
|
||||
|
||||
/*
|
||||
* color blend function, based on FastLED blend function
|
||||
* the calculation for each color is: result = (A*(amountOfA) + A + B*(amountOfB) + B) / 256 with amountOfA = 255 - amountOfB
|
||||
* FastLED Reference
|
||||
* -----------------
|
||||
* functions in this file derived from FastLED @ 3.6.0 (https://github.com/FastLED/FastLED) are marked with a comment containing "derived from FastLED"
|
||||
* those functions are therefore licensed under the MIT license See /src/dependencies/fastled_slim/LICENSE.txt for details.
|
||||
*/
|
||||
|
||||
/*
|
||||
* color blend function
|
||||
* the calculation for each color is: result = (C1*(256-blend)+C2+C2*blend) / 256
|
||||
*/
|
||||
uint32_t WLED_O2_ATTR IRAM_ATTR color_blend(uint32_t color1, uint32_t color2, uint8_t blend) {
|
||||
// min / max blend checking is omitted: calls with 0 or 255 are rare, checking lowers overall performance
|
||||
@@ -25,7 +34,7 @@ uint32_t WLED_O2_ATTR IRAM_ATTR color_blend(uint32_t color1, uint32_t color2, ui
|
||||
* original idea: https://github.com/wled-dev/WLED/pull/2465 by https://github.com/Proto-molecule
|
||||
* speed optimisations by @dedehai
|
||||
*/
|
||||
uint32_t WLED_O2_ATTR color_add(uint32_t c1, uint32_t c2, bool preserveCR) //1212558 | 1212598 | 1212576 | 1212530
|
||||
uint32_t WLED_O2_ATTR color_add(uint32_t c1, uint32_t c2, bool preserveCR)
|
||||
{
|
||||
if (c1 == BLACK) return c2;
|
||||
if (c2 == BLACK) return c1;
|
||||
@@ -40,10 +49,9 @@ uint32_t WLED_O2_ATTR color_add(uint32_t c1, uint32_t c2, bool preserveCR) //121
|
||||
uint32_t b = rb & 0xFFFF;
|
||||
uint32_t w = wg >> 16;
|
||||
uint32_t g = wg & 0xFFFF;
|
||||
uint32_t max = std::max(r,g);
|
||||
max = std::max(max,b);
|
||||
max = std::max(max,w);
|
||||
const uint32_t scale = (uint32_t(255)<<8) / max; // division of two 8bit (shifted) values does not work -> use bit shifts and multiplaction instead
|
||||
uint32_t maxval = (r > g) ? ((r > b) ? r : b) : ((g > b) ? g : b); // find max value. note: faster than using max() function or on par
|
||||
maxval = (w > maxval) ? w : maxval; // check white channel as well to avoid division by zero in pure white input
|
||||
const uint32_t scale = (uint32_t(255)<<8) / maxval; // division of two 8bit (shifted) values does not work -> use bit shifts and multiplaction instead
|
||||
rb = ((rb * scale) >> 8) & TWO_CHANNEL_MASK;
|
||||
wg = (wg * scale) & ~TWO_CHANNEL_MASK;
|
||||
} else wg <<= 8; //shift white and green back to correct position
|
||||
@@ -60,48 +68,54 @@ uint32_t WLED_O2_ATTR color_add(uint32_t c1, uint32_t c2, bool preserveCR) //121
|
||||
|
||||
/*
|
||||
* fades color toward black
|
||||
* if using "video" method the resulting color will never become black unless it is already black
|
||||
* if using "video" method the resulting color will not become black unless it is already black or distorts the hue
|
||||
*/
|
||||
uint32_t IRAM_ATTR color_fade(uint32_t c1, uint8_t amount, bool video) {
|
||||
if (c1 == BLACK || amount == 0) return 0; // black or full fade
|
||||
if (amount == 255) return c1; // no change
|
||||
uint32_t addRemains = 0;
|
||||
|
||||
if (!video) amount++; // add one for correct scaling using bitshifts
|
||||
else {
|
||||
// video scaling: make sure colors do not dim to zero if they started non-zero unless they distort the hue
|
||||
uint8_t r = byte(c1>>16), g = byte(c1>>8), b = byte(c1), w = byte(c1>>24); // extract r, g, b, w channels
|
||||
uint8_t maxc = (r > g) ? ((r > b) ? r : b) : ((g > b) ? g : b); // determine dominant channel for hue preservation
|
||||
addRemains = r && (r<<5) > maxc ? 0x00010000 : 0; // note: setting color preservation threshold too high results in flickering and
|
||||
addRemains |= g && (g<<5) > maxc ? 0x00000100 : 0; // jumping colors in low brightness gradients. Multiplying the color preserves
|
||||
addRemains |= b && (b<<5) > maxc ? 0x00000001 : 0; // better accuracy than dividing the maxc. Shifting by 5 is a good compromise
|
||||
addRemains |= w ? 0x01000000 : 0; // i.e. remove color channel if <13% of max
|
||||
}
|
||||
const uint32_t TWO_CHANNEL_MASK = 0x00FF00FF;
|
||||
uint32_t rb = (((c1 & TWO_CHANNEL_MASK) * amount) >> 8) & TWO_CHANNEL_MASK; // scale red and blue
|
||||
uint32_t wg = (((c1 >> 8) & TWO_CHANNEL_MASK) * amount) & ~TWO_CHANNEL_MASK; // scale white and green
|
||||
return (rb | wg) + addRemains;
|
||||
uint32_t rb = c1 & TWO_CHANNEL_MASK; // extract R and B channels
|
||||
uint32_t wg = (c1 >> 8) & TWO_CHANNEL_MASK; // extract W and G channels (shifted for multiplication)
|
||||
uint32_t rb_scaled;
|
||||
uint32_t wg_scaled;
|
||||
|
||||
// video scaling: make sure colors do not dim to zero if they started non-zero unless they distort the hue
|
||||
if (video) {
|
||||
rb_scaled = ((rb * amount + 0x007F007F) >> 8) & TWO_CHANNEL_MASK; // scale red and blue, add 0.5 for rounding
|
||||
wg_scaled = (wg * amount + 0x007F007F) & ~TWO_CHANNEL_MASK; // scale white and green, add 0.5 for rounding
|
||||
uint8_t r = byte(rb>>16), g = byte(wg), b = byte(rb), w = byte(wg>>16); // extract r, g, b, w channels from original color (wg is shifted)
|
||||
uint8_t maxc = (r > g) ? ((r > b) ? r : b) : ((g > b) ? g : b); // determine dominant channel for hue preservation
|
||||
maxc = (maxc>>2) + 1; // divide by 4 to get ~25% threshold for hue preservation, add 1 to prevent "washout" of very dark colors (prevents them becoming gray)
|
||||
rb_scaled |= r > maxc ? 0x00010000 : 0;
|
||||
wg_scaled |= g > maxc ? 0x00000100 : 0;
|
||||
rb_scaled |= b > maxc ? 0x00000001 : 0;
|
||||
wg_scaled |= w ? 0x01000000 : 0; // preserve white if it is present
|
||||
} else {
|
||||
rb_scaled = ((rb * (amount + 1)) >> 8) & TWO_CHANNEL_MASK; // scale red and blue
|
||||
wg_scaled = ((wg * (amount + 1)) & ~TWO_CHANNEL_MASK); // scale white and green
|
||||
}
|
||||
|
||||
return (rb_scaled | wg_scaled);
|
||||
}
|
||||
|
||||
/*
|
||||
* color adjustment in HSV color space (converts RGB to HSV and back), color conversions are not 100% accurate!
|
||||
shifts hue, increase brightness, decreases saturation (if not black)
|
||||
note: inputs are 32bit to speed up the function, useful input value ranges are 0-255
|
||||
* shifts hue, increase brightness, decreases saturation (if not black)
|
||||
* note: inputs are 32bit to speed up the function, useful input value ranges are -255 to +255
|
||||
* note2: if only one hue change is needed, use CRGBW.adjust_hue() instead (much faster)
|
||||
*/
|
||||
uint32_t adjust_color(uint32_t rgb, uint32_t hueShift, uint32_t lighten, uint32_t brighten) {
|
||||
if (rgb == 0 || hueShift + lighten + brighten == 0) return rgb; // black or no change
|
||||
WLED_O3_ATTR void adjust_color(CRGBW& rgb, int32_t hueShift, int32_t satChange, int32_t valueChange) {
|
||||
if(rgb.color32 == 0 && valueChange <= 0) return; // black and no value change -> return black
|
||||
CHSV32 hsv;
|
||||
rgb2hsv(rgb, hsv); //convert to HSV
|
||||
hsv.h += (hueShift << 8); // shift hue (hue is 16 bits)
|
||||
hsv.s = max((int32_t)0, (int32_t)hsv.s - (int32_t)lighten); // desaturate
|
||||
hsv.v = min((uint32_t)255, (uint32_t)hsv.v + brighten); // increase brightness
|
||||
uint32_t rgb_adjusted;
|
||||
hsv2rgb(hsv, rgb_adjusted); // convert back to RGB TODO: make this into 16 bit conversion
|
||||
return rgb_adjusted;
|
||||
hsv.s = (int)hsv.s + satChange < 0 ? 0 : ((int)hsv.s + satChange > 255 ? 255 : (int)hsv.s + satChange);
|
||||
hsv.v = (int)hsv.v + valueChange < 0 ? 0 : ((int)hsv.v + valueChange > 255 ? 255 : (int)hsv.v + valueChange);
|
||||
hsv2rgb_spectrum(hsv, rgb); // convert back to RGB
|
||||
}
|
||||
|
||||
// 1:1 replacement of fastled function optimized for ESP, slightly faster, more accurate and uses less flash (~ -200bytes)
|
||||
uint32_t ColorFromPaletteWLED(const CRGBPalette16& pal, unsigned index, uint8_t brightness, TBlendType blendType) {
|
||||
// derived from FastLED: replacement of fastled function optimized for ESP, slightly faster, more accurate and uses less flash (~ -200bytes)
|
||||
uint32_t ColorFromPalette(const CRGBPalette16& pal, unsigned index, uint8_t brightness, TBlendType blendType) {
|
||||
if (blendType == LINEARBLEND_NOWRAP) {
|
||||
index = (index * 0xF0) >> 8; // Blend range is affected by lo4 blend of values, remap to avoid wrapping
|
||||
}
|
||||
@@ -249,12 +263,13 @@ void loadCustomPalettes() {
|
||||
byte tcp[72]; //support gradient palettes with up to 18 entries
|
||||
CRGBPalette16 targetPalette;
|
||||
customPalettes.clear(); // start fresh
|
||||
StaticJsonDocument<1536> pDoc; // barely enough to fit 72 numbers -> TODO: current format uses 214 bytes max per palette, why is this buffer so large?
|
||||
unsigned emptyPaletteGap = 0; // count gaps in palette files to stop looking for more (each exists() call takes ~5ms)
|
||||
for (int index = 0; index < WLED_MAX_CUSTOM_PALETTES; index++) {
|
||||
char fileName[32];
|
||||
sprintf_P(fileName, PSTR("/palette%d.json"), index);
|
||||
|
||||
StaticJsonDocument<1536> pDoc; // barely enough to fit 72 numbers
|
||||
if (WLED_FS.exists(fileName)) {
|
||||
emptyPaletteGap = 0; // reset gap counter if file exists
|
||||
DEBUGFX_PRINTF_P(PSTR("Reading palette from %s\n"), fileName);
|
||||
if (readObjectFromFile(fileName, nullptr, &pDoc)) {
|
||||
JsonArray pal = pDoc[F("palette")];
|
||||
@@ -288,69 +303,109 @@ void loadCustomPalettes() {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
emptyPaletteGap++;
|
||||
if (emptyPaletteGap > WLED_MAX_CUSTOM_PALETTE_GAP) break; // stop looking for more palettes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void hsv2rgb(const CHSV32& hsv, uint32_t& rgb) // convert HSV (16bit hue) to RGB (32bit with white = 0)
|
||||
{
|
||||
unsigned int remainder, region, p, q, t;
|
||||
unsigned int h = hsv.h;
|
||||
unsigned int s = hsv.s;
|
||||
unsigned int v = hsv.v;
|
||||
if (s == 0) {
|
||||
rgb = v << 16 | v << 8 | v;
|
||||
return;
|
||||
// convert HSV (16bit hue) to RGB (32bit with white = 0), optimized for speed
|
||||
WLED_O2_ATTR void hsv2rgb_spectrum(const CHSV32& hsv, CRGBW& rgb) {
|
||||
unsigned p, q, t;
|
||||
unsigned region = ((unsigned)hsv.h * 6) >> 16; // h / (65536 / 6)
|
||||
unsigned remainder = (hsv.h - (region * 10923)) * 6; // 10923 = (65536 / 6)
|
||||
|
||||
// check for zero saturation
|
||||
if (hsv.s == 0) {
|
||||
rgb.r = rgb.g = rgb.b = hsv.v;
|
||||
return;
|
||||
}
|
||||
region = h / 10923; // 65536 / 6 = 10923
|
||||
remainder = (h - (region * 10923)) * 6;
|
||||
p = (v * (255 - s)) >> 8;
|
||||
q = (v * (255 - ((s * remainder) >> 16))) >> 8;
|
||||
t = (v * (255 - ((s * (65535 - remainder)) >> 16))) >> 8;
|
||||
|
||||
p = (hsv.v * (255 - hsv.s)) >> 8;
|
||||
q = (hsv.v * (255 - ((hsv.s * remainder) >> 16))) >> 8;
|
||||
t = (hsv.v * (255 - ((hsv.s * (65535 - remainder)) >> 16))) >> 8;
|
||||
switch (region) {
|
||||
case 0:
|
||||
rgb = v << 16 | t << 8 | p; break;
|
||||
rgb.r = hsv.v;
|
||||
rgb.g = t;
|
||||
rgb.b = p;
|
||||
break;
|
||||
case 1:
|
||||
rgb = q << 16 | v << 8 | p; break;
|
||||
rgb.r = q;
|
||||
rgb.g = hsv.v;
|
||||
rgb.b = p;
|
||||
break;
|
||||
case 2:
|
||||
rgb = p << 16 | v << 8 | t; break;
|
||||
rgb.r = p;
|
||||
rgb.g = hsv.v;
|
||||
rgb.b = t;
|
||||
break;
|
||||
case 3:
|
||||
rgb = p << 16 | q << 8 | v; break;
|
||||
rgb.r = p;
|
||||
rgb.g = q;
|
||||
rgb.b = hsv.v;
|
||||
break;
|
||||
case 4:
|
||||
rgb = t << 16 | p << 8 | v; break;
|
||||
rgb.r = t;
|
||||
rgb.g = p;
|
||||
rgb.b = hsv.v;
|
||||
break;
|
||||
default:
|
||||
rgb = v << 16 | p << 8 | q; break;
|
||||
rgb.r = hsv.v;
|
||||
rgb.g = p;
|
||||
rgb.b = q;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void rgb2hsv(const uint32_t rgb, CHSV32& hsv) // convert RGB to HSV (16bit hue), much more accurate and faster than fastled version
|
||||
{
|
||||
hsv.raw = 0;
|
||||
int32_t r = (rgb>>16)&0xFF;
|
||||
int32_t g = (rgb>>8)&0xFF;
|
||||
int32_t b = rgb&0xFF;
|
||||
int32_t minval, maxval, delta;
|
||||
minval = min(r, g);
|
||||
minval = min(minval, b);
|
||||
maxval = max(r, g);
|
||||
maxval = max(maxval, b);
|
||||
if (maxval == 0) return; // black
|
||||
hsv.v = maxval;
|
||||
delta = maxval - minval;
|
||||
// CHSV to CRGB wrapper conversion: slower so this should not be used in time critical code, use rainbow version instead
|
||||
void hsv2rgb_spectrum(const CHSV& hsv, CRGB& rgb) {
|
||||
CHSV32 hsv32(hsv);
|
||||
CRGBW rgb32;
|
||||
hsv2rgb_spectrum(hsv32, rgb32);
|
||||
rgb = CRGB(rgb32);
|
||||
}
|
||||
|
||||
// convert RGB to HSV (16bit hue), not 100% color accurate. note: using "O3" makes it ~5% faster at minimal flash cost (~20 bytes)
|
||||
WLED_O3_ATTR void rgb2hsv(const CRGBW& rgb, CHSV32& hsv) {
|
||||
int32_t r = rgb.r; // note: using 32bit variables tested faster than 8bit
|
||||
int32_t g = rgb.g;
|
||||
int32_t b = rgb.b;
|
||||
uint32_t minval, maxval;
|
||||
int32_t delta;
|
||||
// find min/max value. note: faster than using min/max functions (lets compiler optimize more when using "O3"), other variants (nested ifs, xor) tested slower
|
||||
maxval = (r > g) ? ((r > b) ? r : b) : ((g > b) ? g : b);
|
||||
if (maxval == 0) {
|
||||
hsv.hsv32 = 0;
|
||||
return; // black, avoids division by zero
|
||||
}
|
||||
minval = (r < g) ? ((r < b) ? r : b) : ((g < b) ? g : b);
|
||||
hsv.v = maxval;
|
||||
delta = maxval - minval;
|
||||
if (delta != 0) {
|
||||
hsv.s = (255 * delta) / maxval;
|
||||
if (hsv.s == 0) return; // gray value
|
||||
if (maxval == r) hsv.h = (10923 * (g - b)) / delta;
|
||||
else if (maxval == g) hsv.h = 21845 + (10923 * (b - r)) / delta;
|
||||
else hsv.h = 43690 + (10923 * (r - g)) / delta;
|
||||
// note: early return if s==0 is omitted here to increase speed as gray values are rarely used
|
||||
if (maxval == r) hsv.h = (uint16_t)((10923 * (g - b)) / delta);
|
||||
else if (maxval == g) hsv.h = (uint16_t)(21845 + (10923 * (b - r)) / delta);
|
||||
else hsv.h = (uint16_t)(43690 + (10923 * (r - g)) / delta);
|
||||
} else {
|
||||
hsv.s = 0;
|
||||
hsv.h = 0; // gray, hue is undefined but set to 0 for consistency
|
||||
}
|
||||
}
|
||||
|
||||
CHSV rgb2hsv(const CRGB c) { // CRGB to CHSV
|
||||
CHSV32 hsv;
|
||||
rgb2hsv(CRGBW(c), hsv);
|
||||
return CHSV(hsv);
|
||||
}
|
||||
|
||||
void colorHStoRGB(uint16_t hue, byte sat, byte* rgb) { //hue, sat to rgb
|
||||
uint32_t crgb;
|
||||
hsv2rgb(CHSV32(hue, sat, 255), crgb);
|
||||
rgb[0] = byte((crgb) >> 16);
|
||||
rgb[1] = byte((crgb) >> 8);
|
||||
rgb[2] = byte(crgb);
|
||||
CRGBW crgb;
|
||||
hsv2rgb_spectrum(CHSV32(hue, sat, 255), crgb);
|
||||
rgb[0] = crgb.r;
|
||||
rgb[1] = crgb.g;
|
||||
rgb[2] = crgb.b;
|
||||
}
|
||||
|
||||
//get RGB values from color temperature in K (https://tannerhelland.com/2012/09/18/convert-temperature-rgb-algorithm-code.html)
|
||||
|
||||
+141
-90
@@ -1,96 +1,34 @@
|
||||
#pragma once
|
||||
#ifndef WLED_COLORS_H
|
||||
#define WLED_COLORS_H
|
||||
|
||||
#include <vector>
|
||||
#include "src/dependencies/fastled_slim/fastled_slim.h"
|
||||
/*
|
||||
* Color structs and color utility functions
|
||||
*/
|
||||
#include <vector>
|
||||
#include "FastLED.h"
|
||||
/*
|
||||
Note on color types and conversions:
|
||||
- WLED uses 32bit colors (RGBW), if possible, use CRGBW instead of CRGB for better performance (no conversion in setPixelColor)
|
||||
- use CRGB if RAM usage is of concern (i.e. for larger color arrays)
|
||||
- direct conversion (assignment or construction) from CHSV/CHSV32 to CRGB/CRGBW use the "rainbow" method (nicer colors, see fastled documentation)
|
||||
- converting CRGB(W) to HSV32 color is quite accurate but still not 100% (but much more accurate than fastled's "hsv2rgb_approximate" function)
|
||||
- when converting CRGB(W) to HSV32 and back, "hsv2rgb_spectrum" preserves the colors better than the _rainbow version
|
||||
- to manipulate an RGB color in HSV space, use the adjust_color function or the CRGBW.adjust_hue method
|
||||
|
||||
#define ColorFromPalette ColorFromPaletteWLED // override fastled version
|
||||
Some functions in this file are derived from FastLED (https://github.com/FastLED/FastLED) licensed under the MIT license.
|
||||
See /src/dependencies/fastled_slim/LICENSE.txt for details.
|
||||
*/
|
||||
|
||||
// CRGBW can be used to manipulate 32bit colors faster. However: if it is passed to functions, it adds overhead compared to a uint32_t color
|
||||
// use with caution and pay attention to flash size. Usually converting a uint32_t to CRGBW to extract r, g, b, w values is slower than using bitshifts
|
||||
// it can be useful to avoid back and forth conversions between uint32_t and fastled CRGB
|
||||
struct CRGBW {
|
||||
union {
|
||||
uint32_t color32; // Access as a 32-bit value (0xWWRRGGBB)
|
||||
struct {
|
||||
uint8_t b;
|
||||
uint8_t g;
|
||||
uint8_t r;
|
||||
uint8_t w;
|
||||
};
|
||||
uint8_t raw[4]; // Access as an array in the order B, G, R, W
|
||||
};
|
||||
// 32bit color mangling macros
|
||||
#define RGBW32(r,g,b,w) (uint32_t((byte(w) << 24) | (byte(r) << 16) | (byte(g) << 8) | (byte(b))))
|
||||
#define R(c) (byte((c) >> 16))
|
||||
#define G(c) (byte((c) >> 8))
|
||||
#define B(c) (byte(c))
|
||||
#define W(c) (byte((c) >> 24))
|
||||
|
||||
// Default constructor
|
||||
inline CRGBW() __attribute__((always_inline)) = default;
|
||||
struct CRGBW; // forward declations
|
||||
struct CHSV32;
|
||||
|
||||
// Constructor from a 32-bit color (0xWWRRGGBB)
|
||||
constexpr CRGBW(uint32_t color) __attribute__((always_inline)) : color32(color) {}
|
||||
|
||||
// Constructor with r, g, b, w values
|
||||
constexpr CRGBW(uint8_t red, uint8_t green, uint8_t blue, uint8_t white = 0) __attribute__((always_inline)) : b(blue), g(green), r(red), w(white) {}
|
||||
|
||||
// Constructor from CRGB
|
||||
constexpr CRGBW(CRGB rgb) __attribute__((always_inline)) : b(rgb.b), g(rgb.g), r(rgb.r), w(0) {}
|
||||
|
||||
// Access as an array
|
||||
inline const uint8_t& operator[] (uint8_t x) const __attribute__((always_inline)) { return raw[x]; }
|
||||
|
||||
// Assignment from 32-bit color
|
||||
inline CRGBW& operator=(uint32_t color) __attribute__((always_inline)) { color32 = color; return *this; }
|
||||
|
||||
// Assignment from r, g, b, w
|
||||
inline CRGBW& operator=(const CRGB& rgb) __attribute__((always_inline)) { b = rgb.b; g = rgb.g; r = rgb.r; w = 0; return *this; }
|
||||
|
||||
// Conversion operator to uint32_t
|
||||
inline operator uint32_t() const __attribute__((always_inline)) {
|
||||
return color32;
|
||||
}
|
||||
/*
|
||||
// Conversion operator to CRGB
|
||||
inline operator CRGB() const __attribute__((always_inline)) {
|
||||
return CRGB(r, g, b);
|
||||
}
|
||||
|
||||
CRGBW& scale32 (uint8_t scaledown) // 32bit math
|
||||
{
|
||||
if (color32 == 0) return *this; // 2 extra instructions, worth it if called a lot on black (which probably is true) adding check if scaledown is zero adds much more overhead as its 8bit
|
||||
uint32_t scale = scaledown + 1;
|
||||
uint32_t rb = (((color32 & 0x00FF00FF) * scale) >> 8) & 0x00FF00FF; // scale red and blue
|
||||
uint32_t wg = (((color32 & 0xFF00FF00) >> 8) * scale) & 0xFF00FF00; // scale white and green
|
||||
color32 = rb | wg;
|
||||
return *this;
|
||||
}*/
|
||||
|
||||
};
|
||||
|
||||
struct CHSV32 { // 32bit HSV color with 16bit hue for more accurate conversions
|
||||
union {
|
||||
struct {
|
||||
uint16_t h; // hue
|
||||
uint8_t s; // saturation
|
||||
uint8_t v; // value
|
||||
};
|
||||
uint32_t raw; // 32bit access
|
||||
};
|
||||
inline CHSV32() __attribute__((always_inline)) = default; // default constructor
|
||||
|
||||
/// Allow construction from hue, saturation, and value
|
||||
/// @param ih input hue
|
||||
/// @param is input saturation
|
||||
/// @param iv input value
|
||||
inline CHSV32(uint16_t ih, uint8_t is, uint8_t iv) __attribute__((always_inline)) // constructor from 16bit h, s, v
|
||||
: h(ih), s(is), v(iv) {}
|
||||
inline CHSV32(uint8_t ih, uint8_t is, uint8_t iv) __attribute__((always_inline)) // constructor from 8bit h, s, v
|
||||
: h((uint16_t)ih << 8), s(is), v(iv) {}
|
||||
inline CHSV32(const CHSV& chsv) __attribute__((always_inline)) // constructor from CHSV
|
||||
: h((uint16_t)chsv.h << 8), s(chsv.s), v(chsv.v) {}
|
||||
inline operator CHSV() const { return CHSV((uint8_t)(h >> 8), s, v); } // typecast to CHSV
|
||||
};
|
||||
extern bool gammaCorrectCol;
|
||||
// similar to NeoPixelBus NeoGammaTableMethod but allows dynamic changes (superseded by NPB::NeoGammaDynamicTableMethod)
|
||||
class NeoGammaWLEDMethod {
|
||||
@@ -118,18 +56,20 @@ class NeoGammaWLEDMethod {
|
||||
inline uint32_t color_blend16(uint32_t c1, uint32_t c2, uint16_t b) { return color_blend(c1, c2, b >> 8); };
|
||||
[[gnu::hot, gnu::pure]] uint32_t color_add(uint32_t, uint32_t, bool preserveCR = false);
|
||||
[[gnu::hot, gnu::pure]] uint32_t color_fade(uint32_t c1, uint8_t amount, bool video = false);
|
||||
[[gnu::hot, gnu::pure]] uint32_t adjust_color(uint32_t rgb, uint32_t hueShift, uint32_t lighten, uint32_t brighten);
|
||||
[[gnu::hot, gnu::pure]] uint32_t ColorFromPaletteWLED(const CRGBPalette16 &pal, unsigned index, uint8_t brightness = (uint8_t)255U, TBlendType blendType = LINEARBLEND);
|
||||
void adjust_color(CRGBW& rgb, int32_t hueShift, int32_t satChange,int32_t valueChange);
|
||||
|
||||
[[gnu::hot, gnu::pure]] uint32_t ColorFromPalette(const CRGBPalette16 &pal, unsigned index, uint8_t brightness = (uint8_t)255U, TBlendType blendType = LINEARBLEND);
|
||||
CRGBPalette16 generateHarmonicRandomPalette(const CRGBPalette16 &basepalette);
|
||||
CRGBPalette16 generateRandomPalette();
|
||||
void loadCustomPalettes();
|
||||
extern std::vector<CRGBPalette16> customPalettes;
|
||||
inline size_t getPaletteCount() { return FIXED_PALETTE_COUNT + customPalettes.size(); }
|
||||
inline uint32_t colorFromRgbw(byte* rgbw) { return uint32_t((byte(rgbw[3]) << 24) | (byte(rgbw[0]) << 16) | (byte(rgbw[1]) << 8) | (byte(rgbw[2]))); }
|
||||
void hsv2rgb(const CHSV32& hsv, uint32_t& rgb);
|
||||
|
||||
void hsv2rgb_spectrum(const CHSV32& hsv, CRGBW& rgb);
|
||||
void hsv2rgb_spectrum(const CHSV& hsv, CRGB& rgb);
|
||||
void rgb2hsv(const CRGBW& rgb, CHSV32& hsv);
|
||||
CHSV rgb2hsv(const CRGB c);
|
||||
void colorHStoRGB(uint16_t hue, byte sat, byte* rgb);
|
||||
void rgb2hsv(const uint32_t rgb, CHSV32& hsv);
|
||||
inline CHSV rgb2hsv(const CRGB c) { CHSV32 hsv; rgb2hsv((uint32_t((byte(c.r) << 16) | (byte(c.g) << 8) | (byte(c.b)))), hsv); return CHSV(hsv); } // CRGB to hsv
|
||||
void colorKtoRGB(uint16_t kelvin, byte* rgb);
|
||||
void colorCTtoRGB(uint16_t mired, byte* rgb); //white spectrum to rgb
|
||||
void colorXYtoRGB(float x, float y, byte* rgb); // only defined if huesync disabled TODO
|
||||
@@ -149,7 +89,118 @@ static inline uint32_t fast_color_scale(const uint32_t c, const uint8_t scale) {
|
||||
}
|
||||
|
||||
// palettes
|
||||
extern const TProgmemRGBPalette16 PartyColors_gc22 PROGMEM;
|
||||
extern const TProgmemRGBPalette16* const fastledPalettes[];
|
||||
extern const uint8_t* const gGradientPalettes[];
|
||||
#endif
|
||||
|
||||
|
||||
struct CHSV32 { // 32bit HSV color with 16bit hue for more accurate conversions
|
||||
union {
|
||||
struct {
|
||||
uint16_t h; // hue
|
||||
uint8_t s; // saturation
|
||||
uint8_t v; // value
|
||||
};
|
||||
uint32_t hsv32; // 32bit access
|
||||
};
|
||||
inline CHSV32() __attribute__((always_inline)) = default; // default constructor
|
||||
|
||||
// allow construction from hue (ih), saturation (is), and value (iv)
|
||||
inline CHSV32(uint16_t ih, uint8_t is, uint8_t iv) __attribute__((always_inline)) // constructor from 16bit h, s, v
|
||||
: h(ih), s(is), v(iv) {}
|
||||
|
||||
inline CHSV32(uint8_t ih, uint8_t is, uint8_t iv) __attribute__((always_inline)) // constructor from 8bit h, s, v
|
||||
: h((uint16_t)ih << 8), s(is), v(iv) {}
|
||||
|
||||
inline CHSV32(const CHSV& chsv) __attribute__((always_inline)) // constructor from CHSV
|
||||
: h((uint16_t)chsv.h << 8), s(chsv.s), v(chsv.v) {}
|
||||
|
||||
inline operator CHSV() const { return CHSV((uint8_t)(h >> 8), s, v); } // typecast to CHSV
|
||||
|
||||
// construction from a 32bit rgb color (white channel is ignored)
|
||||
inline CHSV32(const CRGBW& rgb) __attribute__((always_inline));
|
||||
|
||||
inline CHSV32& operator= (const CRGBW& rgb) __attribute__((always_inline)); // assignment from 32bit rgb color (white channel is ignored)
|
||||
};
|
||||
|
||||
// CRGBW can be used to manipulate 32bit colors faster. However: if it is passed to functions, it adds overhead compared to a uint32_t color
|
||||
// use with caution and pay attention to flash size. Usually converting a uint32_t to CRGBW to extract r, g, b, w values is slower than using bitshifts
|
||||
// it can be useful to avoid back and forth conversions between uint32_t and fastled CRGB
|
||||
struct CRGBW {
|
||||
union {
|
||||
uint32_t color32; // Access as a 32-bit value (0xWWRRGGBB)
|
||||
struct {
|
||||
uint8_t b;
|
||||
uint8_t g;
|
||||
uint8_t r;
|
||||
uint8_t w;
|
||||
};
|
||||
uint8_t raw[4]; // Access as an array in the order B, G, R, W (matches 32 bit colors)
|
||||
};
|
||||
|
||||
// Default constructor
|
||||
inline CRGBW() __attribute__((always_inline)) = default;
|
||||
|
||||
// Constructor from a 32-bit color (0xWWRRGGBB)
|
||||
constexpr CRGBW(uint32_t color) __attribute__((always_inline)) : color32(color) {}
|
||||
|
||||
// Constructor with r, g, b, w values
|
||||
constexpr CRGBW(uint8_t red, uint8_t green, uint8_t blue, uint8_t white = 0) __attribute__((always_inline)) : b(blue), g(green), r(red), w(white) {}
|
||||
|
||||
// Constructor from CRGB
|
||||
constexpr CRGBW(CRGB rgb) __attribute__((always_inline)) : b(rgb.b), g(rgb.g), r(rgb.r), w(0) {}
|
||||
|
||||
// Constructor from CHSV32
|
||||
inline CRGBW(CHSV32 hsv) __attribute__((always_inline)) { hsv2rgb_rainbow(hsv.h, hsv.s, hsv.v, raw, true); }
|
||||
|
||||
// Constructor from CHSV
|
||||
inline CRGBW(CHSV hsv) __attribute__((always_inline)) { hsv2rgb_rainbow(hsv.h<<8, hsv.s, hsv.v, raw, true); }
|
||||
|
||||
// Access as an array
|
||||
inline const uint8_t& operator[](uint8_t x) const __attribute__((always_inline)) { return raw[x]; }
|
||||
|
||||
// Assignment from 32-bit color
|
||||
inline CRGBW& operator=(uint32_t color) __attribute__((always_inline)) { color32 = color; return *this; }
|
||||
|
||||
// Assignment from CHSV32
|
||||
inline CRGBW& operator=(CHSV32 hsv) __attribute__((always_inline)) { hsv2rgb_rainbow(hsv.h, hsv.s, hsv.v, raw, true); return *this; }
|
||||
|
||||
// Assignment from CHSV
|
||||
inline CRGBW& operator=(CHSV hsv) __attribute__((always_inline)) { hsv2rgb_rainbow(hsv.h<<8, hsv.s, hsv.v, raw, true); return *this; }
|
||||
|
||||
// Assignment from r, g, b, w
|
||||
inline CRGBW& operator=(const CRGB& rgb) __attribute__((always_inline)) { b = rgb.b; g = rgb.g; r = rgb.r; w = 0; return *this; }
|
||||
|
||||
// Conversion operator to uint32_t
|
||||
inline operator uint32_t() const __attribute__((always_inline)) {
|
||||
return color32;
|
||||
}
|
||||
|
||||
// adjust hue: input range is 256 for full color cycle, input can be negative
|
||||
inline void adjust_hue(int hueshift) __attribute__((always_inline)) {
|
||||
CHSV32 hsv = *this;
|
||||
hsv.h += hueshift << 8;
|
||||
hsv2rgb_spectrum(hsv, *this);
|
||||
}
|
||||
|
||||
// get the average of the R, G, B and W values
|
||||
uint8_t getAverageLight() const {
|
||||
return (r + g + b + w) >> 2;
|
||||
}
|
||||
};
|
||||
|
||||
inline CHSV32::CHSV32(const CRGBW& rgb) {
|
||||
rgb2hsv(rgb, *this);
|
||||
}
|
||||
|
||||
inline CHSV32& CHSV32::operator= (const CRGBW& rgb) { // assignment from 32bit rgb color (white channel is ignored)
|
||||
rgb2hsv(rgb, *this);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// explicit hsv2rgb conversions for compatibility
|
||||
inline CRGBW hsv2rgb(const CHSV32& hsv) { return CRGBW(hsv); }
|
||||
inline void hsv2rgb(const CHSV32& hsv, CRGBW& rgb) { rgb = CRGBW(hsv); }
|
||||
inline void hsv2rgb(const CHSV32& hsv, uint32_t& rgb) { rgb = CRGBW(hsv).color32; }
|
||||
|
||||
#endif
|
||||
+76
-22
@@ -15,6 +15,7 @@ constexpr size_t FIXED_PALETTE_COUNT = DYNAMIC_PALETTE_COUNT + FASTLED_PALETTE_C
|
||||
#else
|
||||
#define WLED_MAX_CUSTOM_PALETTES 10 // ESP8266: limit custom palettes to 10
|
||||
#endif
|
||||
#define WLED_MAX_CUSTOM_PALETTE_GAP 20 // max number of empty palette files in a row before stopping to look for more (20 takes 100ms)
|
||||
|
||||
// You can define custom product info from build flags.
|
||||
// This is useful to allow API consumer to identify what type of WLED version
|
||||
@@ -55,32 +56,39 @@ constexpr size_t FIXED_PALETTE_COUNT = DYNAMIC_PALETTE_COUNT + FASTLED_PALETTE_C
|
||||
|
||||
#ifdef ESP8266
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 3
|
||||
#define WLED_MAX_RMT_CHANNELS 0 // ESP8266 does not have RMT nor I2S
|
||||
#define WLED_MAX_I2S_CHANNELS 0
|
||||
#define WLED_MAX_ANALOG_CHANNELS 5
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 3 // no longer used for bus creation but used to distinguish S2/S3 in UI
|
||||
#define WLED_MAX_TIMERS 16 // reduced limit for ESP8266 due to memory constraints
|
||||
#define WLED_PLATFORM_ID 0 // used in UI to distinguish ESP types, needs a proper fix!
|
||||
#else
|
||||
#if !defined(LEDC_CHANNEL_MAX) || !defined(LEDC_SPEED_MODE_MAX)
|
||||
#include "driver/ledc.h" // needed for analog/LEDC channel counts
|
||||
#endif
|
||||
#define WLED_MAX_ANALOG_CHANNELS (LEDC_CHANNEL_MAX*LEDC_SPEED_MODE_MAX)
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32C3) // 2 RMT, 6 LEDC, only has 1 I2S but NPB does not support it ATM
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 2
|
||||
#define WLED_MAX_RMT_CHANNELS 2 // ESP32-C3 has 2 RMT output channels
|
||||
#define WLED_MAX_I2S_CHANNELS 0 // I2S not supported by NPB
|
||||
//#define WLED_MAX_ANALOG_CHANNELS 6
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 4 // no longer used for bus creation but used to distinguish S2/S3 in UI
|
||||
#define WLED_PLATFORM_ID 1 // used in UI to distinguish ESP types, needs a proper fix!
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S2) // 4 RMT, 8 LEDC, only has 1 I2S bus, supported in NPB
|
||||
// the 5th bus (I2S) will prevent Audioreactive usermod from functioning (it is last used though)
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 12 // x4 RMT + x1/x8 I2S0
|
||||
#define WLED_MAX_RMT_CHANNELS 4 // ESP32-S2 has 4 RMT output channels
|
||||
#define WLED_MAX_I2S_CHANNELS 8 // I2S parallel output supported by NPB
|
||||
//#define WLED_MAX_ANALOG_CHANNELS 8
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 4 // no longer used for bus creation but used to distinguish S2/S3 in UI
|
||||
#define WLED_PLATFORM_ID 2 // used in UI to distinguish ESP type in UI
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S3) // 4 RMT, 8 LEDC, has 2 I2S but NPB supports parallel x8 LCD on I2S1
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 12 // x4 RMT + x8 I2S-LCD
|
||||
#define WLED_MAX_RMT_CHANNELS 4 // ESP32-S3 has 4 RMT output channels
|
||||
#define WLED_MAX_I2S_CHANNELS 8 // uses LCD parallel output not I2S
|
||||
//#define WLED_MAX_ANALOG_CHANNELS 8
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 6 // no longer used for bus creation but used to distinguish S2/S3 in UI
|
||||
#define WLED_PLATFORM_ID 3 // used in UI to distinguish ESP type in UI, needs a proper fix!
|
||||
#else
|
||||
// the last digital bus (I2S0) will prevent Audioreactive usermod from functioning
|
||||
#define WLED_MAX_DIGITAL_CHANNELS 16 // x1/x8 I2S1 + x8 RMT
|
||||
#define WLED_MAX_RMT_CHANNELS 8 // ESP32 has 8 RMT output channels
|
||||
#define WLED_MAX_I2S_CHANNELS 8 // I2S parallel output supported by NPB
|
||||
//#define WLED_MAX_ANALOG_CHANNELS 16
|
||||
#define WLED_MIN_VIRTUAL_BUSSES 6 // no longer used for bus creation but used to distinguish S2/S3 in UI
|
||||
#define WLED_PLATFORM_ID 4 // used in UI to distinguish ESP type in UI, needs a proper fix!
|
||||
#endif
|
||||
#define WLED_MAX_TIMERS 64 // maximum number of timers
|
||||
#define WLED_MAX_DIGITAL_CHANNELS (WLED_MAX_RMT_CHANNELS + WLED_MAX_I2S_CHANNELS)
|
||||
#endif
|
||||
// WLED_MAX_BUSSES was used to define the size of busses[] array which is no longer needed
|
||||
// instead it will help determine max number of buses that can be defined at compile time
|
||||
@@ -113,6 +121,8 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#define RELAY_DELAY 50 // delay in ms between switching on relay and sending data to LEDs
|
||||
|
||||
#if defined(ESP8266) || defined(CONFIG_IDF_TARGET_ESP32S2)
|
||||
#define WLED_MAX_COLOR_ORDER_MAPPINGS 5
|
||||
#else
|
||||
@@ -208,6 +218,12 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#define USERMOD_ID_BRIGHTNESS_FOLLOW_SUN 57 //Usermod "usermod_v2_brightness_follow_sun.h"
|
||||
#define USERMOD_ID_USER_FX 58 //Usermod "user_fx"
|
||||
|
||||
//Wifi encryption type
|
||||
#ifdef WLED_ENABLE_WPA_ENTERPRISE
|
||||
#define WIFI_ENCRYPTION_TYPE_PSK 0 //None/WPA/WPA2
|
||||
#define WIFI_ENCRYPTION_TYPE_ENTERPRISE 1 //WPA/WPA2-Enterprise
|
||||
#endif
|
||||
|
||||
//Access point behavior
|
||||
#define AP_BEHAVIOR_BOOT_NO_CONN 0 //Open AP when no connection after boot
|
||||
#define AP_BEHAVIOR_NO_CONN 1 //Open when no connection (either after boot or if connection is lost)
|
||||
@@ -299,7 +315,7 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#define TYPE_UCS8903 26
|
||||
#define TYPE_APA106 27
|
||||
#define TYPE_FW1906 28 //RGB + CW + WW + unused channel (6 channels per IC)
|
||||
#define TYPE_UCS8904 29 //first RGBW digital type (hardcoded in busmanager.cpp, memUsage())
|
||||
#define TYPE_UCS8904 29 //first RGBW digital type (hardcoded in busmanager.cpp)
|
||||
#define TYPE_SK6812_RGBW 30
|
||||
#define TYPE_TM1814 31
|
||||
#define TYPE_WS2805 32 //RGB + WW + CW
|
||||
@@ -441,6 +457,31 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#define ERR_OVERCURRENT 31 // An attached current sensor has measured a current above the threshold (not implemented)
|
||||
#define ERR_UNDERVOLT 32 // An attached voltmeter has measured a voltage below the threshold (not implemented)
|
||||
|
||||
// JSON buffer lock owners
|
||||
#define JSON_LOCK_UNKNOWN 255
|
||||
#define JSON_LOCK_CFG_DES 1
|
||||
#define JSON_LOCK_CFG_SER 2
|
||||
#define JSON_LOCK_CFG_SEC_DES 3
|
||||
#define JSON_LOCK_CFG_SEC_SER 4
|
||||
#define JSON_LOCK_SETTINGS 5
|
||||
#define JSON_LOCK_XML 6
|
||||
#define JSON_LOCK_LEDMAP 7
|
||||
// unused 8
|
||||
#define JSON_LOCK_PRESET_LOAD 9
|
||||
#define JSON_LOCK_PRESET_SAVE 10
|
||||
#define JSON_LOCK_WS_RECEIVE 11
|
||||
#define JSON_LOCK_WS_SEND 12
|
||||
#define JSON_LOCK_IR 13
|
||||
#define JSON_LOCK_SERVER 14
|
||||
#define JSON_LOCK_MQTT 15
|
||||
#define JSON_LOCK_SERIAL 16
|
||||
#define JSON_LOCK_SERVEJSON 17
|
||||
#define JSON_LOCK_NOTIFY 18
|
||||
#define JSON_LOCK_PRESET_NAME 19
|
||||
#define JSON_LOCK_LEDGAP 20
|
||||
#define JSON_LOCK_LEDMAP_ENUM 21
|
||||
#define JSON_LOCK_REMOTE 22
|
||||
|
||||
// Timer mode types
|
||||
#define NL_MODE_SET 0 //After nightlight time elapsed, set to target brightness
|
||||
#define NL_MODE_FADE 1 //Fade to target brightness gradually
|
||||
@@ -459,6 +500,8 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#define SUBPAGE_UM 8
|
||||
#define SUBPAGE_UPDATE 9
|
||||
#define SUBPAGE_2D 10
|
||||
#define SUBPAGE_PINS 11
|
||||
#define SUBPAGE_LAST SUBPAGE_PINS
|
||||
#define SUBPAGE_LOCK 251
|
||||
#define SUBPAGE_PINREQ 252
|
||||
#define SUBPAGE_CSS 253
|
||||
@@ -474,23 +517,28 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#define MAX_LEDS 1536 //can't rely on memory limit to limit this to 1536 LEDs
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S2)
|
||||
#define MAX_LEDS 2048 //due to memory constraints S2
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
#define MAX_LEDS 4096
|
||||
#else
|
||||
#define MAX_LEDS 16384
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// maximum total memory that can be used for bus-buffers and pixel buffers
|
||||
#ifndef MAX_LED_MEMORY
|
||||
#ifdef ESP8266
|
||||
#define MAX_LED_MEMORY 4096
|
||||
#define MAX_LED_MEMORY (8*1024)
|
||||
#else
|
||||
#if defined(ARDUINO_ARCH_ESP32S2)
|
||||
#define MAX_LED_MEMORY 16384
|
||||
#elif defined(ARDUINO_ARCH_ESP32C3)
|
||||
#define MAX_LED_MEMORY 32768
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32S2)
|
||||
#ifndef BOARD_HAS_PSRAM
|
||||
#define MAX_LED_MEMORY (28*1024) // S2 has ~170k of free heap after boot, using 28k is the absolute limit to keep WLED functional
|
||||
#else
|
||||
#define MAX_LED_MEMORY (48*1024) // with PSRAM there is more wiggle room as buffers get moved to PSRAM when needed (prioritize functionality over speed)
|
||||
#endif
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32S3)
|
||||
#define MAX_LED_MEMORY (192*1024) // S3 has ~330k of free heap after boot
|
||||
#elif defined(CONFIG_IDF_TARGET_ESP32C3)
|
||||
#define MAX_LED_MEMORY (100*1024) // C3 has ~240k of free heap after boot, even with 8000 LEDs configured (2D) there is 30k of contiguous heap left
|
||||
#else
|
||||
#define MAX_LED_MEMORY 65536
|
||||
#define MAX_LED_MEMORY (85*1024) // ESP32 has ~160k of free heap after boot and an additional 64k of 32bit access memory that is used for pixel buffers
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
@@ -555,7 +603,7 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#ifdef ESP8266
|
||||
#define JSON_BUFFER_SIZE 10240
|
||||
#else
|
||||
#if defined(ARDUINO_ARCH_ESP32S2)
|
||||
#if defined(CONFIG_IDF_TARGET_ESP32S2)
|
||||
#define JSON_BUFFER_SIZE 24576
|
||||
#else
|
||||
#define JSON_BUFFER_SIZE 32767
|
||||
@@ -611,7 +659,12 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#define DEFAULT_LED_PIN 2 // GPIO2 (D4) on Wemos D1 mini compatible boards, safe to use on any board
|
||||
#endif
|
||||
#else
|
||||
#define DEFAULT_LED_PIN 16 // aligns with GPIO2 (D4) on Wemos D1 mini32 compatible boards (if it is unusable it will be reassigned in WS2812FX::finalizeInit())
|
||||
#if defined(WLED_USE_ETHERNET)
|
||||
#define DEFAULT_LED_PIN 4 // GPIO4 seems to be a "safe bet" for all known ethernet boards (issue #5155)
|
||||
//#warning "Compiling with Ethernet support. The default LED pin has been changed to pin 4."
|
||||
#else
|
||||
#define DEFAULT_LED_PIN 16 // aligns with GPIO2 (D4) on Wemos D1 mini32 compatible boards (if it is unusable it will be reassigned in WS2812FX::finalizeInit())
|
||||
#endif
|
||||
#endif
|
||||
#define DEFAULT_LED_TYPE TYPE_WS2812_RGB
|
||||
#define DEFAULT_LED_COUNT 30
|
||||
@@ -685,5 +738,6 @@ static_assert(WLED_MAX_BUSSES <= 32, "WLED_MAX_BUSSES exceeds hard limit");
|
||||
#endif
|
||||
|
||||
#define WLED_O2_ATTR __attribute__((optimize("O2")))
|
||||
#define WLED_O3_ATTR __attribute__((optimize("O3")))
|
||||
|
||||
#endif
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta content='width=device-width' name='viewport'>
|
||||
|
||||
+21
-7
@@ -90,7 +90,7 @@ function loadJS(FILE_URL, async = true, preGetV = undefined, postGetV = undefine
|
||||
scE.setAttribute("type", "text/javascript");
|
||||
scE.setAttribute("async", async);
|
||||
d.body.appendChild(scE);
|
||||
// success event
|
||||
// success event
|
||||
scE.addEventListener("load", () => {
|
||||
//console.log("File loaded");
|
||||
if (preGetV) preGetV();
|
||||
@@ -126,6 +126,10 @@ function getLoc() {
|
||||
}
|
||||
}
|
||||
function getURL(path) { return (loc ? locproto + "//" + locip : "") + path; }
|
||||
// HTML entity escaper – use on any remote/user-supplied text inserted into innerHTML
|
||||
function esc(s) { return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
||||
// URL sanitizer – blocks javascript: and data: URIs, use for externally supplied URLs for some basic safety
|
||||
function safeUrl(u) { return /^https?:\/\//.test(u) ? u : '#'; }
|
||||
function B() { window.open(getURL("/settings"),"_self"); }
|
||||
var timeout;
|
||||
function showToast(text, error = false) {
|
||||
@@ -137,16 +141,26 @@ function showToast(text, error = false) {
|
||||
x.style.animation = 'none';
|
||||
timeout = setTimeout(function(){ x.className = x.className.replace("show", ""); }, 2900);
|
||||
}
|
||||
function uploadFile(fileObj, name) {
|
||||
async function uploadFile(fileObj, name, callback) {
|
||||
let file = fileObj.files?.[0]; // get first file, "?"" = optional chaining in case no file is selected
|
||||
if (!file) { callback?.(false); return; }
|
||||
if (/\.json$/i.test(name)) { // same as name.toLowerCase().endsWith('.json')
|
||||
try {
|
||||
const minified = JSON.stringify(JSON.parse(await file.text())); // validate and minify JSON
|
||||
file = new Blob([minified], { type: file.type || "application/json" });
|
||||
} catch (err) {
|
||||
if (!confirm("JSON invalid. Continue?")) { callback?.(false); return; }
|
||||
// proceed with original file if invalid but user confirms
|
||||
}
|
||||
}
|
||||
var req = new XMLHttpRequest();
|
||||
req.addEventListener('load', function(){showToast(this.responseText,this.status >= 400)});
|
||||
req.addEventListener('error', function(e){showToast(e.stack,true);});
|
||||
req.addEventListener('load', function(){showToast(this.responseText,this.status >= 400); if(callback) callback(this.status < 400);});
|
||||
req.addEventListener('error', function(e){showToast("Upload failed",true); if(callback) callback(false);});
|
||||
req.open("POST", "/upload");
|
||||
var formData = new FormData();
|
||||
formData.append("data", fileObj.files[0], name);
|
||||
formData.append("data", file, name);
|
||||
req.send(formData);
|
||||
fileObj.value = '';
|
||||
return false;
|
||||
}
|
||||
// connect to WebSocket, use parent WS or open new, callback function gets passed the new WS object
|
||||
function connectWs(onOpen) {
|
||||
@@ -187,7 +201,7 @@ function sendDDP(ws, start, len, colors) {
|
||||
pkt[0] = 0x02; // DDP protocol indicator for WLED websocket. Note: below DDP protocol bytes are offset by 1
|
||||
pkt[1] = 0x40; // flags: 0x40 = no push, 0x41 = push (i.e. render), note: this is DDP protocol byte 0
|
||||
pkt[2] = 0x00; // reserved
|
||||
pkt[3] = 0x01; // 1 = RGB (currently only supported mode)
|
||||
pkt[3] = 0x0B; // RGB, 8bit per channel
|
||||
pkt[4] = 0x01; // destination id (not used but 0x01 is default output)
|
||||
pkt[5] = (off >> 24) & 255; // DDP protocol 4-7 is offset
|
||||
pkt[6] = (off >> 16) & 255;
|
||||
|
||||
+890
-641
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html><head><meta content='width=device-width' name='viewport'>
|
||||
<html lang="en"><head><meta content='width=device-width' name='viewport'>
|
||||
<title>DMX Map</title>
|
||||
<script>function B(){window.history.back()};function RS(){window.location = "/settings";}function RP(){top.location.href="/";}function FM() {
|
||||
var dmxlabels = ["SET 0","RED","GREEN","BLUE","WHITE","SHUTTER","SET 255", "DISABLED"];
|
||||
|
||||
+42
-25
@@ -5,12 +5,6 @@
|
||||
<meta name="author" content="DedeHai, based on editor by Me-No-Dev">
|
||||
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"><!-- prevent too much scaling on mobile -->
|
||||
<link rel="shortcut icon" href="favicon.ico">
|
||||
<link href="style.css" rel="stylesheet">
|
||||
<!-- Optional lightweight JSON editor - fallback to textarea if CDN is unavailable -->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.4/ace.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.4/mode-json.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.4/theme-monokai.min.js"></script>
|
||||
<script src="common.js"></script>
|
||||
<style>
|
||||
/* Editor-specific styles */
|
||||
body {
|
||||
@@ -113,6 +107,34 @@ body {
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
</style>
|
||||
<script>
|
||||
// load common.js with retry on error, then load Ace editor from CDN with retries, then load style.css
|
||||
function loadFiles(u, r, cb) {
|
||||
var s = document.createElement('script'),
|
||||
// set 1s timeout if retry count is less than 10 (i.e. for Ace scripts)
|
||||
tm = r < 10 ? setTimeout(() => { s.onload=s.onerror=null; cb(); }, 1000) : 0;
|
||||
s.src = u;
|
||||
s.onload = () => { clearTimeout(tm); cb(); };
|
||||
s.onerror = () => {
|
||||
clearTimeout(tm);
|
||||
if (r !== 0) setTimeout(() => loadFiles(u, r < 0 ? r : r - 1, cb), 100); // if r is -1 or > 0 try again
|
||||
else cb();
|
||||
};
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
loadFiles('common.js', -1, () => {
|
||||
const cdn = "https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.4/";
|
||||
// load external scripts in sequence (3 retries each)
|
||||
loadFiles(cdn + 'ace.min.js', 3, () => {
|
||||
loadFiles(cdn + 'mode-json.min.js', 3, () => {
|
||||
loadFiles(cdn + 'theme-monokai.min.js', 3, () => {
|
||||
// all scripts loaded (or skipped) load style.css
|
||||
if (window.loadResources) loadResources(['style.css'], S);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
var QueuedRequester = function(){ this.q=[]; this.r=false; this.x=null; }
|
||||
QueuedRequester.prototype = {
|
||||
_request: function(req){
|
||||
@@ -411,7 +433,7 @@ function createEditor(element,file){
|
||||
// Check filename from text field or current file
|
||||
var pathField = gId("filepath");
|
||||
var filename = (pathField && pathField.value) ? pathField.value : currentFile;
|
||||
aceEditor.session.setMode(filename && filename.toLowerCase().endsWith('.json') ? "ace/mode/json" : "ace/mode/text");
|
||||
aceEditor.session.setMode(filename && (/\.json$/i.test(filename)) ? "ace/mode/json" : "ace/mode/text"); // same as filename.toLowerCase().endsWith('.json')
|
||||
}
|
||||
|
||||
// Try to initialize Ace editor if available
|
||||
@@ -467,7 +489,7 @@ function createEditor(element,file){
|
||||
var filename = pathField ? pathField.value : currentFile;
|
||||
var border = "2px solid #333";
|
||||
|
||||
if (filename && filename.toLowerCase().endsWith('.json')) {
|
||||
if (filename && (/\.json$/i.test(filename))) { // same as filename.toLowerCase().endsWith('.json')
|
||||
try {
|
||||
JSON.parse(ta.value);
|
||||
} catch(e) {
|
||||
@@ -478,23 +500,19 @@ function createEditor(element,file){
|
||||
};
|
||||
|
||||
function saveFile(filename,data){
|
||||
var finalData = data;
|
||||
// Minify JSON files before upload
|
||||
if (filename.toLowerCase().endsWith('.json')) {
|
||||
var outdata = data;
|
||||
if (/\.json$/i.test(filename)) { // same as filename.toLowerCase().endsWith('.json')
|
||||
try {
|
||||
finalData = JSON.stringify(JSON.parse(data));
|
||||
outdata = JSON.stringify(JSON.parse(data)); // validate and minify
|
||||
} catch(e) {
|
||||
alert("Invalid JSON! Please fix syntax.");
|
||||
alert("Invalid JSON! Please fix.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
var fd=new FormData();
|
||||
fd.append("file",new Blob([finalData],{type:"text/plain"}),filename);
|
||||
req.add("POST","/upload",fd,function(st,resp){
|
||||
if (st!=200) alert("ERROR "+st+": "+resp);
|
||||
else {
|
||||
showToast("File saved");
|
||||
uploadFile({files: [new Blob([outdata], {type:"text/plain"})]}, filename, function(s) {
|
||||
if(s) {
|
||||
refreshTree();
|
||||
loadFile(filename); // (re)load if saved successfully to update formating or show file content
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -505,9 +523,9 @@ function createEditor(element,file){
|
||||
gId("preview").style.display="none";
|
||||
gId("editor").style.display="flex";
|
||||
if (st==200) {
|
||||
if (filename.toLowerCase().endsWith('.json')) {
|
||||
if ((/\.json$/i.test(filename))) { // same as filename.toLowerCase().endsWith('.json')
|
||||
try {
|
||||
setContent(filename.toLowerCase().includes('ledmap') ? prettyLedmap(resp) : JSON.stringify(JSON.parse(resp), null, 2));
|
||||
setContent(/ledmap/i.test(filename) ? prettyLedmap(resp) : JSON.stringify(JSON.parse(resp), null, 2)); // pretty-print ledmap files (i.e. if file name includes "ledmap" case-insensitive)
|
||||
} catch(e) {
|
||||
setContent(resp);
|
||||
}
|
||||
@@ -534,8 +552,7 @@ function createEditor(element,file){
|
||||
}
|
||||
if (!fn.startsWith("/")) fn = "/" + fn;
|
||||
currentFile = fn; // Update current file
|
||||
saveFile(fn, getContent());
|
||||
loadFile(fn);
|
||||
saveFile(fn, getContent())
|
||||
},
|
||||
loadText:function(fn){
|
||||
currentFile=fn;
|
||||
@@ -558,7 +575,7 @@ function createEditor(element,file){
|
||||
};
|
||||
}
|
||||
|
||||
function onBodyLoad(){
|
||||
function S(){
|
||||
var vars={};
|
||||
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,k,v){
|
||||
vars[decodeURIComponent(k)]=decodeURIComponent(v);
|
||||
@@ -577,7 +594,7 @@ function onBodyLoad(){
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body onload="onBodyLoad()">
|
||||
<body>
|
||||
<div id="toast"></div>
|
||||
<div id="loader"><div class="loader"></div></div>
|
||||
<div id="top"></div>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
To edit the current font, this is the workflow:
|
||||
|
||||
go to https://icomoon.io/
|
||||
In the menu, go to manage projects and import the json file from this folder and load it
|
||||
Add new icons or exchange existing ones: if changing existing one, make sure the unicode stays the same (can be edited before exporting)
|
||||
Go to "Generate SVG & More" and check the size of new icons (clicking on icons brings up the editor) -> scale new icons to match the size of existing ones
|
||||
Go to "Generate font" tab, check unicodes are correct (can use any unicode, range > e900 is "custom range" and now preferred)
|
||||
Download the font package and replace the files in this folder with new files
|
||||
Using an online converter, convert the *.woff font into woff2 format (about half the file size)
|
||||
Using another online converter, convert the woff2 font to base64 encoding for CSS
|
||||
in index.css, replace the font string at the top, keep the "data:font/woff2;charset=utf-8;" and dont use octet-stream (browser compatibility).
|
||||
|
||||
enjoy your new icons in the UI :)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Open *demo.html* to see a list of all the glyphs in your font along with their codes/ligatures.
|
||||
|
||||
To use the generated font in desktop programs, you can install the TTF font. In order to copy the character associated with each icon, refer to the text box at the bottom right corner of each glyph in demo.html. The character inside this text box may be invisible; but it can still be copied. See this guide for more info: https://icomoon.io/#docs/local-fonts
|
||||
To use the generated font in desktop programs, you can install the TTF font. In order to copy the character associated with each icon, refer to the text box at the bottom right corner of each glyph in demo.html. The character inside this text box may be invisible; but it can still be copied. See this guide for more info: https://icomoon.io/docs#install
|
||||
|
||||
You won't need any of the files located under the *demo-files* directory when including the generated font in your own projects.
|
||||
|
||||
|
||||
@@ -147,6 +147,12 @@ p {
|
||||
font-size: 16px;
|
||||
}
|
||||
.fs1 {
|
||||
font-size: 48px;
|
||||
}
|
||||
.fs2 {
|
||||
font-size: 28px;
|
||||
}
|
||||
.fs3 {
|
||||
font-size: 32px;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,45 @@
|
||||
<link rel="stylesheet" href="style.css"></head>
|
||||
<body>
|
||||
<div class="bgc1 clearfix">
|
||||
<h1 class="mhmm mvm"><span class="fgc1">Font Name:</span> wled122 <small class="fgc1">(Glyphs: 23)</small></h1>
|
||||
<h1 class="mhmm mvm"><span class="fgc1">Font Name:</span> wled122 <small class="fgc1">(Glyphs: 25)</small></h1>
|
||||
</div>
|
||||
<div class="clearfix mhl ptl">
|
||||
<h1 class="mvm mtn fgc1">Grid Size: 16</h1>
|
||||
<div class="glyph fs1">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-pixelforge"></span>
|
||||
<span class="mls"> i-pixelforge</span>
|
||||
</div>
|
||||
<fieldset class="fs0 size1of1 clearfix hidden-false">
|
||||
<input type="text" readonly value="e900" class="unit size1of2" />
|
||||
<input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
|
||||
</fieldset>
|
||||
<div class="fs0 bshadow0 clearfix hidden-true">
|
||||
<span class="unit pvs fgc1">liga: </span>
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="clearfix mhl ptl">
|
||||
<h1 class="mvm mtn fgc1">Grid Size: 14</h1>
|
||||
<div class="glyph fs2">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-editor"></span>
|
||||
<span class="mls"> i-editor</span>
|
||||
</div>
|
||||
<fieldset class="fs0 size1of1 clearfix hidden-false">
|
||||
<input type="text" readonly value="e901" class="unit size1of2" />
|
||||
<input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
|
||||
</fieldset>
|
||||
<div class="fs0 bshadow0 clearfix hidden-true">
|
||||
<span class="unit pvs fgc1">liga: </span>
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="clearfix mhl ptl">
|
||||
<h1 class="mvm mtn fgc1">Grid Size: Unknown</h1>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-pattern"></span>
|
||||
<span class="mls"> i-pattern</span>
|
||||
@@ -27,7 +61,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-segments"></span>
|
||||
<span class="mls"> i-segments</span>
|
||||
@@ -41,7 +75,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-sun"></span>
|
||||
<span class="mls"> i-sun</span>
|
||||
@@ -55,7 +89,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-palette"></span>
|
||||
<span class="mls"> i-palette</span>
|
||||
@@ -69,7 +103,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-eye"></span>
|
||||
<span class="mls"> i-eye</span>
|
||||
@@ -83,7 +117,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-speed"></span>
|
||||
<span class="mls"> i-speed</span>
|
||||
@@ -97,7 +131,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-expand"></span>
|
||||
<span class="mls"> i-expand</span>
|
||||
@@ -111,7 +145,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-power"></span>
|
||||
<span class="mls"> i-power</span>
|
||||
@@ -125,7 +159,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-settings"></span>
|
||||
<span class="mls"> i-settings</span>
|
||||
@@ -139,7 +173,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-playlist"></span>
|
||||
<span class="mls"> i-playlist</span>
|
||||
@@ -153,7 +187,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-night"></span>
|
||||
<span class="mls"> i-night</span>
|
||||
@@ -167,7 +201,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-cancel"></span>
|
||||
<span class="mls"> i-cancel</span>
|
||||
@@ -181,7 +215,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-sync"></span>
|
||||
<span class="mls"> i-sync</span>
|
||||
@@ -195,7 +229,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-confirm"></span>
|
||||
<span class="mls"> i-confirm</span>
|
||||
@@ -209,7 +243,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-brightness"></span>
|
||||
<span class="mls"> i-brightness</span>
|
||||
@@ -223,7 +257,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-nodes"></span>
|
||||
<span class="mls"> i-nodes</span>
|
||||
@@ -237,7 +271,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-add"></span>
|
||||
<span class="mls"> i-add</span>
|
||||
@@ -251,7 +285,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-edit"></span>
|
||||
<span class="mls"> i-edit</span>
|
||||
@@ -265,7 +299,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-intensity"></span>
|
||||
<span class="mls"> i-intensity</span>
|
||||
@@ -279,7 +313,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-star"></span>
|
||||
<span class="mls"> i-star</span>
|
||||
@@ -293,7 +327,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-info"></span>
|
||||
<span class="mls"> i-info</span>
|
||||
@@ -307,7 +341,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-del"></span>
|
||||
<span class="mls"> i-del</span>
|
||||
@@ -321,7 +355,7 @@
|
||||
<input type="text" readonly value="" class="liga unitRight" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="glyph fs1">
|
||||
<div class="glyph fs3">
|
||||
<div class="clearfix bshadow0 pbs">
|
||||
<span class="i-presets"></span>
|
||||
<span class="mls"> i-presets</span>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" standalone="no"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<metadata>Generated by IcoMoon</metadata>
|
||||
<defs>
|
||||
<font id="wled122" horiz-adv-x="1024">
|
||||
<font-face units-per-em="1024" ascent="819.2" descent="-204.8" />
|
||||
<missing-glyph horiz-adv-x="1024" />
|
||||
<glyph unicode=" " horiz-adv-x="0" d="" />
|
||||
<glyph unicode="" glyph-name="del" d="M256 21.333v512h512v-512c0-46.933-38.4-85.333-85.333-85.333h-341.334c-46.933 0-85.333 38.4-85.333 85.333zM810.667 661.333v-85.333h-597.334v85.333h149.334l42.666 42.667h213.334l42.666-42.667h149.334z" />
|
||||
<glyph unicode="" glyph-name="presets" d="M704 704c131.413 0 234.667-103.253 234.667-234.667 0-161.28-145.067-292.693-364.8-491.946l-61.867-56.32-61.867 55.893c-219.733 199.68-364.8 331.093-364.8 492.373 0 131.414 103.254 234.667 234.667 234.667 74.24 0 145.493-34.56 192-89.173 46.507 54.613 117.76 89.173 192 89.173zM516.267 40.533c203.093 183.894 337.066 305.494 337.066 428.8 0 85.334-64 149.334-149.333 149.334-65.707 0-129.707-42.24-151.893-100.694h-79.787c-22.613 58.454-86.613 100.694-152.32 100.694-85.333 0-149.333-64-149.333-149.334 0-123.306 133.973-244.906 337.066-428.8l4.267-4.266z" />
|
||||
<glyph unicode="" glyph-name="info" d="M512 746.667c235.52 0 426.667-191.147 426.667-426.667s-191.147-426.667-426.667-426.667-426.667 191.147-426.667 426.667 191.147 426.667 426.667 426.667zM554.667 106.667v256h-85.334v-256h85.334zM554.667 448v85.333h-85.334v-85.333h85.334z" />
|
||||
<glyph unicode="" glyph-name="power" d="M554.667 704v-426.667h-85.334v426.667h85.334zM760.747 611.413c82.773-70.4 135.253-174.506 135.253-291.413 0-212.053-171.947-384-384-384s-384 171.947-384 384c0 116.907 52.48 221.013 135.253 291.413l60.16-60.16c-66.986-54.613-110.080-137.813-110.080-231.253 0-165.12 133.547-298.667 298.667-298.667s298.667 133.547 298.667 298.667c0 93.44-43.094 176.64-110.507 230.827z" />
|
||||
<glyph unicode="" glyph-name="settings" d="M816.64 280.064l85.504-67.584c8.192-6.144 10.24-16.896 5.12-26.112l-81.92-141.824c-5.12-9.216-15.872-12.8-25.088-9.216l-101.888 40.96c-20.992-15.872-44.032-29.696-69.12-39.936l-15.36-108.544c-1.024-10.24-9.728-17.408-19.968-17.408h-163.84c-10.24 0-18.432 7.168-20.48 17.408l-15.36 108.544c-25.088 10.24-47.616 23.552-69.12 39.936l-101.888-40.96c-9.216-3.072-19.968 0-25.088 9.216l-81.92 141.824c-4.608 8.704-2.56 19.968 5.12 26.112l86.528 67.584c-2.048 12.8-3.072 26.624-3.072 39.936s1.536 27.136 3.584 39.936l-86.528 67.584c-8.192 6.144-10.24 16.896-5.12 26.112l81.92 141.824c5.12 9.216 15.872 12.8 25.088 9.216l101.888-40.96c20.992 15.872 44.032 29.696 69.12 39.936l15.36 108.544c1.536 10.24 9.728 17.408 19.968 17.408h163.84c10.24 0 18.944-7.168 20.48-17.408l15.36-108.544c25.088-10.24 47.616-23.552 69.12-39.936l101.888 40.96c9.216 3.072 19.968 0 25.088-9.216l81.92-141.824c4.608-8.704 2.56-19.968-5.12-26.112l-86.528-67.584c2.048-12.8 3.072-26.112 3.072-39.936s-1.024-27.136-2.56-39.936zM512 166.4c84.48 0 153.6 69.12 153.6 153.6s-69.12 153.6-153.6 153.6-153.6-69.12-153.6-153.6 69.12-153.6 153.6-153.6z" />
|
||||
<glyph unicode="" glyph-name="eye" d="M512 640c213.333 0 395.52-132.693 469.333-320-73.813-187.307-256-320-469.333-320s-395.52 132.693-469.333 320c73.813 187.307 256 320 469.333 320zM512 106.667c117.76 0 213.333 95.573 213.333 213.333s-95.573 213.333-213.333 213.333-213.333-95.573-213.333-213.333 95.573-213.333 213.333-213.333zM512 448c70.827 0 128-57.173 128-128s-57.173-128-128-128-128 57.173-128 128 57.173 128 128 128z" />
|
||||
<glyph unicode="" glyph-name="sync" d="M512 661.333c188.587 0 341.333-152.746 341.333-341.333 0-66.987-19.626-129.28-52.906-181.76l-62.294 62.293c19.2 35.414 29.867 76.374 29.867 119.467 0 141.227-114.773 256-256 256v-128l-170.667 170.667 170.667 170.666v-128zM512 64v128l170.667-170.667-170.667-170.666v128c-188.587 0-341.333 152.746-341.333 341.333 0 66.987 19.626 129.28 52.906 181.76l62.294-62.293c-19.2-35.414-29.867-76.374-29.867-119.467 0-141.227 114.773-256 256-256z" />
|
||||
<glyph unicode="" glyph-name="playlist" d="M556.8 414.293l125.867-94.293-256-192v384zM556.8 414.293l125.867-94.293-256-192v384zM556.8 414.293l-130.133 97.707v-384l256 192zM469.333 658.347c-62.293-7.68-119.040-32.427-166.4-69.12l-60.586 61.013c63.146 51.627 141.226 85.76 226.986 94.293v-86.186zM242.773 529.067c-36.693-47.36-61.44-104.107-69.12-166.4h-86.186c8.533 85.76 42.666 163.84 94.293 226.986zM173.653 277.333c7.68-62.293 32.427-119.040 69.12-165.973l-61.013-61.013c-51.627 63.146-85.76 141.226-94.293 226.986h86.186zM242.347-10.24l60.586 61.013c47.36-36.693 104.107-61.44 166.4-69.12v-86.186c-85.333 8.533-163.84 42.666-226.986 94.293zM938.667 320c0-220.16-167.254-401.92-381.867-424.533v86.186c167.253 22.187 296.533 165.547 296.533 338.347s-129.28 316.16-296.533 338.347v86.186c214.613-22.613 381.867-204.373 381.867-424.533z" />
|
||||
<glyph unicode="" glyph-name="add" d="M810.667 277.333h-256v-256h-85.334v256h-256v85.334h256v256h85.334v-256h256v-85.334z" />
|
||||
<glyph unicode="" glyph-name="nodes" d="M85.333 106.667v42.666h128v-170.666h-128v42.666h85.334v21.334h-42.667v42.666h42.667v21.334h-85.334zM128 490.667v128h-42.667v42.666h85.334v-170.666h-42.667zM85.333 362.667v42.666h128v-38.4l-76.8-89.6h76.8v-42.666h-128v38.4l76.8 89.6h-76.8zM298.667 618.667h597.333v-85.334h-597.333v85.334zM298.667 21.333v85.334h597.333v-85.334h-597.333zM298.667 277.333v85.334h597.333v-85.334h-597.333z" />
|
||||
<glyph unicode="" glyph-name="pattern" d="M511.573 746.667c235.947 0 427.094-191.147 427.094-426.667s-191.147-426.667-427.094-426.667c-235.52 0-426.24 191.147-426.24 426.667s190.72 426.667 426.24 426.667zM512-21.333c188.587 0 341.333 152.746 341.333 341.333s-152.746 341.333-341.333 341.333-341.333-152.746-341.333-341.333 152.746-341.333 341.333-341.333zM661.333 362.667c-35.413 0-64 28.586-64 64s28.587 64 64 64c35.414 0 64-28.587 64-64s-28.586-64-64-64zM362.667 362.667c-35.414 0-64 28.586-64 64s28.586 64 64 64c35.413 0 64-28.587 64-64s-28.587-64-64-64zM512 85.333c-99.413 0-183.893 62.294-218.027 149.334h436.054c-34.134-87.040-118.614-149.334-218.027-149.334z" />
|
||||
<glyph unicode="" glyph-name="night" d="M386.4 738.667c231.104 0 418.667-187.563 418.667-418.667s-187.563-418.667-418.667-418.667c-43.96 0-85.827 6.699-125.6 19.259 169.979 53.171 293.067 211.845 293.067 399.408s-123.088 346.237-293.067 399.408c39.773 12.56 81.64 19.259 125.6 19.259z" />
|
||||
<glyph unicode="" glyph-name="brightness" d="M853.333 461.227l141.227-141.227-141.227-141.227v-200.106h-200.106l-141.227-141.227-141.227 141.227h-200.106v200.106l-141.227 141.227 141.227 141.227v200.106h200.106l141.227 141.227 141.227-141.227h200.106v-200.106zM512 64c141.227 0 256 114.773 256 256s-114.773 256-256 256-256-114.773-256-256 114.773-256 256-256zM512 490.667c94.293 0 170.667-76.374 170.667-170.667s-76.374-170.667-170.667-170.667-170.667 76.374-170.667 170.667 76.374 170.667 170.667 170.667z" />
|
||||
<glyph unicode="" glyph-name="palette" d="M512 704c212.053 0 384-152.747 384-341.333 0-117.76-95.573-213.334-213.333-213.334h-75.52c-35.414 0-64-28.586-64-64 0-16.213 6.4-31.146 16.213-42.24 10.24-11.52 16.64-26.453 16.64-43.093 0-35.413-28.587-64-64-64-212.053 0-384 171.947-384 384s171.947 384 384 384zM277.333 320c35.414 0 64 28.587 64 64s-28.586 64-64 64c-35.413 0-64-28.587-64-64s28.587-64 64-64zM405.333 490.667c35.414 0 64 28.586 64 64s-28.586 64-64 64c-35.413 0-64-28.587-64-64s28.587-64 64-64zM618.667 490.667c35.413 0 64 28.586 64 64s-28.587 64-64 64c-35.414 0-64-28.587-64-64s28.586-64 64-64zM746.667 320c35.413 0 64 28.587 64 64s-28.587 64-64 64c-35.414 0-64-28.587-64-64s28.586-64 64-64z" />
|
||||
<glyph unicode="" glyph-name="edit" d="M128 96l471.893 471.893 160-160-471.893-471.893h-160v160zM883.627 531.627l-78.080-78.080-160 160 78.080 78.080c16.64 16.64 43.52 16.64 60.16 0l99.84-99.84c16.64-16.64 16.64-43.52 0-60.16z" />
|
||||
<glyph unicode="" glyph-name="speed" d="M640 789.333v-85.333h-256v85.333h256zM469.333 234.667v256h85.334v-256h-85.334zM811.947 516.693c52.48-65.706 84.053-148.906 84.053-239.36 0-212.053-171.52-384-384-384s-384 171.947-384 384c0 212.054 171.947 384 384 384 90.453 0 173.653-31.573 239.787-84.48l60.586 60.587c21.76-17.92 41.814-38.4 60.16-60.16zM512-21.333c165.12 0 298.667 133.546 298.667 298.666s-133.547 298.667-298.667 298.667-298.667-133.547-298.667-298.667 133.547-298.666 298.667-298.666z" />
|
||||
<glyph unicode="" glyph-name="sun" d="M288.427 625.493l-60.587-60.16-76.373 76.374 60.16 60.16zM170.667 384v-85.333h-128v85.333h128zM554.667 808.533v-125.866h-85.334v125.866h85.334zM872.533 641.707l-76.373-76.374-60.16 60.16 76.373 76.374zM735.573 57.173l59.734 59.734 76.8-76.374-60.16-60.16zM853.333 384h128v-85.333h-128v85.333zM512 597.333c141.227 0 256-114.773 256-256s-114.773-256-256-256-256 114.774-256 256c0 141.227 114.773 256 256 256zM469.333-125.867v125.867h85.334v-125.867h-85.334zM151.467 40.96l76.373 76.8 60.16-60.16-76.373-76.8z" />
|
||||
<glyph unicode="" glyph-name="segments" d="M511.573 40.96l314.88 244.907 69.547-54.187-384-298.667-384 298.667 69.12 53.76zM512 149.333l-384 298.667 384 298.667 384-298.667-69.973-54.187z" />
|
||||
<glyph unicode="" glyph-name="cancel" d="M512 746.667c235.947 0 426.667-190.72 426.667-426.667s-190.72-426.667-426.667-426.667-426.667 190.72-426.667 426.667 190.72 426.667 426.667 426.667zM725.333 166.827l-153.173 153.173 153.173 153.173-60.16 60.16-153.173-153.173-153.173 153.173-60.16-60.16 153.173-153.173-153.173-153.173 60.16-60.16 153.173 153.173 153.173-153.173z" />
|
||||
<glyph unicode="" glyph-name="confirm" d="M384 142.080l451.84 451.413 60.16-60.16-512-512-238.507 238.507 60.587 60.16z" />
|
||||
<glyph unicode="" glyph-name="expand" d="M707.84 465.493l60.16-60.16-256-256-256 256 60.16 60.16 195.84-195.413z" />
|
||||
<glyph unicode="" glyph-name="intensity" d="M576 803.413c166.827-133.546 277.333-338.773 277.333-568.746 0-188.587-152.746-341.334-341.333-341.334s-341.333 152.747-341.333 341.334c0 144.213 51.626 276.906 137.813 379.306l-1.28-15.36c0-87.893 66.56-159.146 154.88-159.146 87.893 0 145.493 71.253 145.493 159.146 0 91.734-31.573 204.8-31.573 204.8zM499.627 21.333c113.066 0 204.8 91.734 204.8 204.8 0 59.307-8.534 117.334-25.174 172.374-43.52-58.454-121.6-94.72-197.12-110.080-75.093-15.36-119.893-64-119.893-133.12 0-74.24 61.44-133.974 137.387-133.974z" />
|
||||
<glyph unicode="" glyph-name="star" d="M938.667 437.76l-232.534-201.813 69.547-299.947-263.68 159.147-263.68-159.147 69.973 299.947-232.96 201.813 306.774 26.027 119.893 282.88 119.893-282.454zM512 174.933l160.853-97.28-42.666 182.614 141.653 122.88-186.88 16.213-72.96 172.373-72.533-171.946-186.88-16.214 141.653-122.88-42.667-182.613z" />
|
||||
<glyph unicode="" glyph-name="pixelforge" d="M910.398 66.419l-241.236 241.236c-14.934 14.934-39.371 14.934-54.306 0l-18.102-18.102-147.2 147.2 241.646 241.648h-256.001l-113.645-113.645-11.249 11.247h-54.306v-54.306l11.247-11.247-164.848-164.849 127.999-127.999 164.848 164.848 147.2-147.2-18.102-18.102c-14.934-14.934-14.934-39.371 0-54.306l241.236-241.236c14.934-14.934 39.371-14.934 54.306 0l90.509 90.509c14.935 14.934 14.935 39.371 0.002 54.306z" />
|
||||
<glyph unicode="" glyph-name="editor" horiz-adv-x="1074" d="M976.272 266.38c0-11.223-7.016-22.448-14.5-30.867l-157.14-185.202c-27.126-31.802-82.311-57.055-123.469-57.055h-508.837c-16.837 0-40.688 5.146-40.688 26.191 0 11.223 7.016 22.448 14.5 30.867l157.14 185.202c27.126 31.802 82.311 57.055 123.469 57.055h508.837c16.837 0 40.688-5.146 40.688-26.191zM815.856 427.264v-74.828h-389.112c-58.461 0-130.952-33.208-168.835-78.104l-159.949-188.009c0 3.74-0.467 7.951-0.467 11.691v448.977c0 57.523 47.233 104.761 104.761 104.761h149.66c57.523 0 104.761-47.233 104.761-104.761v-14.968h254.418c57.523 0 104.761-47.233 104.761-104.761z" />
|
||||
</font></defs></svg>
|
||||
|
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -1,10 +1,9 @@
|
||||
@font-face {
|
||||
font-family: 'wled122';
|
||||
src:
|
||||
url('fonts/wled122.woff2?e3eban') format('woff2'),
|
||||
url('fonts/wled122.ttf?e3eban') format('truetype'),
|
||||
url('fonts/wled122.woff?e3eban') format('woff'),
|
||||
url('fonts/wled122.svg?e3eban#wled122') format('svg');
|
||||
url('fonts/wled122.ttf?yzxblb') format('truetype'),
|
||||
url('fonts/wled122.woff?yzxblb') format('woff'),
|
||||
url('fonts/wled122.svg?yzxblb#wled122') format('svg');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: block;
|
||||
@@ -25,6 +24,12 @@
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
.i-pixelforge:before {
|
||||
content: "\e900";
|
||||
}
|
||||
.i-editor:before {
|
||||
content: "\e901";
|
||||
}
|
||||
.i-pattern:before {
|
||||
content: "\e23d";
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
@font-face {
|
||||
font-family: "WIcons";
|
||||
src: url(data:font/woff2;charset=utf-8;base64,d09GMgABAAAAAAnUAAsAAAAAE1AAAAmFAAGZmgAAAAAAAAAAAAAAAAAAAAAAAAAABmAAgXwRCAqcYJZIATYCJANwCzoABCAFgwYHIBs7D8iOwzgm3MXMnzZCktnjcbN+QlJLaJ3ulULplpW6UqWioeS91Jye0jUlJwZr5nTdE3LntdPvAg+ft/fbsLsGlNLuhlmQjKi7NPDEIgwTmP//a6mdl+SHUBhEIdHFxak7s4E/yzhJSjC7BQQLfDwopF/i6aqSElEFDXx8ZVWjy3rym4N6FlZQ4hu+nXsGIDMQF3gAxa14AgArtVMhfkgjfEAbiChwuSIwEUCmudPhiQdT6rvIjLSRZEwDhF9BIsooI53TIRIoIUD8kyNZI7UjAyMrR/aM/DwaOpozah9LGCsY2zN2YOzs2L3xqeNp4zXjq8bXT/hMBLj/53YDAIS+7u668n3H+HRPdZd1u3TzdRZdVMTfIl5HfKgd1b7Svqd9W9uprdP8QTOmeaz5TPORJlDDjHVjG0ANMQYsmRrKlmpyqV7kubIQC2GSIkFS+MneCJ48JJFVChQfuwKMp2yU9pmq1VKUR6ret0Gp0SjVYRRF+Xj7+OiUSk/GIzu1miHZWx+g8Y1RUktPmqIitRTXVNzzCtuFPKcH0zRBG+Y9/CnhBa20v5oHfsEUMgXMPEfO5ZcJx0FIPiVywgjb6MIuV+oZ4v2kk6/znIxDKrguM22y+bW8wUGqi7aL8fQJzwnCj8tIppdI9bYDSVJVCQInipW0HbtclcT7vCyLmXaSVrQSNMybaJJBh2PiXrXbgd6AbqecdDTO9EQEIeW0VPWQcdQ8ltPOEu+76q2IxUToJeWpfjQiHHH5AsADLj1bHgQxXsUoHfKYbg+CxCxC69eHcOvWheJ1l6b0nD7jG+bSA1dCZVxmw8ZJ/IYtxPtbJxlpQ/LGjSq00TmdNIZxrGel+y+rZJro+nUh3PrNIGwK6WrXNMV2xTeRWHSjScktLJfe1rc7spyvk3b6V4k48Sr3Am1Pv/QifhsI2uMvc863OiQQRNoedpPfHnSwcete+aDEE67cKzTgBlQgjpjgTDnJtGnX2qbmXJ6FOBLZ7wsr+JZzYnbjdbkCuEfU0HvlwqbtUgJ7zRXFNJsvSxlwz2WYta4xjri/fsulnnFVPyonpP0RL5oVNKkkfElG4csTDNAsgzC38G7gSKVgSZ7m/cEvKALmxKz//u7h6egHF7MrH4jJp/Zx4q32a8T71xnHVRCGlfFZNttd2FcUaay6e9PkhucyR0oPu1z1z/DB+8wixAFdMU1gnmB4xAw68pwHcWjlFrBnXxLjj63UGgvNGVGAJFzxFw+Womn7MAibVbu6leHRB5sc10fLtbrdr/JqV6Yr+ovwFtRHE7M4zG90qNB6YREoo51kFJabq3NeHVKdef/hsMFFSpt5m8XmJqDDAnR0c418mxmxrQzQuyPnspRwfAYkpthzr7gST1xNSf4WtBMM9DQT19uL+gb47gFLP3cT08F8I4dZxJl41Gsx9WHzLBOHzWjRS9NLCOUBCFQ+uGhB/V7ZzUwKESTmDriJ+UecdD/bFXFMLLsjgiAt4pp7ulpxb2tzE8I8xhyHODBK3SGg6QP12BiP3YMw2rDFtWUDXL+esnv3H9QxqfmbDnbMLjGUFpqqZbnWSg0lhWv9wU35qTHqP9zqUrL7kqKj8YjZzg01pb9+yQ8sXZpYxKGiFJTNsIwwpyR44gEOnV/+ennFdHD/2lQ3uS5y1qzIztXUNPE6odYJ0PqUiWJtgKGKMILY60dxeYynbb+sFKKqNn0Wz2rLtMbBQWPnYtmJa4WqFRob/9mmuycQVv7ifCNvXrlhzgDLDvAGA+8H5xjK948cDet+FaXfS+Lko/Wt+vScqarq6kZTbk4NaKqpObkEEpsac9L1rRNXJgPbrWyDdYje6tBQAztkbYC0wDe4UnNipmnZtInu/ujf6Kf7ve112Huf92Ev/7enB/+nP7pbrPiQJZbi0jCSpoN9UNPTkj7JMwpbWgopAbhtbOWkytAF3K+/qo0SASNW2G2bLfnshpB4a9dmz7/Hx//dc3OXNZ46YRyXUV2dYRsD97qKL79qazu+vSI1vPXT7375bWSGocBofD2eIRzJ0cMC0tenwQ0gfvuSdvd14f1uEooLPE3JJHL6uCd/n5n8d35UOKPn6nhr8kyrV3ad3nz2iTiNL414EnefL/JGLlWZtZWaqoEh4xSjvsGb/6m9raFlsLm4uHkQWlv7T/weZzjHHe7xZiUzpJ5WAWBLDNwRKxwRYnFoXGxcaKxN6DR8BNn2o9Nqmmutvra5TnIjXMBlmIFZ3yPYX3Mt9v5mmHuwYvvxPverL9eSvszXNjUXrkbqcGOVW2bEbDGKi3MLVTWzzWHF54Bu/2rA1qko6l9fFgVbBurfVBWFFlVW1ugxOwcs+8W//FcUZJieLl9WXA8eGL5crB7fhOMyxl8bjQWGjB1bW/ok6Ucqensr7F8H7utsmdqoHmz99rvyeE/Pz7u64mvVXLjyY8v8j5XhZeH3aPX75dpiO5eN/OzwcG7zkflt/sd5e7YcqbOowfRg22R5585at2vXX87W1Y0gQ079497eYT1EkyoEqMYABmHd8QvKGrRG6bJYTDCCZYGEWcm5G1jXM2i54Y9WtiBuklP57YtBZMAWlu2fYzDM7Q+5FmxKS3Oz5jwK6IactbWPowuQgNyHluKlaw9wnbOmtuajo/VSw9FrBSRwMcuUV2ZwFhh6s7hsqriWCsgA2s3nFcri4I7O+asxwxZbtLL03E9bhcR6Yz9mIbF0U96K0xGA7bx9y+l2//73j+H2i0EGd27uAVNI/WhCYuWqIDaYxads0lcVFV+dOlHmBx/qO7c6/uZX0tReUtJQv64y3adAvX6xDezAX/8Wm8Cgh/95O9OxsNCYnsXWQ+7pCz8/NMZ57ZAIGEdTw+ap8V+I3NUVe375wiv+lccqj172X7Yw5gJAUQGYPQ6QyxRfgeC+Qc5WnAMCAHFv6TJtet3pn/83b4YCAIBv35ofpTRyt5PjZEwT8KYAEQK8nFgBcE/yUwn2oqHSBKoEG7KZQLMpjo5uha/PI2yuBWOCTSDZajpqQ68+Za18jgGgYMT8nBhjKcFrKCYF6yKSZRLF5tR5YKhUzzNWM52mBvuPMiL7xPx4UaRgFiJZAVFscZ2HUIhUPcEaH5WWDvvmvdPfl5KaCvO8o1+fFCBb6hvuLz8lMROwfjPN8iar90RCCiRCJr3ugqHf6LqgUYYs5hzvu9tMIOUr/xpvRsNVvdZ/p+mB8n7V2Spo0T+aRhPpNhsNFOqxoE2u0suqTipgx58IJA0AAAA=) format('woff');
|
||||
src: url(data:font/woff2;charset=utf-8;base64,d09GMgABAAAAAAsAAA0AAAAAFlgAAAqqAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP0ZGVE0cGhgGYACEGhEICp08lnkLPgABNgIkA3gEIAWDGweCNhvxEVGUcFI3wBeFsYOmlCFXadeSCl4PGhMTwyMh0q9d2MXuDaeszCMkmT3Abd0Eu2ijAIMUa1IDbaQmRj/wndtnJB+d8BHN/+ZKv+zJJpUCCAsMA5IcArBbtlteAg6ToYi3nPp6KxH97fd9OQgssMYTSymghAPMMODmLNpvv/P8BPzeodosVKppyCRNZE0QEqlTCp0SqP9T4O4gAMzzFuTJg2RPa6/23s/f4IYKREKfr6tTc/cLu7dh2JTwmhJdUiSLQqZVQFvmy6mScazQAwlZ7apjDAOl7l8dYEyN5azo7xRYCTCz7gCAzIa7hoI38uBn9/NfQMIrA5RCyCOfOtya0oEneAKP2+M8AEzujgX5QIQYkXEhC5nk4BVC6f6L4cmN4YazURxLPmVQjD4XkFWhNcfmv38+EMNisJkOyOKfgx6n/2z9efLjZY9fPol6EvJEdaY7I5y1zu3Ok64kl58r7bcprplPfZ+GvELuPwEAiGmvZJPj8ErdT9kXF+1jV7AvsG3seNY31uuFw5m/LLgKwNzGLGd8mO+cfw6A8S5jCsM/9wfEH8iWrJEYBLUxMHfsLJpcHQqzOuDEFhQjM1otoVvVg94O/zMIoCJtI1ACwThSfr8yQL1KvQ5rAApCJOJJKBSl4cdB3IwhcY7A5i3/hNDuIJq7NmfVLJNq2Z1hACMTkEpSDwPzGMtL6Qj7EFl8BemVw4zAppSRHW5ZhSxVZIZwKIDXduoxP57T0cgYeukZbC1afoHHq6/OwUSERJEC0lcLGXjp0QKyd7tOLYzdaXLTFHYixavtddgQ0YyI6xbZbLleW+DKSDGxqrvjTWIRtNNgOF6yGYc0ZhihH0R1vR9WuWn2Q4pkWdcmW0QsbEIYzglYJKxhzbvPBSWhn9uiMsuraZ3jiQ75dBgpD4mW9tgSdSHFzLzEcnLiNDvb59n9lVxzrObWObWDviOG3Dwt5RZCKdLLyl04L0+xvKG6aEG0nJFTM6AcuXROdpzmFJCcH9+uWfmohYxDH0Nxk+nRN4ZT3uJW3O32b9GChl57lSFlYeur0F6s+ve/cC8GeUHLy5CeTZoB7XGeFaxDWspDQ9CBaXdnUZU9hGerGTqIgUtgQxhFauojOOdYXo78csyahwycYlRk/FVxQdrYrQc7r1tJQJv1+Xi5FbW+xPCwj5pLicU1YATAPRM9hVc9RfdxWc2300x9lIgM3K/9xgtYHI8miESYICECeMSQt3EtAdq7jhUlLE2CiYgNqUeZNrzc9nLTTg+EeckP9Kz28vnwTeoolOtCGyF5WOonuVZNPkHX/RKff2/l48rnCUbIfJZad59cYhSwkWPEJUQkRvZrYUMVbAKCS6jB/bp7M2ItABfEMpgBinhBFLgze5jkAlW62xjORdV67XqlRsPsObLU7cI+/4ss97HdGJ2iXMrTFMuRTzAe2SISYd9NlE6rZmS4ahqS+8GKTA7ZuWs9YGQfYGQHdUqbXcy+iQC2aiEDhkdLTkhvpoYOmp6tTc6yvgVbEIGdkoPu2sV275V27N23h7awKFxyUm5n1CGxXfscu7nrlINyF7v00vEyotuwG5If4LpYtazK+s3xmi4bpC2UoPNVnRa9JubCZj3+jg4Zl+iGnds38V2bNqxnXOKcUkYv8Vw1vppL4+lMDDMok9jqbFmxHE1LeYp/Sc6O03odj1droeRpqckiE7Qa4jB+nO5OlVyIymtCtJdACJKcTKe3Kct4DL+2knGWW/gpzKXr191XULH0Ay1NmD9ndUMvJaoqrCq5dStqFaosxPyr8/N902gfWD5BcFtmaqreo8wxq1T1+g6+d8iQDLnRJBeYZP4jf/MEBpHR0Lj1zmvSecXw/+vqjLhyTs+enLSoujoiRy3LDbIhvmtxCTAzTZPZBNzr683+Pi7U/TOZjE+Z8yHfzlQzMbsdS4t1ulIwTTJN6/hj5nBM5GevHDFhfTVob+tnthVHUVyu6o1q8GeQCn5TYowqQ4a0asLK33fsSX2zLCVo473WZ4XPWu/gTUr4n1nSfH38mHmqzKpYCucxNo9yXJO1toU1NYX8GuAm7EXRRVH9ja9f0zCPBxUQoNvXeb64MoLftWmu23d39+9eBU1d+UObPKOkpETCw4F7hvbO3brNG0u0Qnrt6B9fveVI0AIMu+aSkOtc3VrSJG5IwMsAv2Rwvfs6ObS5xyXIGfFGlW5cxjv/b4+s7/gTclsCLce7ZvXo6i3rJxi2P9ln4irW+XW89OtSmD3FBmYRo9jaDUvEEip98Bf1mytr7BaFwmJXXVf/AsfRQx8c8MBdywDCjkgAM7s2GDeXXEdyeRSPy4viEmSqzesYgTclp1nKvv50S/kNN+Me01EF0wbWprFZyoBXWACDKu3Cljz17p1WbIZ7xFwjnWai0bGQqsZQK2xf3jggsrSXIVaxQ5EaS2GoE0/jlHG6deccNaU4PqGWZWrG4+588wUzl9saGzWaiLzKjH1B/XEQ4LgwcYIvPn16iYkW1K9gpBLXayyhAJWUWWu2o4jXaVtbtfzXgfuQTk3DaPbaBw817l7OvamJX0Yz0gPOtn4jx9N79MYQbCTF84i+sxz6kXTj3MYcbvkx56XzGsMoWng/EOvWrcWLo2/Jki/by8srSCjHsse7du1fBqtFNQfTTAMOYnfw+6srmZgvttlWFUunU+SoXWtJpU4qtduaqVndnxftCHhw2c5Qs43pa9cbRfu0y1Nt5oTN6hPvfS+w6LgjvexcaoGJZO76IeYh02unz5FWVjqiKer9q78ieyU0Da60eLSoAM296/BJHbMKCIXs4Xs17vLgTs35ikkIrh9BLc4dTXAxNvU5UvV1Vb7bhkO4BhD/9lGHO+/fn4NjlwtHhQO8BSSK5a9HRtGUqfZwnbmeTb2rTbpb764lHTY8Ydt87VtQbHW9UlkZn5WaPRqobxB3qLN+/cb18J+f+dNROn5AISbO1lVAbseul2ewdd4vjwdVkzC2L02fKWdJE3fnxAH7JhVtSF4/EDxhQNoukP0c++bTOk5j6JfTPn6EbndfYOD6FcsJIgKUob1Inz6u5zRZLPsWD0IB4t4DWzCg1XLY/wIGg30NHTTauPsJKVtSOtJ9O2/rYgfF03zzHqybNYqD/yx4tforP6Ld9vAr2ybl/3yIRTcdrwzuetFFSSMAH0LMxI2+fkDdCcDYJyA3ipitETmBOLi8EZmJSOpOPFq/DTxMGhrE3JLs83kymayp5Uh8Ms2xDiHtOJqBLNjEdz8eyLwgrYDkpX6syTp5sNVEYdFEZesHeyLOS68ey57lZy682pmLOqOJ4wcS2GwSmTfZWPLgMWbCdumm7N32YP5QDH110k4bAfiCL0Df065NIHyl/q626c2Y16wHeIviHYE4G+iT5oGtK/bUXlddcGyeJwQBPKxxgIKM7PhKE0/2uuQ+juqSmmzG3PDQFXfqjwMpWpmyPLpjTQbA8zda3OddU9za9W/xDBTYht7SfiikklBMEosFGw5ceGBX1J+TRABBhBBGBFHEEIeCD40EkkghjYx77NI+y02QY4JeWJYom4tVXCrlMg1XCDMwWSeBQMpFORkyRSehUM1EmQphXMqVogyVtJNIKOEiERcruUyTmZOVJOkkzsrJEGRl5WR5AgA=);
|
||||
}
|
||||
|
||||
:root {
|
||||
@@ -94,6 +94,11 @@ button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.iconlabel{
|
||||
font-size:12px;
|
||||
margin-top:2px;
|
||||
}
|
||||
|
||||
.labels {
|
||||
margin: 0;
|
||||
padding: 8px 0 2px 0;
|
||||
|
||||
+24
-7
@@ -10,7 +10,7 @@
|
||||
<title>WLED</title>
|
||||
<link rel="stylesheet" href="index.css">
|
||||
</head>
|
||||
<body onload="onLoad()">
|
||||
<body>
|
||||
|
||||
<div id="cv" class="overlay">Loading WLED UI...</div>
|
||||
<noscript><div class="overlay" style="opacity:1;">Sorry, WLED UI needs JavaScript!</div></noscript>
|
||||
@@ -126,12 +126,28 @@
|
||||
<input id="hexc" title="Hex RGB" type="text" class="noslide" onkeydown="hexEnter()" autocomplete="off" maxlength="8" />
|
||||
<button id="hexcnf" class="btn btn-xs" onclick="fromHex();"><i class="icons btn-icon"></i></button>
|
||||
</div>
|
||||
<div style="padding: 8px 0;" id="btns">
|
||||
<button class="btn btn-xs" title="File editor" type="button" id="edit" onclick="window.location.href=getURL('/edit')"><i class="icons btn-icon"></i></button>
|
||||
<button class="btn btn-xs" title="PixelForge" type="button" onclick="window.location.href=getURL('/pixelforge.htm')"><i class="icons btn-icon"></i></button>
|
||||
<button class="btn btn-xs" title="Add custom palette" type="button" id="adPal" onclick="window.location.href=getURL('/cpal.htm')"><i class="icons btn-icon"></i></button>
|
||||
<button class="btn btn-xs" title="Remove last custom palette" type="button" id="rmPal" onclick="palettesData=null;localStorage.removeItem('wledPalx');requestJson({rmcpal:true});setTimeout(loadPalettes,250,loadPalettesData);"><i class="icons btn-icon"></i></button>
|
||||
|
||||
<div style="padding: 12px 0; display:flex; justify-content:center; gap:16px;" id="btns">
|
||||
<div>
|
||||
<button class="btn btn-xs" title="File editor" type="button" onclick="window.location.href=getURL('/edit')">
|
||||
<i class="icons btn-icon"></i>
|
||||
</button>
|
||||
<div class="iconlabel">Files</div>
|
||||
</div>
|
||||
<div>
|
||||
<button class="btn btn-xs" title="PixelForge" type="button" onclick="window.location.href=getURL('/pixelforge.htm')">
|
||||
<i class="icons btn-icon"></i>
|
||||
</button>
|
||||
<div class="iconlabel">PixelForge</div>
|
||||
</div>
|
||||
<div>
|
||||
<button class="btn btn-xs" title="Custom palettes" type="button" onclick="window.location.href=getURL('/cpal.htm')">
|
||||
<i class="icons btn-icon"></i>
|
||||
</button>
|
||||
<div class="iconlabel">Palettes</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="labels hd" id="pall"><i class="icons sel-icon" onclick="tglHex()"></i> Color palette</p>
|
||||
<div id="palw" class="il">
|
||||
<div class="staytop fnd">
|
||||
@@ -364,8 +380,9 @@
|
||||
<!--
|
||||
If you want to load iro.js and rangetouch.js as consecutive requests, you can do it like it was done in 0.14.0:
|
||||
https://github.com/wled/WLED/blob/v0.14.0/wled00/data/index.htm
|
||||
A more compact approach is implemented to load iro.js at the beginning of index.js.
|
||||
-->
|
||||
<script src="iro.js"></script>
|
||||
<!-- <script src="iro.js"></script> NOTE: iro.js is loaded at the beginning of index.js -->
|
||||
<script src="rangetouch.js"></script>
|
||||
<script src="index.js"></script>
|
||||
</body>
|
||||
|
||||
+106
-54
@@ -8,6 +8,7 @@ var segLmax = 0; // size (in pixels) of largest selected segment
|
||||
var selectedFx = 0;
|
||||
var selectedPal = 0;
|
||||
var csel = 0; // selected color slot (0-2)
|
||||
var cpick; // iro color picker
|
||||
var currentPreset = -1;
|
||||
var lastUpdate = 0;
|
||||
var segCount = 0, ledCount = 0, lowestUnused = 0, maxSeg = 0, lSeg = 0;
|
||||
@@ -42,16 +43,24 @@ var hol = [
|
||||
[0, 0, 1, 1, "https://images.alphacoders.com/119/1198800.jpg"] // new year
|
||||
];
|
||||
|
||||
var cpick = new iro.ColorPicker("#picker", {
|
||||
width: 260,
|
||||
wheelLightness: false,
|
||||
wheelAngle: 270,
|
||||
wheelDirection: "clockwise",
|
||||
layout: [{
|
||||
component: iro.ui.Wheel,
|
||||
options: {}
|
||||
}]
|
||||
});
|
||||
// load iro.js sequentially to avoid 503 errors, retries until successful
|
||||
(function loadIro() {
|
||||
const l = d.createElement('script');
|
||||
l.src = 'iro.js';
|
||||
l.onload = () => {
|
||||
cpick = new iro.ColorPicker("#picker", {
|
||||
width: 260,
|
||||
wheelLightness: false,
|
||||
wheelAngle: 270,
|
||||
wheelDirection: "clockwise",
|
||||
layout: [{component: iro.ui.Wheel, options: {}}]
|
||||
});
|
||||
d.readyState === 'complete' ? onLoad() : window.addEventListener('load', onLoad);
|
||||
};
|
||||
l.onerror = () => setTimeout(loadIro, 100);
|
||||
document.head.appendChild(l);
|
||||
})();
|
||||
|
||||
|
||||
function handleVisibilityChange() {if (!d.hidden && new Date () - lastUpdate > 3000) requestJson();}
|
||||
function sCol(na, col) {d.documentElement.style.setProperty(na, col);}
|
||||
@@ -301,6 +310,21 @@ function onLoad()
|
||||
sl.addEventListener('touchstart', toggleBubble);
|
||||
sl.addEventListener('touchend', toggleBubble);
|
||||
});
|
||||
// limiter for all number inputs except segment inputs: limit inputs instantly note: segment inputs are special if matrix is enabled, they allow for trailing strips, need a lot of special cases to handle that
|
||||
d.addEventListener("input", function(e) {
|
||||
const t = e.target;
|
||||
if (t.tagName === "INPUT" && t.type === "number" && !(t.id && t.id.startsWith("seg"))) {
|
||||
let val = parseFloat(t.value);
|
||||
const max = parseFloat(t.max);
|
||||
const min = parseFloat(t.min);
|
||||
|
||||
if (!isNaN(val)) {
|
||||
if (val > max) t.value = max;
|
||||
if (val < min) t.value = min;
|
||||
if (t.oninput) t.oninput(); // refresh UI labels
|
||||
}
|
||||
}
|
||||
}, false);
|
||||
}
|
||||
|
||||
function updateTablinks(tabI)
|
||||
@@ -688,7 +712,7 @@ function populateInfo(i)
|
||||
var vcn = "Kuuhaku";
|
||||
if (i.cn) vcn = i.cn;
|
||||
|
||||
cn += `v${i.ver} "${vcn}"<br><br><table>
|
||||
cn += `v${i.ver} <i>"${vcn}"</i>${i.release ? '<br>('+i.release+')' : ''}<br><br><table>
|
||||
${urows}
|
||||
${urows===""?'':'<tr><td colspan=2><hr style="height:1px;border-width:0;color:gray;background-color:gray"></td></tr>'}
|
||||
${i.opt&0x100?inforow("Debug","<button class=\"btn btn-xs\" onclick=\"requestJson({'debug':"+(i.opt&0x0080?"false":"true")+"});\"><i class=\"icons "+(i.opt&0x0080?"on":"off")+"\"></i></button>"):''}
|
||||
@@ -698,13 +722,17 @@ ${inforow("Uptime",getRuntimeStr(i.uptime))}
|
||||
${inforow("Time",i.time)}
|
||||
${inforow("Free heap",(i.freeheap/1024).toFixed(1)," kB")}
|
||||
${i.psram?inforow("Free PSRAM",(i.psram/1024).toFixed(1)," kB"):""}
|
||||
<tr><td colspan=2><hr class="sml"></td></tr>
|
||||
${i.leds.count?inforow("Total LEDs",i.leds.count):""}
|
||||
${inforow("Estimated current",pwru)}
|
||||
${inforow("Average FPS",i.leds.fps)}
|
||||
<tr><td colspan=2><hr class="sml"></td></tr>
|
||||
${inforow("MAC address",i.mac)}
|
||||
${inforow("CPU clock",i.clock," MHz")}
|
||||
${inforow("Flash size",i.flash," MB")}
|
||||
${inforow("Filesystem",i.fs.u + "/" + i.fs.t + " kB (" +Math.round(i.fs.u*100/i.fs.t) + "%)")}
|
||||
${inforow("Environment",i.arch + " " + i.core + " (" + i.lwip + ")")}
|
||||
${inforow("Environment",i.arch + " " + i.core + ( i.lwip ? " (" + i.lwip + ")" : ""))}
|
||||
${i.repo?inforow("GitHub","<a href=\"https://github.com/"+i.repo+"\" target=\"_blank\" rel=\"noopener noreferrer\">" + i.repo + "</a>"):""}
|
||||
</table>`;
|
||||
gId('kv').innerHTML = cn;
|
||||
// update all sliders in Info
|
||||
@@ -785,6 +813,7 @@ function populateSegments(s)
|
||||
`<option value="13" ${inst.bm==13?' selected':''}>Soft Light</option>`+
|
||||
`<option value="14" ${inst.bm==14?' selected':''}>Dodge</option>`+
|
||||
`<option value="15" ${inst.bm==15?' selected':''}>Burn</option>`+
|
||||
`<option value="16" ${inst.bm==16?' selected':''}>Stencil</option>`+
|
||||
`</select></div>`+
|
||||
`</div>`;
|
||||
let sndSim = `<div data-snd="si" class="lbl-s hide">Sound sim<br>`+
|
||||
@@ -972,8 +1001,6 @@ function populatePalettes()
|
||||
);
|
||||
}
|
||||
}
|
||||
if (li.cpalcount>0) gId("rmPal").classList.remove("hide");
|
||||
else gId("rmPal").classList.add("hide");
|
||||
}
|
||||
|
||||
function redrawPalPrev()
|
||||
@@ -1056,6 +1083,11 @@ function btype(b)
|
||||
case 34: return "ESP32-S3";
|
||||
case 5:
|
||||
case 35: return "ESP32-C3";
|
||||
case 39: return "ESP32-C6";
|
||||
case 40: return "ESP32-C61";
|
||||
case 41: return "ESP32-C5";
|
||||
case 42:
|
||||
case 43: return "ESP32-P4";
|
||||
case 1:
|
||||
case 82: return "ESP8266";
|
||||
}
|
||||
@@ -1150,7 +1182,7 @@ function updateLen(s)
|
||||
let mySD = gId("mkSYD");
|
||||
if (isM) {
|
||||
// do we have 1D segment *after* the matrix?
|
||||
if (start >= mw*mh) {
|
||||
if (start >= mw*mh && s > 0) {
|
||||
if (sY) { sY.value = 0; sY.max = 0; sY.min = 0; }
|
||||
if (eY) { eY.value = 1; eY.max = 1; eY.min = 0; }
|
||||
sX.min = mw*mh; sX.max = ledCount-1;
|
||||
@@ -1645,14 +1677,10 @@ function setEffectParameters(idx)
|
||||
paOnOff[0] = paOnOff[0].substring(0,dPos);
|
||||
}
|
||||
if (paOnOff.length>0 && paOnOff[0] != "!") text = paOnOff[0];
|
||||
gId("adPal").classList.remove("hide");
|
||||
if (lastinfo.cpalcount>0) gId("rmPal").classList.remove("hide");
|
||||
} else {
|
||||
// disable palette list
|
||||
text += ' not used';
|
||||
palw.style.display = "none";
|
||||
gId("adPal").classList.add("hide");
|
||||
gId("rmPal").classList.add("hide");
|
||||
// Close palette dialog if not available
|
||||
if (palw.lastElementChild.tagName == "DIALOG") {
|
||||
palw.lastElementChild.close();
|
||||
@@ -1943,12 +1971,12 @@ function pleDur(p,i,field)
|
||||
function pleTr(p,i,field)
|
||||
{
|
||||
const du = gId(`pl${p}du${i}`);
|
||||
const dv = parseFloat(du.value);
|
||||
if (dv > 0) {
|
||||
field.max = dv;
|
||||
if (parseFloat(field.value) > dv)
|
||||
field.value = du.value;
|
||||
}
|
||||
const dv = parseFloat(du.value); // duaration value in seconds
|
||||
const max = parseFloat(field.max);
|
||||
let val = parseFloat(field.value);
|
||||
if (isNaN(val)) return;
|
||||
val = Math.min(val, max, dv > 0 ? dv : max); // limit to max or duration, whichever is smaller
|
||||
field.value = val;
|
||||
if (field.validity.valid)
|
||||
plJson[p].transition[i] = Math.floor(field.value*10);
|
||||
}
|
||||
@@ -2104,8 +2132,8 @@ function makePlEntry(p,i)
|
||||
<td class="c">#${i+1}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="c" width="40%"><input class="segn" type="number" placeholder="Duration" max=6553.0 min=0.0 step=0.1 oninput="pleDur(${p},${i},this)" value="${plJson[p].dur[i]/10.0}" id="pl${p}du${i}" ${man?"readonly":""}>s</td>
|
||||
<td class="c" width="40%"><input class="segn" type="number" placeholder="Transition" max=65.0 min=0.0 step=0.1 oninput="pleTr(${p},${i},this)" onfocus="pleTr(${p},${i},this)" value="${plJson[p].transition[i]/10.0}">s</td>
|
||||
<td class="c" width="40%"><input class="segn" type="number" style="width:7ch" placeholder="Duration" max=4294967 min=0.0 step=0.1 oninput="pleDur(${p},${i},this)" value="${plJson[p].dur[i]/10.0}" id="pl${p}du${i}" ${man?"readonly":""}>s</td>
|
||||
<td class="c" width="40%"><input class="segn" type="number" style="width:4ch" placeholder="Transition" max=65.5 min=0.0 step=0.1 oninput="pleTr(${p},${i},this)" onfocus="pleTr(${p},${i},this)" value="${plJson[p].transition[i]/10.0}" id="pl${p}tr${i}">s</td>
|
||||
<td class="c"><button class="btn btn-pl-del" onclick="delPl(${p},${i})"><i class="icons btn-icon"></i></button></div></td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -2309,7 +2337,7 @@ function setSi(s)
|
||||
|
||||
function setBm(s)
|
||||
{
|
||||
var value = gId(`seg${s}bm`).selectedIndex;
|
||||
var value = gId(`seg${s}bm`).value;
|
||||
var obj = {"seg": {"id": s, "bm": value}};
|
||||
requestJson(obj);
|
||||
}
|
||||
@@ -2476,6 +2504,10 @@ function saveP(i,pl)
|
||||
obj.o = true;
|
||||
} else {
|
||||
if (pl) {
|
||||
plJson[i].ps.forEach((_,idx) => {
|
||||
const trField = gId(`pl${i}tr${idx}`);
|
||||
if (trField) pleTr(i, idx, trField); // make sure transition time is not longer than duration
|
||||
});
|
||||
obj.playlist = plJson[i];
|
||||
obj.on = true;
|
||||
obj.o = true;
|
||||
@@ -3290,8 +3322,14 @@ function checkVersionUpgrade(info) {
|
||||
const storedVersion = versionInfo.version || '';
|
||||
|
||||
if (storedVersion && storedVersion !== currentVersion) {
|
||||
// Version has changed, show upgrade prompt
|
||||
showVersionUpgradePrompt(info, storedVersion, currentVersion);
|
||||
// Version has changed
|
||||
if (versionInfo.alwaysReport) {
|
||||
// Automatically report if user opted in for always reporting
|
||||
reportUpgradeEvent(info, storedVersion, true);
|
||||
} else {
|
||||
// Show upgrade prompt
|
||||
showVersionUpgradePrompt(info, storedVersion, currentVersion);
|
||||
}
|
||||
} else if (!storedVersion) {
|
||||
// Empty version in file, show install prompt
|
||||
showVersionUpgradePrompt(info, null, currentVersion);
|
||||
@@ -3301,7 +3339,7 @@ function checkVersionUpgrade(info) {
|
||||
console.log('Failed to load version-info.json', e);
|
||||
// On error, save current version for next time
|
||||
if (info && info.ver) {
|
||||
updateVersionInfo(info.ver, false);
|
||||
updateVersionInfo(info.ver, false, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -3327,7 +3365,7 @@ function showVersionUpgradePrompt(info, oldVersion, newVersion) {
|
||||
? `You are now running WLED <strong style="text-wrap: nowrap">${newVersion}</strong>.`
|
||||
: `Your WLED has been upgraded from <strong style="text-wrap: nowrap">${oldVersion}</strong> to <strong style="text-wrap: nowrap">${newVersion}</strong>.`;
|
||||
|
||||
const question = 'Help make WLED better with a one-time hardware report? It includes only device details like chip type, LED count, etc. — never personal data or your activities.'
|
||||
const question = 'Help make WLED better by sharing hardware details like chip type and LED count? This helps us understand how WLED is used and prioritize features — we never collect personal data or your activities.'
|
||||
|
||||
dialog.innerHTML = `
|
||||
<h2 style="margin-top:0;color:var(--c-f);">${title}</h2>
|
||||
@@ -3336,10 +3374,15 @@ function showVersionUpgradePrompt(info, oldVersion, newVersion) {
|
||||
<p style="color:var(--c-f);font-size:0.9em;">
|
||||
<a href="https://kno.wled.ge/about/privacy-policy/" target="_blank" style="color:var(--c-6);">Learn more about what data is collected and why</a>
|
||||
</p>
|
||||
<div style="margin-top:20px;">
|
||||
<button id="versionReportYes" class="btn">Yes</button>
|
||||
<button id="versionReportNo" class="btn">Not Now</button>
|
||||
<button id="versionReportNever" class="btn">Never Ask</button>
|
||||
<div style="margin-top:15px;margin-bottom:15px;">
|
||||
<label style="display:flex;align-items:center;gap:8px;color:var(--c-f);cursor:pointer;">
|
||||
<input type="checkbox" id="versionSaveChoice" style="cursor:pointer;">
|
||||
<span>Save my choice for future updates</span>
|
||||
</label>
|
||||
</div>
|
||||
<div style="margin-top:20px;display:flex;flex-wrap:wrap;gap:8px;">
|
||||
<button id="versionReportYes" class="btn">Report update</button>
|
||||
<button id="versionReportNo" class="btn">Skip reporting</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -3348,23 +3391,27 @@ function showVersionUpgradePrompt(info, oldVersion, newVersion) {
|
||||
|
||||
// Add event listeners
|
||||
gId('versionReportYes').addEventListener('click', () => {
|
||||
reportUpgradeEvent(info, oldVersion);
|
||||
const saveChoice = gId('versionSaveChoice').checked;
|
||||
d.body.removeChild(overlay);
|
||||
// Pass saveChoice as alwaysReport parameter
|
||||
reportUpgradeEvent(info, oldVersion, saveChoice);
|
||||
});
|
||||
|
||||
gId('versionReportNo').addEventListener('click', () => {
|
||||
// Don't update version, will ask again on next load
|
||||
const saveChoice = gId('versionSaveChoice').checked;
|
||||
d.body.removeChild(overlay);
|
||||
});
|
||||
|
||||
gId('versionReportNever').addEventListener('click', () => {
|
||||
updateVersionInfo(newVersion, true);
|
||||
d.body.removeChild(overlay);
|
||||
showToast('You will not be asked again.');
|
||||
if (saveChoice) {
|
||||
// Save "never ask" preference
|
||||
updateVersionInfo(newVersion, true, false);
|
||||
showToast('You will not be asked again.');
|
||||
} else {
|
||||
// Save current version to prevent re-prompting until version changes
|
||||
updateVersionInfo(newVersion, false, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function reportUpgradeEvent(info, oldVersion) {
|
||||
function reportUpgradeEvent(info, oldVersion, alwaysReport) {
|
||||
showToast('Reporting upgrade...');
|
||||
|
||||
// Fetch fresh data from /json/info endpoint as requested
|
||||
@@ -3391,8 +3438,8 @@ function reportUpgradeEvent(info, oldVersion) {
|
||||
};
|
||||
|
||||
// Add optional fields if available
|
||||
if (infoData.psramPresent !== undefined) upgradeData.psramPresent = infoData.psramPresent; // Whether device has PSRAM
|
||||
if (infoData.psramSize !== undefined) upgradeData.psramSize = infoData.psramSize; // Total PSRAM size in MB
|
||||
if (infoData.psrSz !== undefined) upgradeData.psramSize = infoData.psrSz; // Total PSRAM size in MB; can be 0
|
||||
|
||||
// Note: partitionSizes not currently available in /json/info endpoint
|
||||
|
||||
// Make AJAX call to postUpgradeEvent API
|
||||
@@ -3406,8 +3453,12 @@ function reportUpgradeEvent(info, oldVersion) {
|
||||
})
|
||||
.then(res => {
|
||||
if (res.ok) {
|
||||
showToast('Thank you for reporting!');
|
||||
updateVersionInfo(info.ver, false);
|
||||
if (alwaysReport) {
|
||||
showToast('Thank you! Future upgrades will be reported automatically.');
|
||||
} else {
|
||||
showToast('Thank you for reporting!');
|
||||
}
|
||||
updateVersionInfo(info.ver, false, !!alwaysReport);
|
||||
} else {
|
||||
showToast('Report failed. Please try again later.', true);
|
||||
// Do NOT update version info on failure - user will be prompted again
|
||||
@@ -3415,15 +3466,16 @@ function reportUpgradeEvent(info, oldVersion) {
|
||||
})
|
||||
.catch(e => {
|
||||
console.log('Failed to report upgrade', e);
|
||||
showToast('Report failed. Please try again later.', true);
|
||||
// Do NOT update version info on error - user will be prompted again
|
||||
showToast('Report failed', true);
|
||||
updateVersionInfo(info.ver, false, !!alwaysReport);
|
||||
});
|
||||
}
|
||||
|
||||
function updateVersionInfo(version, neverAsk) {
|
||||
function updateVersionInfo(version, neverAsk, alwaysReport) {
|
||||
const versionInfo = {
|
||||
version: version,
|
||||
neverAsk: neverAsk
|
||||
neverAsk: neverAsk,
|
||||
alwaysReport: !!alwaysReport
|
||||
};
|
||||
|
||||
// Create a Blob with JSON content and use /upload endpoint
|
||||
@@ -3455,4 +3507,4 @@ _C.addEventListener('touchstart', lock, false);
|
||||
|
||||
_C.addEventListener('mouseout', move, false);
|
||||
_C.addEventListener('mouseup', move, false);
|
||||
_C.addEventListener('touchend', move, false);
|
||||
_C.addEventListener('touchend', move, false);
|
||||
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta charset="utf-8">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||||
<meta charset="utf-8">
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta content='width=device-width' name='viewport'>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
|
||||
<meta http-equiv="Pragma" content="no-cache">
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="author" content="@dedehai" />
|
||||
<link rel="shortcut icon" href="favicon.ico">
|
||||
<link rel="stylesheet" href="style.css"> <!-- do not use @import url() for css file, it prevents minifying! -->
|
||||
<title>WLED PixelForge</title>
|
||||
<script src="omggif.js"></script> <!-- TODO: add sequential loading, also addin common.js and optimize code size (getURL() etc.) -->
|
||||
<style>
|
||||
body {
|
||||
max-width: 800px;
|
||||
@@ -25,13 +23,13 @@ h3 {
|
||||
}
|
||||
/* shimmer text animation */
|
||||
.title .sh {
|
||||
background: linear-gradient(90deg,
|
||||
#7b47db 0%, #ff6b6b 20%, #feca57 40%, #48dbfb 60%, #7b47db 100%);
|
||||
background-size: 200% 100%;
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
animation: shimmer 4s ease-in-out 5;
|
||||
font-size: 36px;
|
||||
background: linear-gradient(90deg,
|
||||
#7b47db 0%, #ff6b6b 20%, #feca57 40%, #48dbfb 60%, #7b47db 100%);
|
||||
background-size: 200% 100%;
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
animation: shimmer 4s ease-in-out 5;
|
||||
font-size: 36px;
|
||||
}
|
||||
@keyframes shimmer { 50% { background-position: 600% 0; } }
|
||||
|
||||
@@ -96,7 +94,7 @@ h3 {
|
||||
background: #555;
|
||||
}
|
||||
.cm button.danger {
|
||||
color: #f44;
|
||||
color: #b21;
|
||||
}
|
||||
|
||||
/* Editor styles */
|
||||
@@ -278,11 +276,15 @@ button, .btn {
|
||||
|
||||
<div class="cw">
|
||||
<div style="width:100%">
|
||||
<div class="slc">
|
||||
<label>Rotation: <span id="rotVal">0</span>° <input type="checkbox" id="snap">snap</label>
|
||||
<input type="range" id="rotSl" min="0" max="359" value="0" class="sl">
|
||||
</div>
|
||||
<div class="slc">
|
||||
<label>Zoom: </label>
|
||||
<input type="range" id="zoom" min="0" max="100" value="0" class="sl">
|
||||
</div>
|
||||
<canvas id="cv" width="500" height="400"></canvas>
|
||||
<canvas id="cv" width="500" height="500"></canvas>
|
||||
</div>
|
||||
|
||||
<small>Preview at target resolution</small>
|
||||
@@ -330,30 +332,25 @@ button, .btn {
|
||||
<input type="text" id="txt" placeholder="Enter text" maxlength="64" style="margin-left:15px;flex:1;min-width:300px;">
|
||||
<button class="btn" id="aTxt">✓</button>
|
||||
</div>
|
||||
<small style="display:block;text-align:center;">Preview - actual display may differ</small>
|
||||
<canvas id="tpv" width="100" height="50" style="background:#000;display:block;margin:10px auto;border-radius:8px;width:300px;height:150px;"></canvas>
|
||||
|
||||
<h3>Settings</h3>
|
||||
<div class="cs">
|
||||
<div class="fr">
|
||||
Speed <input type="range" id="sx" min="0" max="255">
|
||||
</div>
|
||||
<div class="fr">
|
||||
Y Offset <input type="range" id="ix" min="0" max="255">
|
||||
</div>
|
||||
<div class="fr">
|
||||
Trail <input type="range" id="c1" min="0" max="255">
|
||||
</div>
|
||||
<div class="fr">
|
||||
Font Size <input type="range" id="c2" min="0" max="255">
|
||||
</div>
|
||||
<div class="fr">
|
||||
Rotate <input type="range" id="c3" min="0" max="31">
|
||||
</div>
|
||||
<div class="fr">Speed <input type="range" id="sx" min="0" max="255"></div>
|
||||
<div class="fr">Y Offset <input type="range" id="ix" min="0" max="255"></div>
|
||||
<div class="fr">Trail <input type="range" id="c1" min="0" max="255" value="0"></div>
|
||||
<div class="fr">Font <input type="range" id="c2" min="3" max="255" step="63"></div>
|
||||
<div class="fr">Rotate <input type="range" id="c3" min="3" max="31" step="7"></div>
|
||||
</div>
|
||||
|
||||
<div class="col" style="display:flex;gap:20px;justify-content:center;">
|
||||
<label style="display:flex;align-items:center;gap:5px">
|
||||
<input type="checkbox" id="o1"> Gradient
|
||||
</label>
|
||||
<label style="display:flex;align-items:center;gap:5px">
|
||||
<input type="checkbox" id="o2"> Custom Font
|
||||
</label>
|
||||
<label style="display:flex;align-items:center;gap:5px">
|
||||
<input type="checkbox" id="o3"> Reverse
|
||||
</label>
|
||||
@@ -379,83 +376,88 @@ button, .btn {
|
||||
<div><a href="#" class="tk" data-t="#DAY">#DAY</a> - Weekday (Mon)</div>
|
||||
<div><a href="#" class="tk" data-t="#DDDD">#DDDD</a> - Weekday (Monday)</div>
|
||||
</div>
|
||||
<div style="margin:10px;padding-top:10px;border-top:1px solid #444">
|
||||
<div style="margin:10px;">
|
||||
<strong>Tips:</strong></small><br>
|
||||
• Mix text and tokens: "It's #HHMM O'Clock" or "#HH:#MM:#SS"<br>
|
||||
• Add '0' suffix for leading zeros: #TIME0, #HH0, etc.
|
||||
</div>
|
||||
<hr>
|
||||
<h3>Custom Fonts</h3>
|
||||
<small>FX uses first 5 fonts only</small><br>
|
||||
<div id="fList" style="display:flex; flex-wrap:wrap; gap:8px; padding:10px; justify-content:center;"></div>
|
||||
<button class="btn sml" id="dcf" style="margin:5px auto; display:block; font-size:11px;">Download Classic WLED Fonts</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="ti1D" style="display:none;">Not available in 1D</div>
|
||||
</div>
|
||||
<div id="oTab" class="tabc">
|
||||
<div class="ed active">
|
||||
<div>
|
||||
<h3>Pixel Paint</h3>
|
||||
<div><small>Interactive painting tool</small></div>
|
||||
<button class="btn" id="t1" style="display:none"></button>
|
||||
</div>
|
||||
<div id="tools">
|
||||
<div style="padding:20px;text-align:center;">Loading tools...</div>
|
||||
</div>
|
||||
<hr>
|
||||
<div class="ed active">
|
||||
<div>
|
||||
<h3>Video Lab</h3>
|
||||
<div><small>Stream video and generate animated GIFs (beta)</small></div>
|
||||
<button class="btn" id="t2" style="display:none"></button>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
<div class="ed active">
|
||||
<div>
|
||||
<h3>PIXEL MAGIC Tool</h3>
|
||||
<div><small>Legacy pixel art editor</small></div>
|
||||
<button class="btn" id="t3" style="display:none"></button>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
</div>
|
||||
|
||||
<div style="margin:20px 0">
|
||||
<button class="btn" onclick="window.location.href=wu">Back to the controls</button>
|
||||
<button class="btn" onclick="window.location.href=getURL('/')">Back to the controls</button>
|
||||
</div>
|
||||
|
||||
<div id="ov"></div>
|
||||
<div id="mem" style="display:none;font-size:12px;color:#aaa;"></div>
|
||||
|
||||
<script>
|
||||
const d=document,gId=i=>d.getElementById(i),cE=t=>d.createElement(t);
|
||||
const imgageFX = 53; // image effect number
|
||||
const txtFX = 122; // scrolling text effect number
|
||||
const getId = (i) => document.getElementById(i); // getId() is defined in common.js, but needed before it is loaded
|
||||
|
||||
/* canvases */
|
||||
const cv=gId('cv'),cx=cv.getContext('2d',{willReadFrequently:true});
|
||||
const pv=gId('pv'),pvx=pv.getContext('2d',{willReadFrequently:true});
|
||||
const cv=getId('cv'),cx=cv.getContext('2d',{willReadFrequently:true});
|
||||
const pv=getId('pv'),pvx=pv.getContext('2d',{willReadFrequently:true});
|
||||
let rv, rvc; // off screen canvas for drawing resized & rotated image (created in init())
|
||||
|
||||
|
||||
/* globals */
|
||||
let wu='',sI=null,sF=null,cI=null,bS=1,iS=1,pX=0,pY=0;
|
||||
let sI=null,sF=null,cI=null,bS=1,iS=1,pX=0,pY=0,rot=0;
|
||||
let cr={x:50,y:50,w:200,h:150},drag=false,dH=null,oX=0,oY=0;
|
||||
let pan=false,psX=0,psY=0,poX=0,poY=0;
|
||||
let iL=[]; // image list
|
||||
let gF=null,gI=null,aT=null;
|
||||
let fL; // file list
|
||||
const classics=['console_font_4x6.wbf','console_font_5x12.wbf','console_font_5x8.wbf','console_font_6x8.wbf','console_font_7x9.wbf']; // classic WLED fonts list
|
||||
let pT = []; // local tools list from JSON
|
||||
let wv = [0, 0]; // wled version [major, minor], updated in fsMem(), used to check tool compatibility
|
||||
const remoteURL = 'https://dedehai.github.io/pftools.json'; // Change to your actual repo
|
||||
const toolsjson = 'pftools.json';
|
||||
// note: the pftools.json must use major.minor for tool versions (e.g. 0.95 or 1.1), otherwise the update check won't work
|
||||
// also the code assumes that the tool url points to a gz file
|
||||
|
||||
// load external resources in sequence to avoid 503 errors if heap is low, repeats indefinitely until loaded
|
||||
(function loadFiles() {
|
||||
const s = document.createElement('script');
|
||||
s.src = 'common.js';
|
||||
s.onerror = () => setTimeout(loadFiles, 100);
|
||||
s.onload = () => {
|
||||
loadResources(['style.css','omggif.js'], init); // load omggif.js then call init()
|
||||
};
|
||||
document.head.appendChild(s);
|
||||
})();
|
||||
|
||||
/* init */
|
||||
(async()=>{
|
||||
const params=new URLSearchParams(window.location.search);
|
||||
wu=`http://${params.get('host')||window.location.host}`;
|
||||
|
||||
await segLoad(); // load available segments
|
||||
async function init() {
|
||||
getLoc();
|
||||
// create off screen canvas
|
||||
rv = cE('canvas');
|
||||
rvc = rv.getContext('2d',{willReadFrequently:true});
|
||||
rv.width = cv.width; rv.height = cv.height;
|
||||
await flU(); // update file list
|
||||
toolChk('pixelpaint.htm','t1'); // update buttons of additional tools
|
||||
toolChk('videolab.htm','t2');
|
||||
toolChk('pxmagic.htm','t3');
|
||||
await fsMem(); // show file system memory info
|
||||
})();
|
||||
tabSw(localStorage.tab||'img'); // switch to last open tab or image tab by default
|
||||
await segLoad(); // load available segments
|
||||
await fsMem(); // update & show file system memory info, also updates wled version (wv)
|
||||
await loadTools(); // load additional tools list from pftools.json
|
||||
}
|
||||
|
||||
/* update file list */
|
||||
async function flU(){
|
||||
try{
|
||||
const r = await fetch(`${wu}/edit?func=list`);
|
||||
const r = await fetch(getURL('/edit?list=/&cb=' + Date.now()));
|
||||
fL = await r.json();
|
||||
}catch(e){console.error(e);}
|
||||
}
|
||||
@@ -467,13 +469,13 @@ function msg(m,t=''){
|
||||
d.body.appendChild(el);setTimeout(()=>el.remove(),3000);
|
||||
}
|
||||
/* "loading" overlay */
|
||||
function ovShow(){gId('ov').classList.add('loading');gId('ov').style.display='block';}
|
||||
function ovHide(){gId('ov').classList.remove('loading');gId('ov').style.display='none';}
|
||||
function ovShow(){getId('ov').classList.add('loading');getId('ov').style.display='block';}
|
||||
function ovHide(){getId('ov').classList.remove('loading');getId('ov').style.display='none';}
|
||||
|
||||
/* segments */
|
||||
function segLoad(){
|
||||
const s1=gId('seg'),v1=s1.value,s2=gId('segT'),v2=s2.value;
|
||||
fetch(`${wu}/json/state`).then(r=>r.json()).then(j=>{
|
||||
const s1=getId('seg'),v1=s1.value,s2=getId('segT'),v2=s2.value;
|
||||
fetch(getURL('/json/state')).then(r=>r.json()).then(j=>{
|
||||
s1.innerHTML=''; s2.innerHTML='';
|
||||
if(j.seg&&j.seg.length){
|
||||
j.seg.forEach(({id,n,start,stop,startY,stopY,fx})=>{
|
||||
@@ -490,14 +492,15 @@ function segLoad(){
|
||||
}
|
||||
if(v1) s1.value=v1; if(v2) s2.value=v2;
|
||||
s2.onchange(); // trigger on load to toggle show/hide of text tool
|
||||
txtSegLoad(); // load settings for currently selected segment
|
||||
const o=s1.options[s1.selectedIndex];
|
||||
if(o){ gId('w').value=o.dataset.w||16; gId('h').value=o.dataset.h||16; }
|
||||
if(o){ getId('w').value=o.dataset.w||16; getId('h').value=o.dataset.h||16; }
|
||||
}).catch(console.error);
|
||||
}
|
||||
|
||||
/* which seg is showing image fx 53 */
|
||||
function curImgSeg(){
|
||||
const sel=gId('seg');
|
||||
const sel=getId('seg');
|
||||
for(let i=0;i<sel.options.length;i++){
|
||||
if(parseInt(sel.options[i].dataset.fx)===imgageFX) return parseInt(sel.options[i].value);
|
||||
}
|
||||
@@ -505,24 +508,25 @@ function curImgSeg(){
|
||||
}
|
||||
|
||||
/* seg change -> update target size */
|
||||
gId('seg').onchange = () =>{
|
||||
const o=gId('seg').selectedOptions[0];
|
||||
gId('w').value=o.dataset.w;
|
||||
gId('h').value=o.dataset.h;
|
||||
getId('seg').onchange = () =>{
|
||||
const o=getId('seg').selectedOptions[0];
|
||||
getId('w').value=o.dataset.w;
|
||||
getId('h').value=o.dataset.h;
|
||||
if(cI) crDraw();
|
||||
};
|
||||
|
||||
gId('segT').onchange = () => {
|
||||
const is2D = (gId('segT').selectedOptions[0].dataset.h || 1) > 1;
|
||||
gId('ti').style.display = is2D ? 'block' : 'none';
|
||||
gId('ti1D').style.display = is2D ? 'none' : 'block';
|
||||
getId('segT').onchange = () => {
|
||||
const is2D = (getId('segT').selectedOptions[0].dataset.h || 1) > 1;
|
||||
getId('ti').style.display = is2D ? 'block' : 'none';
|
||||
getId('ti1D').style.display = is2D ? 'none' : 'block';
|
||||
txtSegLoad(); // update controls to match selected segment
|
||||
};
|
||||
|
||||
/* image list */
|
||||
async function imgLoad(){
|
||||
try{
|
||||
await flU(); // update file list
|
||||
const grid=gId('gr');
|
||||
const grid=getId('gr');
|
||||
const types=['gif','png','jpg','jpeg','bmp'];
|
||||
const imgs=fL.filter(f=>types.includes(f.name.split('.').pop()?.toLowerCase()));
|
||||
const newList=imgs.map(f=>f.name.replace('/',''));
|
||||
@@ -544,11 +548,11 @@ async function imgLoad(){
|
||||
}catch(e){console.error(e);}
|
||||
}
|
||||
|
||||
/* load images into grid TODO: when switching tabs, it can throw 503 and have unloaded images, tried to fix it but all my attempts failed*/
|
||||
/* load images into grid */
|
||||
async function imgLoad2(imgs){
|
||||
const grid=gId('gr');
|
||||
const grid=getId('gr');
|
||||
for(const f of imgs){
|
||||
const name=f.name.replace('/',''),url=`${wu}/${name}`;
|
||||
const name=f.name.replace('/',''),url=getURL(`/${name}`);
|
||||
const isGif=name.toLowerCase().endsWith('.gif');
|
||||
const it=cE('div');it.className='it loading';
|
||||
it.dataset.name=name;it.dataset.url=url;
|
||||
@@ -558,83 +562,168 @@ async function imgLoad2(imgs){
|
||||
await new Promise(res=>{
|
||||
const im=new Image();
|
||||
im.onload=()=>{
|
||||
it.style.backgroundImage=`url(${url}?cb=${Date.now()})`;
|
||||
it.style.backgroundImage=`url('${encodeURI(url)}?cb=${Date.now()}')`;
|
||||
if(!isGif) it.style.border="5px solid red";
|
||||
it.classList.remove('loading'); res();
|
||||
const kb=Math.round(f.size/1024);
|
||||
it.title=`${name}\n${im.width}x${im.height}\n${kb} KB`;
|
||||
};
|
||||
im.onerror=()=>{it.classList.remove('loading');it.style.background='#222';res();};
|
||||
im.src=url+'?cb='+Date.now();
|
||||
im.src=encodeURI(url)+'?cb='+Date.now();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function imgRm(nm){
|
||||
iL=iL.filter(n=>n!==nm);
|
||||
const grid=gId('gr');
|
||||
const grid=getId('gr');
|
||||
grid.querySelectorAll('.it').forEach(it=>{ if(it.dataset.name===nm) it.remove(); });
|
||||
//if(iL.length===0){
|
||||
// grid.innerHTML='<div style="grid-column:1/-1;text-align:center;color:#aaa;padding:20px">No images found</div>';
|
||||
//}
|
||||
}
|
||||
|
||||
/* additional tools: check if present, install if not */
|
||||
function toolChk(file, btnId) {
|
||||
try {
|
||||
const has = fL.some(f => f.name.includes(file));
|
||||
const b = gId(btnId);
|
||||
b.style.display = 'block';
|
||||
b.style.margin = '10px auto';
|
||||
if (has) {
|
||||
b.textContent = 'Open';
|
||||
b.onclick = () => window.open(`${wu}/${file}`, '_blank'); // open tool: remove gz to not trigger download
|
||||
} else {
|
||||
b.textContent = 'Download';
|
||||
b.onclick = async () => {
|
||||
const fileGz = file + '.gz'; // use gz version
|
||||
const url = `https://dedehai.github.io/${fileGz}`; // always download gz version
|
||||
if (!confirm(`Download ${url}?`)) return;
|
||||
try {
|
||||
const f = await fetch(url);
|
||||
if (!f.ok) throw new Error("Download failed " + f.status);
|
||||
const blob = await f.blob(), fd = new FormData();
|
||||
fd.append("data", blob, fileGz);
|
||||
const u = await fetch(wu + "/upload", { method: "POST", body: fd });
|
||||
alert(u.ok ? "Tool installed!" : "Upload failed");
|
||||
await flU(); // update file list
|
||||
toolChk(file, btnId); // re-check and update button (must pass non-gz file name)
|
||||
} catch (e) { alert("Error " + e.message); }
|
||||
};
|
||||
}
|
||||
} catch (e) { console.error(e); }
|
||||
// check for tool compatibility with current wled version (wled_min requirement in pftools.json)
|
||||
function compTool(t) {
|
||||
if (!t.wled_min || !wv) return true;
|
||||
const m = t.wled_min.match(/\d+/g);
|
||||
const a = wv, b = [m[0]|0, m[1]|0];
|
||||
return a[0] > b[0] || (a[0] === b[0] && a[1] >= b[1]);
|
||||
}
|
||||
|
||||
/* fs/mem info */
|
||||
/* additional tools: loaded from pftools.json, store json locally for offline use*/
|
||||
async function loadTools() {
|
||||
try {
|
||||
const res = await fetch(getURL('/' + toolsjson + '?cb=' + Date.now())); // load local tools list
|
||||
pT = res.ok ? await res.json() : [];
|
||||
} catch (e) {}
|
||||
|
||||
renderTools(); // render whatever we have
|
||||
|
||||
try {
|
||||
const rT = await (await fetch(remoteURL + '?cb=' + Date.now())).json();
|
||||
let changed = false;
|
||||
rT.forEach(rt => {
|
||||
let lt = pT.find(t => t.id === rt.id);
|
||||
if (!lt) {
|
||||
pT.push(rt); // new tool available
|
||||
changed = true;
|
||||
} else {
|
||||
// check version
|
||||
if (isNewer(rt.ver, lt.ver)) {
|
||||
lt.pending = rt; // mark update as pending, keep old info until user clicks update button
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
if (changed) {
|
||||
await saveToolsjson(); // save updated json
|
||||
renderTools();
|
||||
}
|
||||
} catch(e){console.error(e);}
|
||||
}
|
||||
|
||||
async function saveToolsjson() {
|
||||
const fd = new FormData();
|
||||
fd.append("data", new Blob([JSON.stringify(pT)], {type:'application/json'}), toolsjson);
|
||||
await fetch(getURL("/upload"), { method: "POST", body: fd });
|
||||
}
|
||||
|
||||
// tool versions must be in format major.minor (e.g. 0.95 or 1.1)
|
||||
function isNewer(vN, vO) {
|
||||
return parseFloat(vN) > parseFloat(vO);
|
||||
}
|
||||
|
||||
function renderTools() {
|
||||
let h = '';
|
||||
pT.forEach(t => {
|
||||
const installed = fL.some(f => f.name.includes(t.file)); // check if tool file exists (either .htm or .htm.gz)
|
||||
const target = (installed && t.pending) ? t.pending : t; // if update pending and tool is installed, show update info
|
||||
const compatible = compTool(target); // check if compatible with current wled version
|
||||
h += `<div class="ed active" style="margin-bottom:10px; border-radius:20px; text-align:left;">
|
||||
<div style="display:flex; justify-content:space-between;">
|
||||
<h3>${esc(t.name)} <small style="font-size:10px">v${esc(t.ver)}</small></h3>
|
||||
${installed ? `<button class="sml" style="height:40px;" onclick="deleteFile('${esc(t.file)}')">✕</button>` : ''}
|
||||
</div>
|
||||
${t.desc}
|
||||
<div style="font-size:10px; color:#888;">
|
||||
by ${esc(t.author)} | <a href="${safeUrl(t.source)}" target="_blank">${safeUrl(t.source)}</a>
|
||||
</div>
|
||||
${
|
||||
compatible ?
|
||||
`<div class="crw">
|
||||
${installed ?
|
||||
`<button class="btn" onclick="window.location.href=getURL('/${esc(t.file)}')">Open</button>`
|
||||
: `<button class="btn" onclick="insT('${esc(t.id)}')">Install</button>`
|
||||
}
|
||||
${t.pending && installed ?
|
||||
`<button class="btn" style="color:#fb2" onclick="insT('${esc(t.id)}')">Update v${esc(t.pending.ver)}</button>`
|
||||
: ''
|
||||
}
|
||||
</div>`
|
||||
: `<div style="color:#f44;font-size:12px;"> Requires WLED ${esc(target.wled_min)} </div>`
|
||||
}
|
||||
</div>`;
|
||||
});
|
||||
getId('tools').innerHTML = h || 'No tools found (offline?).';
|
||||
}
|
||||
|
||||
// install or update tool
|
||||
async function insT(id) {
|
||||
const t = pT.find(x => x.id == id);
|
||||
ovShow();
|
||||
try {
|
||||
const src = t.pending || t;
|
||||
const f = await fetch(src.url); // url in json must be pointing to a gz file
|
||||
if (!f.ok) throw new Error("Download failed " + f.status);
|
||||
const fd = new FormData();
|
||||
fd.append("data", await f.blob(), src.file + '.gz'); // always use gz for file name (source MUST be gz)
|
||||
const u = await fetch(getURL("/upload"), { method: "POST", body: fd });
|
||||
alert(u.ok ? "Tool installed!" : "Install failed");
|
||||
if (u.ok && t.pending) {
|
||||
// save and remove update info after successful update
|
||||
Object.assign(t, t.pending);
|
||||
delete t.pending;
|
||||
}
|
||||
await saveToolsjson();
|
||||
await flU(); // refresh file list
|
||||
renderTools();
|
||||
} catch(e) { alert("Error " + e.message); }
|
||||
fsMem(); // refresh memory info after upload
|
||||
ovHide();
|
||||
}
|
||||
|
||||
/* fs/mem info & wled version */
|
||||
async function fsMem(){
|
||||
try{
|
||||
const r=await fetch(`${wu}/json/info`);
|
||||
const r=await fetch(getURL('/json/info'));
|
||||
const info=await r.json();
|
||||
if(info&&info.fs){
|
||||
gId("mem").textContent=`by @dedehai | Memory: ${info.fs.u} KB / ${info.fs.t} KB`;
|
||||
gId("mem").style.display="block";
|
||||
if (info){
|
||||
if (info.fs) {
|
||||
getId("mem").textContent=`by @dedehai | Memory: ${info.fs.u} KB / ${info.fs.t} KB`;
|
||||
getId("mem").style.display="block";
|
||||
}
|
||||
if (info.ver) {
|
||||
const m = info.ver.match(/\d+/g); // extract all numbers from version string (e.g. "16.1.0-beta" → [16, 1])
|
||||
wv = [parseInt(m[0]) || 0, parseInt(m[1]) || 0];
|
||||
}
|
||||
}
|
||||
}catch(e){console.error(e);}
|
||||
}
|
||||
|
||||
/* drag-drop + file input */
|
||||
gId('drop').onclick=()=>{gId('src').value='';gId('src').click();};
|
||||
gId('drop').ondragover=e=>{e.preventDefault();gId('drop').classList.add('active');};
|
||||
gId('drop').ondragleave=()=>gId('drop').classList.remove('active');
|
||||
gId('drop').ondrop=e=>{e.preventDefault();gId('drop').classList.remove('active');gId('src').files=e.dataTransfer.files;fileHandle();};
|
||||
gId('src').onchange=fileHandle;
|
||||
getId('drop').onclick=()=>{getId('src').value='';getId('src').click();};
|
||||
getId('drop').ondragover=e=>{e.preventDefault();getId('drop').classList.add('active');};
|
||||
getId('drop').ondragleave=()=>getId('drop').classList.remove('active');
|
||||
getId('drop').ondrop=e=>{e.preventDefault();getId('drop').classList.remove('active');getId('src').files=e.dataTransfer.files;fileHandle();};
|
||||
getId('src').onchange=fileHandle;
|
||||
|
||||
/* file handler */
|
||||
function fileHandle() {
|
||||
const file = gId('src').files[0];
|
||||
const file = getId('src').files[0];
|
||||
if (!file) return;
|
||||
sF = file; gI = null; gF = [];
|
||||
gId('sz').style.display = 'block';
|
||||
getId('sz').style.display = 'block';
|
||||
|
||||
const isGif = file.type === 'image/gif';
|
||||
const rdr = new FileReader();
|
||||
@@ -695,9 +784,9 @@ function fileHandle() {
|
||||
function imgShow(src, name) {
|
||||
cI = new Image();
|
||||
cI.onload = () => {
|
||||
gId('ed').classList.add('active');
|
||||
gId('drop').innerHTML = `<p>Image loaded: ${name}<br><small>Drop another to replace</small></p>`;
|
||||
gId('fn').value = name.split('.')[0].substring(0, 16);
|
||||
getId('ed').classList.add('active');
|
||||
getId('drop').innerHTML = `<p>Image loaded: ${name}<br><small>Drop another to replace</small></p>`;
|
||||
getId('fn').value = name.split('.')[0].substring(0, 16);
|
||||
viewReset();
|
||||
cr.w = cv.width * 0.8; cr.h = cv.height * 0.8;
|
||||
cr.x = (cv.width - cr.w) / 2; cr.y = (cv.height - cr.h) / 2;
|
||||
@@ -741,14 +830,14 @@ function unsup(url, name) {
|
||||
const f = new File([b], name, { type: b.type });
|
||||
const dt = new DataTransfer();
|
||||
dt.items.add(f);
|
||||
gId('src').files = dt.files;
|
||||
getId('src').files = dt.files;
|
||||
fileHandle();
|
||||
}).catch(() => msg('Failed to load image', 'err'));
|
||||
}
|
||||
|
||||
/* size change -> redraw */
|
||||
gId('w').oninput=()=>{if(cI)crDraw();};
|
||||
gId('h').oninput=()=>{if(cI)crDraw();};
|
||||
getId('w').oninput=()=>{if(cI)crDraw();};
|
||||
getId('h').oninput=()=>{if(cI)crDraw();};
|
||||
|
||||
/* crop helpers */
|
||||
function crClamp(){
|
||||
@@ -765,37 +854,47 @@ function viewReset(){
|
||||
}
|
||||
|
||||
/* zoom */
|
||||
gId('zoom').oninput=()=>{
|
||||
getId('zoom').oninput=()=>{
|
||||
if(!cI)return;
|
||||
const t=gId('zoom').value/100,ns=bS*Math.pow(40,t);
|
||||
const t=getId('zoom').value/100,ns=bS*Math.pow(40,t);
|
||||
const cxm=cv.width/2,cym=cv.height/2;
|
||||
const dx=cxm-pX,dy=cym-pY,f=ns/iS;
|
||||
pX=cxm-dx*f; pY=cym-dy*f; iS=ns;
|
||||
crClamp(); crDraw();
|
||||
};
|
||||
|
||||
/* rotation */
|
||||
function rotUpd(v){
|
||||
if(getId('snap').checked) v = Math.round(v/15)*15 % 360; // snap to multiples of 15°
|
||||
rot = v;
|
||||
getId('rotVal').textContent = v;
|
||||
if(cI) crDraw();
|
||||
}
|
||||
getId('rotSl').oninput = ()=> rotUpd(+getId('rotSl').value);
|
||||
|
||||
|
||||
/* color change */
|
||||
gId('bg').oninput=crDraw;
|
||||
getId('bg').oninput=crDraw;
|
||||
|
||||
/* quick controls */
|
||||
gId('matchAspect').onclick=e=>{
|
||||
getId('matchAspect').onclick=e=>{
|
||||
e.preventDefault();
|
||||
const r=+gId('w').value/+gId('h').value;
|
||||
const r=+getId('w').value/+getId('h').value;
|
||||
cr.h=cr.w/r; crClamp(); crDraw();
|
||||
};
|
||||
gId('matchSize').onclick=e=>{
|
||||
getId('matchSize').onclick=e=>{
|
||||
e.preventDefault();
|
||||
if(!cI)return;
|
||||
cr.w=+gId('w').value*iS; cr.h=+gId('h').value*iS;
|
||||
cr.w=+getId('w').value*iS; cr.h=+getId('h').value*iS;
|
||||
crClamp(); crDraw();
|
||||
};
|
||||
gId('fullSize').onclick=e=>{
|
||||
getId('fullSize').onclick=e=>{
|
||||
e.preventDefault();
|
||||
if(!cI)return;
|
||||
cr.x=0; cr.y=0; cr.w=cv.width; cr.h=cv.height;
|
||||
crClamp(); crDraw();
|
||||
};
|
||||
gId('resetCrop').onclick=e=>{
|
||||
getId('resetCrop').onclick=e=>{
|
||||
e.preventDefault();
|
||||
if(!cI)return;
|
||||
cr.w=cv.width*0.8; cr.h=cv.height*0.8;
|
||||
@@ -882,23 +981,36 @@ cv.ontouchcancel=e=>{e.preventDefault();actEnd();};
|
||||
|
||||
/* draw + preview */
|
||||
function crDraw(){
|
||||
if(!cI) return;
|
||||
|
||||
// render rotated image to offscreen
|
||||
rvc.clearRect(0,0,rv.width,rv.height);
|
||||
rvc.fillStyle = getId('bg').value;
|
||||
rvc.fillRect(0,0,rv.width,rv.height);
|
||||
rvc.imageSmoothingEnabled = false;
|
||||
rvc.save();
|
||||
const dw = cI.width * iS, dh = cI.height * iS;
|
||||
rvc.translate(pX + dw/2, pY + dh/2);
|
||||
rvc.rotate(rot * Math.PI / 180);
|
||||
rvc.drawImage(cI, -dw/2, -dh/2, dw, dh);
|
||||
rvc.restore();
|
||||
|
||||
// copy offscreen to visible
|
||||
cx.clearRect(0,0,cv.width,cv.height);
|
||||
if(!cI)return;
|
||||
cx.fillStyle=gId('bg').value; cx.fillRect(0,0,cv.width,cv.height);
|
||||
cx.imageSmoothingEnabled=false;
|
||||
cx.drawImage(cI,0,0,cI.width,cI.height,pX,pY,cI.width*iS,cI.height*iS);
|
||||
/* crop frame */
|
||||
cx.drawImage(rv, 0, 0);
|
||||
|
||||
// overlay crop frame (only on visible)
|
||||
cx.lineWidth=3; cx.setLineDash([6,4]); cx.shadowColor="#000"; cx.shadowBlur=2;
|
||||
cx.strokeStyle="#FFF"; cx.beginPath(); cx.roundRect(cr.x,cr.y,cr.w,cr.h,6); cx.stroke();
|
||||
cx.shadowColor="#000F";
|
||||
prevUpd();
|
||||
}
|
||||
|
||||
gId('bt').addEventListener('input',()=>{prevUpd();});
|
||||
getId('bt').addEventListener('input',()=>{prevUpd();});
|
||||
function blackTh(c){
|
||||
let t=+gId('bt').value,
|
||||
let t=+getId('bt').value,
|
||||
dt=c.getImageData(0,0,c.canvas.width,c.canvas.height),
|
||||
b=gId('bg').value.match(/\w\w/g).map(x=>parseInt(x,16));
|
||||
b=getId('bg').value.match(/\w\w/g).map(x=>parseInt(x,16));
|
||||
for(let i=0;i<dt.data.length;i+=4)
|
||||
if(dt.data[i]<t&&dt.data[i+1]<t&&dt.data[i+2]<t)
|
||||
dt.data[i]=b[0],dt.data[i+1]=b[1],dt.data[i+2]=b[2];
|
||||
@@ -907,13 +1019,14 @@ function blackTh(c){
|
||||
|
||||
function prevUpd(){
|
||||
if(!cI)return;
|
||||
let w=+gId('w').value,h=+gId('h').value;
|
||||
let w=+getId('w').value,h=+getId('h').value;
|
||||
// Temporary canvas at target size
|
||||
const tc = cE('canvas'); tc.width = w; tc.height = h;
|
||||
const tcx = tc.getContext('2d');
|
||||
tcx.fillStyle=gId('bg').value;
|
||||
tcx.fillStyle=getId('bg').value;
|
||||
tcx.fillRect(0,0,w,h); // fill background (for transparent images)
|
||||
tcx.drawImage(cI,(cr.x-pX)/iS,(cr.y-pY)/iS,cr.w/iS,cr.h/iS,0,0,w,h);
|
||||
tcx.imageSmoothingEnabled = false;
|
||||
tcx.drawImage(rv, cr.x, cr.y, cr.w, cr.h, 0, 0, w, h); // sample cropped area from off screen canvas
|
||||
blackTh(tcx);
|
||||
// scale/stretch to preview canvas, limit to 256px in largest dimension but keep aspect ratio
|
||||
const ratio = h/w;
|
||||
@@ -986,9 +1099,9 @@ function grid(length) {
|
||||
}
|
||||
|
||||
/* create GIF and upload */
|
||||
gId('up').onclick = async () => {
|
||||
getId('up').onclick = async () => {
|
||||
if (!gF || !gI) return; // no image
|
||||
const w = +gId('w').value, h = +gId('h').value, fn = gId('fn').value.trim() || 'image';
|
||||
const w = +getId('w').value, h = +getId('h').value, fn = getId('fn').value.trim() || 'image';
|
||||
const filename = `${fn}.gif`;
|
||||
const repl = iL.includes(filename);
|
||||
if (repl && !confirm(`${filename} already exists. Overwrite?`)) return;
|
||||
@@ -1003,11 +1116,28 @@ gId('up').onclick = async () => {
|
||||
|
||||
const frames = [];
|
||||
for (let i = 0; i < gF.length; i++) {
|
||||
// put current GIF frame into tc
|
||||
const id = new ImageData(new Uint8ClampedArray(gF[i].pixels), gI.width, gI.height);
|
||||
tctx.putImageData(id, 0, 0);
|
||||
cctx.fillStyle = gId('bg').value;
|
||||
|
||||
// render this frame into the offscreen rotated canvas (no overlay)
|
||||
rvc.clearRect(0, 0, rv.width, rv.height);
|
||||
rvc.fillStyle = getId('bg').value;
|
||||
rvc.fillRect(0, 0, rv.width, rv.height);
|
||||
rvc.imageSmoothingEnabled = false;
|
||||
rvc.save();
|
||||
const dw = gI.width * iS, dh = gI.height * iS;
|
||||
rvc.translate(pX + dw / 2, pY + dh / 2);
|
||||
rvc.rotate(rot * Math.PI / 180);
|
||||
rvc.drawImage(tc, -dw / 2, -dh / 2, dw, dh);
|
||||
rvc.restore();
|
||||
|
||||
// sample the crop from the offscreen (already rotated) canvas into output size
|
||||
cctx.fillStyle = getId('bg').value;
|
||||
cctx.fillRect(0, 0, w, h);
|
||||
cctx.drawImage(tc, (cr.x - pX) / iS, (cr.y - pY) / iS, cr.w / iS, cr.h / iS, 0, 0, w, h);
|
||||
cctx.imageSmoothingEnabled = false;
|
||||
cctx.drawImage(rv, cr.x, cr.y, cr.w, cr.h, 0, 0, w, h);
|
||||
|
||||
blackTh(cctx);
|
||||
const fd = cctx.getImageData(0, 0, w, h);
|
||||
frames.push({ data: fd.data, delay: gF[i].delay });
|
||||
@@ -1036,25 +1166,26 @@ gId('up').onclick = async () => {
|
||||
const fU = new File([new Uint8Array(gifData)], filename, { type: 'image/gif' });
|
||||
const fd = new FormData();
|
||||
fd.append('file', fU, filename);
|
||||
const r = await fetch(`${wu}/upload`, { method: 'POST', body: fd });
|
||||
const r = await fetch(getURL('/upload'), { method: 'POST', body: fd });
|
||||
|
||||
if (r.ok) {
|
||||
msg(`${filename} uploaded`);
|
||||
if (repl) imgRm(filename);
|
||||
await imgLoad();
|
||||
gId('src').value = '';
|
||||
gId('drop').innerHTML = '<p>Drop image or click to select</p>';
|
||||
getId('src').value = '';
|
||||
getId('drop').innerHTML = '<p>Drop image or click to select</p>';
|
||||
} else msg('Upload failed', 'err');
|
||||
} catch (e) {
|
||||
msg(`Error: ${e.message}`, 'err');
|
||||
} finally {
|
||||
fsMem(); // refresh memory info after upload
|
||||
ovHide();
|
||||
}
|
||||
};
|
||||
|
||||
/* play on device */
|
||||
async function imgPlay(url,name){
|
||||
const tgt=+gId('seg').value,cur=curImgSeg();
|
||||
const tgt=+getId('seg').value,cur=curImgSeg();
|
||||
if(cur!==null && cur!==tgt){
|
||||
if(!confirm(`Segment ${cur} is currently displaying an image. Switch image display to segment ${tgt}?`))return;
|
||||
}
|
||||
@@ -1064,9 +1195,9 @@ async function imgPlay(url,name){
|
||||
on:true,
|
||||
seg: cur!==null && cur!==tgt
|
||||
? [{id:cur,fx:0,n:""},{id:tgt,fx:53,frz:false,sx:128,n:name}]
|
||||
: {id:tgt,fx:53,frz:false,sx:128,n:name}
|
||||
: {id:tgt,fx:53,frz:false,sx:128,ix:0,n:name}
|
||||
};
|
||||
const r=await fetch(`${wu}/json/state`,{method:'POST',body:JSON.stringify(j)});
|
||||
const r=await fetch(getURL('/json/state'),{method:'POST',body:JSON.stringify(j)});
|
||||
const out=await r.json();
|
||||
if(out.success){
|
||||
msg(`Playing ${name}`);
|
||||
@@ -1084,7 +1215,7 @@ function menuShow(x,y){
|
||||
m.style.left=x+'px'; m.style.top=y+'px';
|
||||
m.innerHTML=`
|
||||
<button onclick="imgDl()">Download</button>
|
||||
<button class="danger" onclick="imgDel()">Delete</button>`;
|
||||
<button class="danger" onclick="deleteFile(sI.name)">Delete</button>`;
|
||||
d.body.appendChild(m);
|
||||
setTimeout(()=>{
|
||||
const h=e=>{
|
||||
@@ -1104,30 +1235,39 @@ async function imgDl(){
|
||||
}catch(e){msg('Download failed','err');}
|
||||
menuClose();
|
||||
}
|
||||
async function imgDel(){
|
||||
if(!confirm(`Delete ${sI.name}?`))return;
|
||||
|
||||
async function deleteFile(name){
|
||||
name = name.replace('/',''); // remove leading slash if present (just in case)
|
||||
if (fL.some(f => f.name.replace('/','') === `${name}.gz`))
|
||||
name += '.gz'; // if .gz version of file exists, delete that (handles tools which are stored gzipped on device)
|
||||
if(!confirm(`Delete ${name}?`))return;
|
||||
ovShow();
|
||||
try{
|
||||
const r = await fetch(`${wu}/edit?func=delete&path=/${sI.name}`);
|
||||
if(r.ok){ msg('Deleted'); imgRm(sI.name); }
|
||||
const r = await fetch(getURL(`/edit?func=delete&path=/${name}`));
|
||||
if(r.ok){
|
||||
msg('Deleted');
|
||||
imgRm(name); // remove image from grid (if this was not an image, this does nothing)
|
||||
}
|
||||
else msg('Delete failed! File in use?','err');
|
||||
}catch(e){msg('Delete failed','err');}
|
||||
finally{ovHide();}
|
||||
menuClose();
|
||||
fsMem(); // refresh memory info after delete
|
||||
menuClose(); // close menu (used for image delete button)
|
||||
await flU(); // update file list
|
||||
renderTools(); // re-render tools list
|
||||
}
|
||||
|
||||
/* tab select and additional tools */
|
||||
function tabSw(tab) {
|
||||
'iTab,xTab,oTab,tImg,tTxt,tOth'.split(',').forEach((id,i)=>{
|
||||
gId(id).classList.toggle('active', tab===['img','txt','oth'][i%3]);
|
||||
getId(id).classList.toggle('active', tab===['img','txt','oth'][i%3]);
|
||||
});
|
||||
localStorage.tab=tab;
|
||||
({txt:txtSegLoad,img:imgLoad}[tab]||(()=>{}))(); // functions to execute on tab switch (currently none for oth)
|
||||
({txt:()=>{txtSegLoad(); scanFonts();}, img:imgLoad}[tab]||(()=>{}))(); // on tab switch, load images and available fonts
|
||||
}
|
||||
'Img,Txt,Oth'.split(',').forEach((s,i)=>{
|
||||
gId('t'+s).onclick=()=>tabSw(['img','txt','oth'][i]);
|
||||
getId('t'+s).onclick=()=>tabSw(['img','txt','oth'][i]);
|
||||
});
|
||||
tabSw(localStorage.tab||'img');
|
||||
|
||||
/* tokens insert */
|
||||
function txtIns(el,t){
|
||||
@@ -1138,55 +1278,135 @@ function txtIns(el,t){
|
||||
}
|
||||
document.addEventListener('click',e=>{
|
||||
const a=e.target.closest('.tk'); if(!a) return;
|
||||
e.preventDefault(); txtIns(gId('txt'),a.dataset.t);
|
||||
e.preventDefault(); txtIns(getId('txt'),a.dataset.t);
|
||||
// txtUp();
|
||||
});
|
||||
|
||||
/* load seg settings into text UI */
|
||||
async function txtSegLoad(){
|
||||
const id=+gId('segT').value;
|
||||
const id=+getId('segT').value;
|
||||
try{
|
||||
|
||||
const r=await fetch(`${wu}/json/state`),j=await r.json();
|
||||
const r=await fetch(getURL('/json/state')),j=await r.json();
|
||||
if(j.seg&&j.seg[id]){
|
||||
const s=j.seg[id];
|
||||
gId('txt').value=s.n||'';
|
||||
gId('sx').value=s.sx||128;
|
||||
gId('ix').value=s.ix||128;
|
||||
gId('c1').value=s.c1||0;
|
||||
gId('c2').value=s.c2||0;
|
||||
gId('c3').value=s.c3||0;
|
||||
gId('o1').checked=!(!s.o1);
|
||||
gId('o3').checked=!(!s.o3);
|
||||
if(s.fx!==txtFX) return; // only update when this segment uses scrolling text effect
|
||||
getId('txt').value=s.n||'';
|
||||
getId('sx').value=s.sx||128;
|
||||
getId('ix').value=s.ix||128;
|
||||
getId('c1').value=s.c1||0;
|
||||
getId('c2').value=s.c2||128;
|
||||
getId('c3').value=s.c3||16;
|
||||
getId('o1').checked=!(!s.o1);
|
||||
getId('o3').checked=!(!s.o3);
|
||||
}
|
||||
}catch(e){console.error(e);}
|
||||
}
|
||||
|
||||
/* auto apply on change */
|
||||
['sx','ix','c1','c2','c3','o1','o3'].forEach(id=>{ gId(id).onchange=txtUp; });
|
||||
['sx','ix','c1','c2','c3','o1','o2','o3'].forEach(id=>{ getId(id).onchange=txtUp; });
|
||||
|
||||
/* send text settings */
|
||||
function txtUp(){
|
||||
const id=+gId('segT').value,txt=gId('txt').value.trim().slice(0,64);
|
||||
const j={on:true,seg:{id,fx:122,n:txt,sx:+gId('sx').value,ix:+gId('ix').value,c1:+gId('c1').value,c2:+gId('c2').value,c3:+gId('c3').value,o1:gId('o1').checked,o3:gId('o3').checked}};
|
||||
fetch(`${wu}/json/state`,{method:'POST',body:JSON.stringify(j)})
|
||||
const id=+getId('segT').value,txt=getId('txt').value.trim().slice(0,64);
|
||||
const j={on:true,seg:{id,fx:122,n:txt,sx:+getId('sx').value,ix:+getId('ix').value,c1:+getId('c1').value,c2:+getId('c2').value,c3:+getId('c3').value,o1:getId('o1').checked,o2:getId('o2').checked,o3:getId('o3').checked}};
|
||||
fetch(getURL('/json/state'),{method:'POST',body:JSON.stringify(j)})
|
||||
.then(r => { if(r.ok) segLoad(); })
|
||||
.catch(console.error);
|
||||
}
|
||||
|
||||
/* apply button */
|
||||
gId('aTxt').onclick=async()=>{
|
||||
const id=+gId('segT').value,txt=gId('txt').value.trim();
|
||||
getId('aTxt').onclick=async()=>{
|
||||
const id=+getId('segT').value,txt=getId('txt').value.trim();
|
||||
ovShow();
|
||||
try{
|
||||
const j={on:true,seg:{id,fx:122,n:txt,sx:+gId('sx').value,ix:+gId('ix').value,c1:+gId('c1').value,c2:+gId('c2').value,c3:+gId('c3').value,o1:gId('o1').checked,o3:gId('o3').checked}};
|
||||
const r=await fetch(`${wu}/json/state`,{method:'POST',body:JSON.stringify(j)});
|
||||
const j={on:true,seg:{id,fx:122,n:txt,sx:+getId('sx').value,ix:+getId('ix').value,c1:+getId('c1').value,c2:+getId('c2').value,c3:+getId('c3').value,o1:getId('o1').checked,o3:getId('o3').checked}};
|
||||
const r=await fetch(getURL('/json/state'),{method:'POST',body:JSON.stringify(j)});
|
||||
const out=await r.json();
|
||||
if(out.success!==false){ msg(`Applied to Segment ${id}`); await segLoad(); }
|
||||
else msg('Failed to apply','err');
|
||||
}catch(e){ msg(`Error: ${e.message}`,'err'); }
|
||||
finally{ ovHide(); }
|
||||
};
|
||||
|
||||
// load available fonts (files ending with .wbf) and display in list
|
||||
function scanFonts(){
|
||||
const wbf=(fL||[]).filter(f=>f.name.endsWith('.wbf'));
|
||||
getId('fList').innerHTML=wbf.map(f=>
|
||||
`<span>${f.name} <b onclick="delFont('${f.name}')" style="cursor:pointer;color:#8cf;padding:0 3px">✖</b></span>`
|
||||
).join('')||'<span style="color:#888">None</span>';
|
||||
getId('dcf').style.display=classics.every(fn=>wbf.some(f=>f.name===fn))?'none':'block'; // hide "Download classic fonts" button if all are present
|
||||
}
|
||||
|
||||
// delete font file
|
||||
async function delFont(name){
|
||||
if(!confirm(`Delete ${name}?`))return;
|
||||
const r=await fetch(getURL(`/edit?func=delete&path=/${name}`));
|
||||
r.ok?msg('Deleted'):msg('Delete failed','err');
|
||||
await flU(); scanFonts();
|
||||
}
|
||||
|
||||
// download classic WLED fonts from github and upload to FS
|
||||
getId('dcf').onclick=async()=>{
|
||||
if(!confirm('Download classic WLED fonts?'))return;
|
||||
ovShow(); let ok=0,fail=0;
|
||||
for(const fn of classics){
|
||||
try{
|
||||
const r=await fetch(`https://dedehai.github.io/wbfFonts/${fn}`);
|
||||
if(!r.ok){fail++;continue;}
|
||||
const fd=new FormData();
|
||||
fd.append('data',await r.blob(),fn);
|
||||
(await fetch(getURL('/upload'),{method:'POST',body:fd})).ok?ok++:fail++;
|
||||
}catch(e){msg(`Failed ${fn}: ${e.message}`,'err');}
|
||||
}
|
||||
ovHide(); msg('Fonts installed');
|
||||
await flU(); scanFonts();
|
||||
};
|
||||
|
||||
/* preview canvas - actual display may differ */
|
||||
const tpv = getId('tpv'), tpx = tpv.getContext('2d');
|
||||
function draw() {
|
||||
// fade out to simulate "trail"
|
||||
let tr = 1 - (getId('c1').value / 280); // c1 controls trail length
|
||||
//tpx.fillStyle = `rgba(0,0,0,${tr.toFixed(2)})`;
|
||||
tpx.fillStyle = `rgba(0,0,0,${tr})`;
|
||||
tpx.fillRect(0,0,100,50);
|
||||
|
||||
let txt = getId('txt').value || 'WLED'; // note: decoding tokens is not implemented as it just takes a lot of code for little benefit
|
||||
let sx = getId('sx').value;
|
||||
let ix = getId('ix').value, c2 = getId('c2').value, c3 = getId('c3').value;
|
||||
|
||||
let fzs = [8, 12, 14, 20, 28][Math.floor(c2/52)] || 8; // Font sizes 1-5
|
||||
let rot = -(Math.round((c3)/7.5)-2) * Math.PI/2; // -2 to 2 maps to 180 to -180
|
||||
let t = (Date.now() * (0.02 + (sx / 255) * 0.1)) % (100 + txt.length * fzs);
|
||||
let x = getId('o3').checked ? (t - (txt.length * fzs)) : 100 - t;
|
||||
let y = 25 + (ix - 128) / 5;
|
||||
|
||||
// draw char-by-char just like the FX
|
||||
tpx.fillStyle = "#fff";
|
||||
tpx.font = fzs + "px monospace";
|
||||
tpx.textAlign = "center";
|
||||
tpx.textBaseline = "middle";
|
||||
|
||||
for(let i=0; i<txt.length; i++) {
|
||||
let charX = x + (i * fzs); // simple letter spacing
|
||||
if(charX < -20 || charX > 120) continue;
|
||||
tpx.save();
|
||||
tpx.translate(charX, y);
|
||||
tpx.rotate(rot);
|
||||
tpx.fillStyle = "#fff";
|
||||
if (getId('o1').checked) { // gradient color
|
||||
let g = tpx.createLinearGradient(0, -fzs/2, 0, fzs/2);
|
||||
g.addColorStop(0, "#f5f"); g.addColorStop(1, "#8cf");
|
||||
tpx.fillStyle = g;
|
||||
}
|
||||
tpx.fillText(txt[i], 0, 0);
|
||||
tpx.restore();
|
||||
}
|
||||
requestAnimationFrame(draw);
|
||||
}
|
||||
draw();
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -40,8 +40,9 @@
|
||||
</head>
|
||||
<body>
|
||||
<button type=submit id="b" onclick="window.location=getURL('/')">Back</button>
|
||||
<button type="submit" onclick="window.location=getURL('/settings/wifi')">WiFi Setup</button>
|
||||
<button type="submit" onclick="window.location=getURL('/settings/leds')">LED Preferences</button>
|
||||
<button type="submit" onclick="window.location=getURL('/settings/wifi')">WiFi & Network</button>
|
||||
<button type="submit" onclick="window.location=getURL('/settings/leds')">LED & Hardware</button>
|
||||
<button type="submit" onclick="window.location=getURL('/settings/pins')">Pin Info</button>
|
||||
<button id="2dbtn" type="submit" onclick="window.location=getURL('/settings/2D')">2D Configuration</button>
|
||||
<button type="submit" onclick="window.location=getURL('/settings/ui')">User Interface</button>
|
||||
<button id="dmxbtn" style="display:none;" type="submit" onclick="window.location=getURL('/settings/dmx')">DMX Output</button>
|
||||
|
||||
@@ -49,7 +49,7 @@
|
||||
if (p.children.length >= maxPanels) return;
|
||||
var pw = parseInt(d.Sf.PW.value);
|
||||
var ph = parseInt(d.Sf.PH.value);
|
||||
let b = `<div id="pnl${i}"><hr class="sml">Panel ${i}<br>
|
||||
let b = `<div id="pnl${i}"><b>Panel ${i}</b><br>
|
||||
1<sup>st</sup> LED: <select name="P${i}B" oninput="UI()">
|
||||
<option value="0">Top</option>
|
||||
<option value="1">Bottom</option>
|
||||
@@ -65,7 +65,7 @@ Serpentine: <input type="checkbox" name="P${i}S" oninput="UI()"><br>
|
||||
Dimensions (WxH): <input name="P${i}W" type="number" min="1" max="255" value="${pw}" oninput="UI()"> x <input name="P${i}H" type="number" min="1" max="255" value="${ph}" oninput="UI()"><br>
|
||||
Offset X: <input name="P${i}X" type="number" min="0" max="255" value="0" oninput="UI()">
|
||||
Y: <input name="P${i}Y" type="number" min="0" max="255" value="0" oninput="UI()"><br><i>(offset from top-left corner in # LEDs)</i>
|
||||
</div>`;
|
||||
<br><br></div>`;
|
||||
p.insertAdjacentHTML("beforeend", b);
|
||||
}
|
||||
|
||||
@@ -255,13 +255,15 @@ Y: <input name="P${i}Y" type="number" min="0" max="255" value="0" oninput="UI()"
|
||||
<button type="button" onclick="B()">Back</button><button type="button" onclick="fS()">Save</button><hr>
|
||||
</div>
|
||||
<h2>2D setup</h2>
|
||||
<div class="sec">
|
||||
Strip or panel:
|
||||
<select id="somp" name="SOMP" onchange="resetPanels();addPanels();UI();" >
|
||||
<option value="0">1D Strip</option>
|
||||
<option value="1">2D Matrix</option>
|
||||
</select><br>
|
||||
</select>
|
||||
</div>
|
||||
<div id="mpdiv" style="display:none;">
|
||||
<hr class="sml">
|
||||
<div class="sec">
|
||||
<h3>Matrix Generator <button type="button" id="expGen" onclick="expand(this,gId('mxGen'));">></button></h3>
|
||||
<div id="mxGen" style="display:none;">
|
||||
Panel dimensions (WxH): <input name="PW" type="number" min="1" max="128" value="8"> x <input name="PH" type="number" min="1" max="128" value="8"><br>
|
||||
@@ -283,21 +285,26 @@ Y: <input name="P${i}Y" type="number" min="0" max="255" value="0" oninput="UI()"
|
||||
WARNING: You may need to update each panel parameters after they are generated.</i><br>
|
||||
<button type="button" onclick="gen();expand(gId('expGen'),gId('mxGen'));">Populate</button>
|
||||
</div>
|
||||
<hr class="sml">
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Panel set-up</h3>
|
||||
Number of panels: <input name="MPC" type="number" min="1" max="64" value="1" oninput="addPanels();UI();"><br>
|
||||
<i>A matrix is made of 1 or more physical LED panels.<br>
|
||||
Each panel can be of different size and/or have different LED orientation and/or starting point and/or layout.</i><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>LED panel layout</h3>
|
||||
<div id="panels">
|
||||
</div>
|
||||
<hr class="sml">
|
||||
<div id="MD"></div>
|
||||
<canvas id="canvas"></canvas>
|
||||
</div>
|
||||
<div id="MD"></div>
|
||||
<canvas id="canvas"></canvas>
|
||||
<div class="sec">
|
||||
<div id="json" >Gap file: <input type="file" name="data" accept=".json"><button type="button" class="sml" onclick="uploadFile(d.Sf.data,'/2d-gaps.json')">Upload</button></div>
|
||||
<i>Note: Gap file is a <b>.json</b> file containing an array with number of elements equal to the matrix size.<br>
|
||||
A value of -1 means that pixel at that position is missing, a value of 0 means never paint that pixel, and 1 means regular pixel.</i>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
<button type="button" onclick="B()">Back</button><button type="button" onclick="fS()">Save</button>
|
||||
</form>
|
||||
|
||||
+282
-114
@@ -6,7 +6,7 @@
|
||||
<title>LED Settings</title>
|
||||
<style> html { visibility: hidden; } </style> <!-- prevent white & ugly display while loading, unhidden in loadResources() -->
|
||||
<script>
|
||||
var maxB=1,maxD=1,maxA=1,maxV=0,maxM=4000,maxPB=2048,maxL=1664,maxCO=5,maxBT=4; //maximum bytes for LED allocation: 4kB for 8266, 32kB for 32
|
||||
var maxD=1,maxI2S=0,maxRMT=0,maxA=1,chipID=0,maxM=4000,maxPB=2048,maxL=1664,maxCO=5,maxBT=4; //maximum bytes for LED allocation: 4kB for 8266, 32kB for 32
|
||||
var customStarts=false,startsDirty=[];
|
||||
function off(n) { gN(n).value = -1;}
|
||||
// these functions correspond to C macros found in const.h
|
||||
@@ -37,6 +37,7 @@
|
||||
|
||||
function S() {
|
||||
getLoc();
|
||||
if(localStorage.getItem('ASc')==='true') d.Sf.AS.checked=true;
|
||||
loadJS(getURL('/settings/s.js?p=2'), false, ()=>{
|
||||
d.ledTypes = [/*{i:22,c:1,t:"D",n:"WS2812"},{i:42,c:6,t:"AA",n:"PWM CCT"}*/]; // filled from GetV()
|
||||
d.um_p = [];
|
||||
@@ -52,22 +53,23 @@
|
||||
}); // If we set async false, file is loaded and executed, then next statement is processed
|
||||
if (loc) d.Sf.action = getURL('/settings/leds');
|
||||
}
|
||||
function bLimits(b,v,p,m,l,o=5,d=2,a=6,n=4) {
|
||||
maxB = b; // maxB - max physical (analog + digital) buses: 32 - ESP32, 14 - S3/S2, 6 - C3, 4 - 8266
|
||||
maxV = v; // maxV - min virtual buses: 6 - ESP32/S3, 4 - S2/C3, 3 - ESP8266 (only used to distinguish S2/S3)
|
||||
maxPB = p; // maxPB - max LEDs per bus
|
||||
maxM = m; // maxM - max LED memory
|
||||
maxL = l; // maxL - max LEDs (will serve to determine ESP >1664 == ESP32)
|
||||
maxCO = o; // maxCO - max Color Order mappings
|
||||
maxD = d; // maxD - max digital channels (can be changed if using ESP32 parallel I2S): 16 - ESP32, 12 - S3/S2, 2 - C3, 3 - 8266
|
||||
maxA = a; // maxA - max analog channels: 16 - ESP32, 8 - S3/S2, 6 - C3, 5 - 8266
|
||||
maxBT = n; // maxBT - max buttons
|
||||
function bLimits(c,p,m,l,o,di,r,i,a,n) {
|
||||
chipID = c; // chip/platformID - 0 = ESP8266, 1 = C3, 2 = S2, 3 = S3, 4 = ESP32
|
||||
maxPB = p; // maxPB - max LEDs per bus
|
||||
maxM = m; // maxM - max LED memory
|
||||
maxL = l; // maxL - max LEDs (will serve to determine ESP >1664 == ESP32)
|
||||
maxCO = o; // maxCO - max Color Order mappings
|
||||
maxD = di; // maxD - max digital channels (can be changed if using ESP32 parallel I2S): 16 - ESP32, 12 - S3/S2, 2 - C3, 3 - 8266
|
||||
maxRMT = r; // maxRMT - max RMT channels: 8 - ESP32, 4 - S2/S3, 2 - C3, 0 - 8266
|
||||
maxI2S = i; // maxI2S - max I2S/LCD channels: 8 - ESP32/S2/S3, 0 - C3/8266
|
||||
maxA = a; // maxA - max analog channels: 16 - ESP32, 8 - S3/S2, 6 - C3, 5 - 8266
|
||||
maxBT = n; // maxBT - max buttons
|
||||
}
|
||||
function is8266() { return maxA == 5 && maxD == 3; } // NOTE: see const.h
|
||||
function is32() { return maxA == 16 && maxD == 16; } // NOTE: see const.h
|
||||
function isC3() { return maxA == 6 && maxD == 2; } // NOTE: see const.h
|
||||
function isS2() { return maxA == 8 && maxD == 12 && maxV == 4; } // NOTE: see const.h
|
||||
function isS3() { return maxA == 8 && maxD == 12 && maxV == 6; } // NOTE: see const.h
|
||||
function is8266() { return chipID == 0; } // NOTE: see const.h: WLED_PLATFORM_ID (TODO: use info json lookup instead)
|
||||
function isC3() { return chipID == 1; }
|
||||
function isS2() { return chipID == 2; }
|
||||
function isS3() { return chipID == 3; }
|
||||
function is32() { return chipID == 4; }
|
||||
function pinsOK() {
|
||||
var ok = true;
|
||||
var nList = d.Sf.querySelectorAll("#mLC input[name^=L]");
|
||||
@@ -122,6 +124,12 @@
|
||||
d.Sf.data.value = '';
|
||||
e.preventDefault();
|
||||
if (!pinsOK()) {e.stopPropagation();return false;} // Prevent form submission and contact with server
|
||||
let usage = getDuse(), invalidBus = false;
|
||||
d.Sf.querySelectorAll("#mLC select[name^=LT]").forEach(s=>{
|
||||
let n = s.name.substring(2,3);
|
||||
if (!isBCok(n, usage)) invalidBus = true;
|
||||
});
|
||||
if (invalidBus) { alert("Invalid Bus-config"); e.stopPropagation(); return false; }
|
||||
// validate HUB75 panel config
|
||||
let LTs = d.Sf.querySelectorAll("#mLC select[name^=LT]");
|
||||
for (let i=0; i<LTs.length; i++) {
|
||||
@@ -136,7 +144,7 @@
|
||||
}
|
||||
}
|
||||
};
|
||||
if (bquot > 200) {var msg = "Too many LEDs! Can't handle that!"; alert(msg); e.stopPropagation(); return false;}
|
||||
if (bquot > 100) {var msg = "Too many LEDs! Can't handle that!"; alert(msg); e.stopPropagation(); return false;}
|
||||
else {
|
||||
if (bquot > 80) {var msg = "Memory usage is high, reboot recommended!\n\rSet transitions to 0 to save memory.";
|
||||
if (bquot > 100) msg += "\n\rToo many LEDs for me to handle properly!"; if (maxM < 10000) msg += "\n\rConsider using an ESP32."; alert(msg);}
|
||||
@@ -219,12 +227,12 @@
|
||||
enABL();
|
||||
gId('m1').innerHTML = maxM;
|
||||
}
|
||||
//returns mem usage
|
||||
//returns mem usage for buses including two pixel buffers (segment buffer + global buffer)
|
||||
function getMem(t, n) {
|
||||
if (isAna(t)) return 5; // analog
|
||||
let len = parseInt(d.Sf["LC"+n].value);
|
||||
len += parseInt(d.Sf["SL"+n].value); // skipped LEDs are allocated too
|
||||
let dbl = 0;
|
||||
let dma = 0; // DMA memory for this bus (only for I2S)
|
||||
let pbfr = len * 8; // pixel buffers: global buffer + segment buffer (at least one segment buffer is required)
|
||||
let ch = 3*hasRGB(t) + hasW(t) + hasCCT(t);
|
||||
let mul = 1;
|
||||
@@ -233,16 +241,30 @@
|
||||
if (is8266() && d.Sf["L0"+n].value == 3) { //8266 DMA uses 5x the mem
|
||||
mul = 5;
|
||||
}
|
||||
let parallelI2S = d.Sf.PR.checked && (is32() || isS2() || isS3()) && !isD2P(t);
|
||||
if (isC3() || (isS3() && !parallelI2S)) {
|
||||
mul = 2; // ESP32 RMT uses double buffer
|
||||
} else if ((is32() || isS2() || isS3()) && toNum(n) > (parallelI2S ? 7 : 0)) {
|
||||
mul = 2; // ESP32 RMT uses double buffer
|
||||
} else if ((parallelI2S && toNum(n) < 8) || (n == 0 && is32())) { // I2S uses extra DMA buffer
|
||||
dbl = len * ch * 3; // DMA buffer for parallel I2S (TODO: ony the bus with largst LED count should be used)
|
||||
if (!is8266() && !isD2P(t)) {
|
||||
mul = 2; // default to double buffer (RMT, 2-pin digital)
|
||||
let driverPref = d.Sf["LD"+n]?.value | 0; // driver preference selection: 0=RMT, 1=I2S
|
||||
if (driverPref == 1) { // I2S to be used
|
||||
mul = 1; // NPB uses single pixel buffer for I2S, DMA buffer serves as second buffer
|
||||
let usage = getDuse();
|
||||
dma = usage.I2Smem; // DMA buffer for I2S/LCD, getDuse() returns the average per I2S bus so it can be distributed and summed
|
||||
}
|
||||
}
|
||||
//console.log(`LED mem for bus ${n} (NPB buffers, DMA buffer per bus, WLED pixel buffers): ${len * ch * mul} + ${dma} + ${pbfr}`);
|
||||
}
|
||||
return len * ch * mul + dbl + pbfr;
|
||||
return len * ch * mul + dma + pbfr;
|
||||
}
|
||||
|
||||
// check if bus configuration is valid
|
||||
function isBCok(n, usage) {
|
||||
if (is8266()) return true; // no special bus limits on ESP8266 other than digital bus count, checked in updateTypeDropdowns()
|
||||
let t = parseInt(d.Sf["LT"+n].value);
|
||||
if (!isDig(t) || isD2P(t)) return true; // only digital non-2pin types need bus check
|
||||
let drv = d.Sf["LD"+n]?.value | 0; // driver preference selection: 0=RMT, 1=I2S
|
||||
if (drv==1 && usage.I2SType!==null && t!==usage.I2SType) return false; // mismatched type in parallel I2S
|
||||
if (drv==0 && usage.rmtUsed > maxRMT) return false; // too many RMT buses
|
||||
if (drv==1 && usage.i2sUsed > maxI2S) return false; // too many I2S buses
|
||||
return true;
|
||||
}
|
||||
|
||||
function UI(change=false)
|
||||
@@ -294,14 +316,12 @@
|
||||
|
||||
// enable/disable LED fields
|
||||
updateTypeDropdowns(); // restrict bus types in dropdowns to max allowed digital/analog buses
|
||||
let dC = 0; // count of digital buses (for parallel I2S)
|
||||
let LTs = d.Sf.querySelectorAll("#mLC select[name^=LT]");
|
||||
LTs.forEach((s,i)=>{
|
||||
// is the field a LED type?
|
||||
var n = s.name.substring(2,3); // bus number (0-Z)
|
||||
var t = parseInt(s.value);
|
||||
memu += getMem(t, n); // calc memory
|
||||
dC += (isDig(t) && !isD2P(t));
|
||||
setPinConfig(n,t);
|
||||
gId("abl"+n).style.display = (!abl || !isDig(t)) ? "none" : "inline"; // show/hide individual ABL settings
|
||||
if (change) { // did we change LED type?
|
||||
@@ -340,39 +360,34 @@
|
||||
let nm = LC.name.substring(0,2); // field name : /L./
|
||||
let n = LC.name.substring(2,3); // bus number (0-Z)
|
||||
let t = parseInt(d.Sf["LT"+n].value); // LED type SELECT
|
||||
if (isDig(t)) {
|
||||
if (isDig(t) && !isD2P(t)) {
|
||||
if (sameType == 0) sameType = t; // first bus type
|
||||
else if (sameType != t) sameType = -1; // different bus type
|
||||
}
|
||||
// do we have a led count field
|
||||
if (nm=="LC") {
|
||||
if (!isHub75(t)) {
|
||||
LC.max = isAna(t) ? 1 : (isDig(t) ? maxPB : 16384); // set max value
|
||||
} else {
|
||||
LC.min = undefined;
|
||||
LC.max = undefined;
|
||||
}
|
||||
let c = parseInt(LC.value,10); //get LED count
|
||||
if (!customStarts || !startsDirty[toNum(n)]) gId("ls"+n).value = sLC; //update start value
|
||||
gId("ls"+n).disabled = !customStarts; //enable/disable field editing
|
||||
if (c) {
|
||||
let s = parseInt(gId("ls"+n).value); //start value
|
||||
if (s+c > sLC) sLC = s+c; //update total count
|
||||
if (c > maxLC) maxLC = c; //max per output
|
||||
if (!isVir(t)) sPC += c; //virtual out busses do not count towards physical LEDs
|
||||
if (isDig(t)) {
|
||||
if (c > maxLC) maxLC = c; //max per output
|
||||
sDI += c; // summarize digital LED count
|
||||
let maPL = parseInt(d.Sf["LA"+n].value);
|
||||
if (maPL == 255) maPL = 12;
|
||||
if (maPL == 255) maPL = 12; // wacky WS2815 mode (255 == 12mA per LED)
|
||||
busMA += maPL*c; // summarize maximum bus current (calculated)
|
||||
}
|
||||
} // increase led count
|
||||
return;
|
||||
}
|
||||
// do we have led pins for digital leds
|
||||
if (nm=="L0" || nm=="L1") {
|
||||
if (!isHub75(t)) {
|
||||
d.Sf["LC"+n].max = maxPB; // update max led count value
|
||||
}
|
||||
else {
|
||||
d.Sf["LC"+n].min = undefined;
|
||||
d.Sf["LC"+n].max = undefined;
|
||||
}
|
||||
}
|
||||
// ignore IP address (stored in pins for virtual busses)
|
||||
if (nm.search(/^L[0-3]/) == 0) { // pin fields
|
||||
if (isVir(t)) {
|
||||
@@ -420,13 +435,47 @@
|
||||
else LC.style.color = d.ro_gpio.some((e)=>e==parseInt(LC.value)) ? "orange" : "#fff";
|
||||
} else LC.style.color = "#fff";
|
||||
});
|
||||
if (is32() || isS2() || isS3()) {
|
||||
if (maxLC > 600 || dC < 2 || sameType <= 0) {
|
||||
d.Sf["PR"].checked = false;
|
||||
gId("prl").classList.add("hide");
|
||||
} else
|
||||
gId("prl").classList.remove("hide");
|
||||
} else d.Sf["PR"].checked = false;
|
||||
|
||||
// Use helper function to calculate channel usage
|
||||
let usage = getDuse();
|
||||
|
||||
d.Sf.querySelectorAll("#mLC select[name^=LT]").forEach((s)=>{
|
||||
let n = s.name.substring(2,3);
|
||||
let t = parseInt(s.value);
|
||||
let drvsel = gId("drvsel"+n); // driver selection dropdown
|
||||
if (drvsel) {
|
||||
drvsel.style.display = "none"; // hide by default
|
||||
drvsel.style.color = "#fff"; // reset color
|
||||
}
|
||||
s.style.color = "#fff"; // reset
|
||||
|
||||
if (isDig(t) && !isD2P(t)) {
|
||||
// Update I2S/RMT driver info/dropdown for ESP32 digital buses, C3 only supports RMT
|
||||
if (!is8266() && !isC3()) {
|
||||
// Show driver selection dropdown when I2S is enabled, mark red if invalid
|
||||
if (drvsel) {
|
||||
if (d.Sf.AS.checked) drvsel.style.display = "inline"; // only show when advanced settings enabled
|
||||
d.Sf["LD"+n].value = d.Sf["LD"+n].value | 0; // default to RMT
|
||||
if (!isBCok(n, usage)) drvsel.style.color = "red"; else drvsel.style.color = "#fff";
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
updateTypeDropdowns(); // update type dropdowns to disable unavailable digital/analog types (I2S/RMT bus count may have changed due to memory usage change)
|
||||
// note: do not remvoe this second call to updateTypeDropdowns() as it also updates the available LED types based on the current bus configuration, not just the driver options
|
||||
|
||||
// Show channel usage warning
|
||||
let chanuse = gId('chanuse');
|
||||
let channelMsg = gId('chanusemsg');
|
||||
if (chanuse && channelMsg && !is8266()) {
|
||||
chanuse.style.display = 'inline';
|
||||
chanuse.style.color = '#ccc';
|
||||
channelMsg.textContent = `Hardware channels used: RMT ${usage.rmtUsed}/${maxRMT}, I2S ${usage.i2sUsed}/${maxI2S}`;
|
||||
if (usage.rmtUsed > maxRMT || usage.i2sUsed > maxI2S) {
|
||||
chanuse.style.color = 'red';
|
||||
}
|
||||
}
|
||||
|
||||
// distribute ABL current if not using PPL
|
||||
enPPL(sDI);
|
||||
|
||||
@@ -462,6 +511,7 @@
|
||||
gId('fpsWarn').style.display = (d.Sf.FR.value == 0) || (d.Sf.FR.value >= 80) ? 'block':'none';
|
||||
gId('fpsHigh').style.display = (d.Sf.FR.value >= 80) ? 'block':'none';
|
||||
}
|
||||
|
||||
function lastEnd(i) {
|
||||
if (i-- < 1) return 0;
|
||||
var s = chrID(i);
|
||||
@@ -470,6 +520,7 @@
|
||||
if (isPWM(t)) v = 1; //PWM busses
|
||||
return isNaN(v) ? 0 : v;
|
||||
}
|
||||
|
||||
function addLEDs(n,init=true)
|
||||
{
|
||||
var o = gEBCN("iST");
|
||||
@@ -485,7 +536,7 @@
|
||||
var cn = `<div class="iST">
|
||||
<hr class="sml">
|
||||
${i+1}:
|
||||
<select name="LT${s}" onchange="updateTypeDropdowns();UI(true)"></select><br>
|
||||
<select name="LT${s}" onchange="UI(true)"></select><br>
|
||||
<div id="abl${s}">
|
||||
mA/LED: <select name="LAsel${s}" onchange="enLA(this,'${s}');UI();">
|
||||
<option value="55" selected>55mA (typ. 5V WS281x)</option>
|
||||
@@ -511,13 +562,19 @@ mA/LED: <select name="LAsel${s}" onchange="enLA(this,'${s}');UI();">
|
||||
<div id="dig${s}l" style="display:none">Clock: <select name="SP${s}"><option value="0">Slowest</option><option value="1">Slow</option><option value="2">Normal</option><option value="3">Fast</option><option value="4">Fastest</option></select></div>
|
||||
<div>
|
||||
<span id="psd${s}">Start:</span> <input type="number" name="LS${s}" id="ls${s}" class="l starts" min="0" max="8191" value="${lastEnd(i)}" oninput="startsDirty[${i}]=true;UI();" required />
|
||||
<div id="dig${s}c" style="display:inline">Length: <input type="number" name="LC${s}" class="l" min="1" max="${maxPB}" value="1" required oninput="UI()" /></div><br>
|
||||
<div id="dig${s}c" style="display:inline">Length: <input type="number" name="LC${s}" class="l" min="1" max="${maxPB}" value="1" required oninput="UI();" /></div><br>
|
||||
</div>
|
||||
<span id="p0d${s}">GPIO:</span><input type="number" name="L0${s}" required class="s" onchange="UI();pinUpd(this);"/>
|
||||
<span id="p1d${s}"></span><input type="number" name="L1${s}" class="s" onchange="UI();pinUpd(this);"/>
|
||||
<span id="p2d${s}"></span><input type="number" name="L2${s}" class="s" onchange="UI();pinUpd(this);"/>
|
||||
<span id="p3d${s}"></span><input type="number" name="L3${s}" class="s" onchange="UI();pinUpd(this);"/>
|
||||
<span id="p4d${s}"></span><input type="number" name="L4${s}" class="s" onchange="UI();pinUpd(this);"/>
|
||||
<div id="drvsel${s}" style="display:none">
|
||||
Driver: <select name="LD${s}" onchange="UI()">
|
||||
<option value="0">RMT</option>
|
||||
<option value="1">I2S</option>
|
||||
</select>
|
||||
</div>
|
||||
<div id="net${s}h" class="hide">Host: <input type="text" name="HS${s}" maxlength="32" pattern="[a-zA-Z0-9_\\-]*" onchange="UI()"/>.local</div>
|
||||
<div id="dig${s}r" style="display:inline"><br><span id="rev${s}">Reversed</span>: <input type="checkbox" name="CV${s}"></div>
|
||||
<div id="dig${s}s" style="display:inline"><br>Skip first LEDs: <input type="number" name="SL${s}" min="0" max="255" value="0" oninput="UI()"></div>
|
||||
@@ -698,6 +755,7 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
addLEDs(1);
|
||||
for (var j=0; j<v.pin.length; j++) d.getElementsByName(`L${j}${i}`)[0].value = v.pin[j];
|
||||
d.getElementsByName("LT"+i)[0].value = v.type;
|
||||
d.getElementsByName("LD"+i)[0].value = v.drv | 0; // output driver type (RMT or I2S, default to RMT if not set)
|
||||
d.getElementsByName("LS"+i)[0].value = v.start;
|
||||
d.getElementsByName("LC"+i)[0].value = v.len;
|
||||
d.getElementsByName("CO"+i)[0].value = v.order & 0x0F;
|
||||
@@ -710,7 +768,6 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
d.getElementsByName("LA"+i)[0].value = v.ledma;
|
||||
d.getElementsByName("MA"+i)[0].value = v.maxpwr;
|
||||
});
|
||||
d.getElementsByName("PR")[0].checked = l.prl | 0;
|
||||
d.getElementsByName("MA")[0].value = l.maxpwr;
|
||||
d.getElementsByName("ABL")[0].checked = l.maxpwr > 0;
|
||||
}
|
||||
@@ -762,7 +819,7 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
if (d.ro_gpio.includes(j)) txt += " (R/O)";
|
||||
let opt = addOption(sel, txt, j);
|
||||
if (j === v) opt.selected = true; // this is "our" pin
|
||||
else if (d.um_p.includes(j)) opt.disabled = true; // someone else's pin
|
||||
else if (d.um_p.includes(j) && j > -1) opt.disabled = true; // someone else's pin
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -843,11 +900,50 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
// calculate channel usage across all buses
|
||||
function getDuse() {
|
||||
let rmtUsed = 0, i2sUsed = 0;
|
||||
let I2SType = null;
|
||||
let I2Smem = 0; // DMA memory usage for I2S buses: 3x LED count for single I2S bus, 24x LED count for parallel I2S
|
||||
let maxLEDs = 0; // max number of LEDs for DMA buffer calc
|
||||
if (!is8266()) {
|
||||
d.Sf.querySelectorAll("#mLC select[name^=LT]").forEach(sel => {
|
||||
let n = sel.name.substring(2,3);
|
||||
let t = parseInt(sel.value);
|
||||
let driverPref = d.Sf["LD"+n]?.value | 0;
|
||||
let ledCount = (parseInt(d.Sf["LC"+n].value) || 0) + (parseInt(d.Sf["SL"+n].value) || 0);
|
||||
|
||||
if (isDig(t) && !isD2P(t)) {
|
||||
if (driverPref === 1) {
|
||||
i2sUsed++;
|
||||
maxLEDs = maxLEDs > ledCount ? maxLEDs : ledCount; // for parallel I2S the memory buffer is shared, largest bus determines total memory usage
|
||||
if (!I2SType) I2SType = t; // first I2S bus determines allowed type for all subsequent I2S buses (parallel I2S limitation)
|
||||
} else {
|
||||
rmtUsed++;
|
||||
}
|
||||
}
|
||||
});
|
||||
// calculate I2S memory usage
|
||||
if (I2SType) {
|
||||
let ch = 3*hasRGB(I2SType) + hasW(I2SType) + hasCCT(I2SType); // byte channel count per LED
|
||||
if (is16b(I2SType)) maxLEDs *= 2; // 16 bit LEDs use 2 bytes per channel
|
||||
I2Smem = maxLEDs * ch * (i2sUsed > 1 || isS3() ? 24 : 3); // 3 bytes per LED byte for single I2S, 24 bytes per LED byte for parallel I2S (S3 always uses parallel), assumes 3-step cadence
|
||||
I2Smem = Math.round(I2Smem / i2sUsed); // average memory per I2S bus (used for memory estimation), round to nearest integer to avoid float rounding errors
|
||||
}
|
||||
}
|
||||
return { rmtUsed, i2sUsed, I2SType, I2Smem };
|
||||
}
|
||||
|
||||
// dynamically enforce bus type availability based on current usage
|
||||
function updateTypeDropdowns() {
|
||||
let LTs = d.Sf.querySelectorAll("#mLC select[name^=LT]");
|
||||
let digitalB = 0, analogB = 0, twopinB = 0, virtB = 0;
|
||||
// count currently used buses
|
||||
|
||||
// calculate channel usage
|
||||
let usage = getDuse();
|
||||
let firstI2SType = null;
|
||||
|
||||
// Count all bus types
|
||||
LTs.forEach(sel => {
|
||||
let t = parseInt(sel.value);
|
||||
if (isDig(t) && !isD2P(t)) digitalB++;
|
||||
@@ -855,36 +951,84 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
if (isD2P(t)) twopinB++;
|
||||
if (isVir(t)) virtB++;
|
||||
});
|
||||
// enable/disable type options according to limits in dropdowns
|
||||
|
||||
// update each LED-type and driver dropdown with appropriate constraints
|
||||
let RMTcount = 0;
|
||||
let I2Scount = 0;
|
||||
LTs.forEach(sel => {
|
||||
let n = sel.name.substring(2,3);
|
||||
const curType = parseInt(sel.value);
|
||||
const curDriver = d.Sf["LD"+n]?.value | 0;
|
||||
const disable = (q) => sel.querySelectorAll(q).forEach(o => o.disabled = true);
|
||||
const enable = (q) => sel.querySelectorAll(q).forEach(o => o.disabled = false);
|
||||
enable('option'); // reset all first
|
||||
// max digital buses: ESP32 & S2 support mono I2S as well as parallel so we need to take that into account; S3 only supports parallel
|
||||
// supported outputs using parallel I2S/mono I2S: S2: 12/5, S3: 12/4, ESP32: 16/9
|
||||
let maxDB = maxD - ((is32() || isS2() || isS3()) ? (!d.Sf["PR"].checked) * 8 - (!isS3()) : 0); // adjust max digital buses if parallel I2S is not used
|
||||
// disallow adding more of a type that has reached its limit but allow changing the current type
|
||||
if (digitalB >= maxDB && !(isDig(curType) && !isD2P(curType))) disable('option[data-type="D"]');
|
||||
// Update LED type constraints for digital buses
|
||||
if (isDig(curType) && !isD2P(curType)) {
|
||||
// If this bus uses I2S and other I2S buses exist, restrict to same type
|
||||
if (curDriver === 1) {
|
||||
if (firstI2SType == null) firstI2SType = curType; // set first type, first I2S bus is allowed to change to any digital type
|
||||
else {
|
||||
sel.querySelectorAll('option[data-type="D"]').forEach(o => {
|
||||
if (parseInt(o.value) !== firstI2SType) o.disabled = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (digitalB >= maxD) disable('option[data-type="D"]'); // disable digital bus options if limit reached
|
||||
else if (!is8266() && usage.rmtUsed >= maxRMT && (firstI2SType != null)) {
|
||||
// there are still digital buses available, restrict digital bus options to I2S type if RMT is full (ESP32 only)
|
||||
sel.querySelectorAll('option[data-type="D"]').forEach(o => {
|
||||
if (parseInt(o.value) !== firstI2SType) o.disabled = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
// 2-pin digital buses limited to 2
|
||||
if (twopinB >= 2 && !isD2P(curType)) disable('option[data-type="2P"]');
|
||||
// Disable PWM types that need more pins than available (accounting for current type's pins if PWM)
|
||||
// PWM analog types limited by pin count
|
||||
disable(`option[data-type^="${'A'.repeat(maxA - analogB + (isPWM(curType)?numPins(curType):0) + 1)}"]`);
|
||||
|
||||
// update driver selection dropdowns
|
||||
let drvsel = gId("drvsel"+n);
|
||||
if (drvsel && isDig(curType) && !isD2P(curType)) {
|
||||
let rmtOpt = drvsel.querySelector('option[value="0"]');
|
||||
let i2sOpt = drvsel.querySelector('option[value="1"]');
|
||||
rmtOpt.disabled = false;
|
||||
i2sOpt.disabled = false;
|
||||
if (curDriver === 0) {
|
||||
if ((usage.i2sUsed >= maxI2S)) i2sOpt.disabled = true; // disable I2S selection on RMT buses if full
|
||||
RMTcount++;
|
||||
if (RMTcount > maxRMT) {
|
||||
rmtOpt.disabled = true; // disable RMT if now full (other logic disables digital types if both full)
|
||||
d.Sf["LD"+n].value = "1"; // switch to I2S (if no I2S available, digital type is disabled above)
|
||||
}
|
||||
}
|
||||
else {
|
||||
if ((usage.rmtUsed >= maxRMT)) rmtOpt.disabled = true; // disable RMT selection on I2S buses if full
|
||||
I2Scount++;
|
||||
if (I2Scount > maxI2S) {
|
||||
i2sOpt.disabled = true; // disable I2S if now full (other logic disables digital types if both full)
|
||||
d.Sf["LD"+n].value = "0"; // switch to RMT (if no RMT available, digital type is disabled above)
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<form id="form_s" name="Sf" method="post">
|
||||
<div class="toprow">
|
||||
<div class="helpB"><button type="button" onclick="H('features/settings/#led-settings')">?</button></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button><hr>
|
||||
</div>
|
||||
<h2>LED & Hardware setup</h2>
|
||||
<form id="form_s" name="Sf" method="post">
|
||||
<div class="toprow">
|
||||
<div class="helpB"><button type="button" onclick="H('features/settings/#led-settings')">?</button></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button><hr>
|
||||
</div>
|
||||
<h2>LED setup</h2>
|
||||
<div class="sec">
|
||||
Total LEDs: <span id="lc">?</span> <span id="pc"></span><br>
|
||||
<i>Recommended power supply for brightest white:</i><br>
|
||||
<b><span id="psu">?</span></b><br>
|
||||
<span id="psu2"><br></span>
|
||||
<br>
|
||||
Global brightness factor: <input name="BF" type="number" class="m" min="1" max="255" required> %<br>
|
||||
Enable automatic brightness limiter: <input type="checkbox" name="ABL" onchange="enABL()"><br>
|
||||
<div id="abl">
|
||||
<i>Automatically limits brightness to stay close to the limit.<br>
|
||||
@@ -892,7 +1036,7 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
If using multiple outputs it is recommended to use per-output limiter.<br>
|
||||
Analog (PWM) and virtual LEDs cannot use automatic brightness limiter.<br></i>
|
||||
<div id="psuMA">Maximum PSU Current: <input name="MA" type="number" class="xl" min="250" max="65000" oninput="UI()" required> mA<br></div>
|
||||
Use per-output limiter: <input type="checkbox" name="PPL" onchange="UI()"><br>
|
||||
Use per-output limiter: <input type="checkbox" name="PPL" onchange="UI()"><br><br>
|
||||
<div id="ppldis" style="display:none;">
|
||||
<i>Make sure you enter correct value for each LED output.<br>
|
||||
If using multiple outputs with only one PSU, distribute its power proportionally amongst outputs.</i><br>
|
||||
@@ -904,8 +1048,7 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
multiple power injection points and a fuse!<br>
|
||||
</div>
|
||||
</div>
|
||||
<h3>Hardware setup</h3>
|
||||
<div id="mLC">LED outputs:</div>
|
||||
<div id="mLC"><h4>LED outputs:</h4></div>
|
||||
<hr class="sml">
|
||||
<button type="button" id="+" onclick="addLEDs(1,false)">+</button>
|
||||
<button type="button" id="-" onclick="addLEDs(-1,false)">-</button><br>
|
||||
@@ -915,8 +1058,11 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
⚠ You might run into stability or lag issues.<br>
|
||||
Use less than <span id="wreason">800 LEDs per output</span> for the best experience!<br>
|
||||
</div>
|
||||
<div id="chanuse" style="display: none;">
|
||||
<span id="chanusemsg"></span><br>
|
||||
</div>
|
||||
<hr class="sml">
|
||||
<div id="prl" class="hide">Use parallel I2S: <input type="checkbox" name="PR"><br></div>
|
||||
Show Advanced Settings <input type="checkbox" name="AS" onchange="localStorage.setItem('ASc',this.checked);UI()"><br>
|
||||
Make a segment for each output: <input type="checkbox" name="MS"><br>
|
||||
Custom bus start indices: <input type="checkbox" onchange="tglSi(this.checked)" id="si"><br>
|
||||
<hr class="sml">
|
||||
@@ -927,17 +1073,45 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
<button type="button" id="com_add" onclick="addCOM()">+</button>
|
||||
<button type="button" id="com_rem" onclick="remCOM()">-</button>
|
||||
</div>
|
||||
<hr class="sml">
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Color & White</h3>
|
||||
Use Gamma correction for color: <input type="checkbox" name="GC"> (strongly recommended)<br>
|
||||
Use Gamma correction for brightness: <input type="checkbox" name="GB"> (not recommended)<br>
|
||||
Use Gamma value: <input name="GV" type="number" class="m" placeholder="2.2" min="0.1" max="3" step="0.1" required><br><br>
|
||||
White Balance correction: <input type="checkbox" name="CCT"><br>
|
||||
<div id="wc">
|
||||
Global override for Auto-calculate white:
|
||||
<select name="AW">
|
||||
<option value=255>Disabled</option>
|
||||
<option value=0>None</option>
|
||||
<option value=1>Brighter</option>
|
||||
<option value=2>Accurate</option>
|
||||
<option value=3>Dual</option>
|
||||
<option value=4>Max</option>
|
||||
</select>
|
||||
<br>
|
||||
Calculate CCT from RGB: <input type="checkbox" name="CR"><br>
|
||||
CCT IC used (Athom 15W): <input type="checkbox" name="IC"><br>
|
||||
CCT blending (±100%): <input type="number" class="s" min="-100" max="100" name="CB" onchange="UI()" required> %<br>
|
||||
<small>Positive: additive blend, Negative: exclusive blend<br></small>
|
||||
<i class="warn"><b>⚠</b> Set to 0 when using 2-wire (reverse polarity) CCT strips</i><br><br>
|
||||
</div>
|
||||
</div>
|
||||
<h2>Hardware setup</h2>
|
||||
<div class="sec">
|
||||
<h3>Buttons</h3>
|
||||
<div id="btn_wrap">
|
||||
Buttons:
|
||||
<div id="btns"></div>
|
||||
<hr class="sml">
|
||||
<button type="button" id="btn_add" onclick="addBtn(gId('btns').children.length,-1,0)">+</button>
|
||||
<button type="button" id="btn_rem" onclick="remBtn()">-</button>
|
||||
</div>
|
||||
Disable internal pull-up/down: <input type="checkbox" name="IP"><br>
|
||||
Touch threshold: <input type="number" class="s" min="0" max="100" name="TT" required><br>
|
||||
<hr class="sml">
|
||||
Touch threshold: <input type="number" class="s" min="0" max="100" name="TT" required><br><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>IR Remote</h3>
|
||||
IR GPIO: <input type="number" min="-1" max="48" name="IR" onchange="UI()" class="xs"><select name="IT" onchange="UI()">
|
||||
<option value=0>Remote disabled</option>
|
||||
<option value=1>24-key RGB</option>
|
||||
@@ -951,22 +1125,31 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
</select><span style="cursor: pointer;" onclick="off('IR')"> ✕</span><br>
|
||||
Apply IR change to main segment only: <input type="checkbox" name="MSO"><br>
|
||||
<div id="json" style="display:none;">JSON file: <input type="file" name="data" accept=".json"><button type="button" class="sml" onclick="uploadFile(d.Sf.data,'/ir.json')">Upload</button><br></div>
|
||||
<a href="https://kno.wled.ge/interfaces/infrared/" target="_blank">IR info</a><br>
|
||||
<hr class="sml">
|
||||
<a href="https://kno.wled.ge/interfaces/infrared/" target="_blank">IR info</a><br><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Relay</h3>
|
||||
Relay GPIO: <input type="number" min="-1" max="48" name="RL" onchange="UI()" class="xs"><span style="cursor: pointer;" onclick="off('RL')"> ✕</span><br>
|
||||
Invert <input type="checkbox" name="RM"> Open drain <input type="checkbox" name="RO"><br>
|
||||
<hr class="sml">
|
||||
<h3>Defaults</h3>
|
||||
Invert <input type="checkbox" name="RM"> Open drain <input type="checkbox" name="RO"><br><br>
|
||||
</div>
|
||||
<h2>General settings</h2>
|
||||
<div class="sec">
|
||||
<h3>Power up</h3>
|
||||
Turn LEDs on after power up/reset: <input type="checkbox" name="BO"><br>
|
||||
Default brightness: <input name="CA" type="number" class="m" min="1" max="255" required> (1-255)<br><br>
|
||||
Apply preset <input name="BP" type="number" class="m" min="0" max="250" required> at boot (0 uses values from above)<br><br>
|
||||
Use Gamma correction for color: <input type="checkbox" name="GC"> (strongly recommended)<br>
|
||||
Use Gamma correction for brightness: <input type="checkbox" name="GB"> (not recommended)<br>
|
||||
Use Gamma value: <input name="GV" type="number" class="m" placeholder="2.8" min="1" max="3" step="0.1" required><br><br>
|
||||
Brightness factor: <input name="BF" type="number" class="m" min="1" max="255" required> %
|
||||
with brightness: <input name="CA" type="number" class="m" min="1" max="255" required> (1-255)<br>
|
||||
<i>(disable if using boot preset to turn LEDs on)</i><br><br>
|
||||
Apply preset <input name="BP" type="number" class="m" min="0" max="250" required> at boot (0 = none)<br><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Transitions</h3>
|
||||
Default transition time: <input name="TD" type="number" class="xl" min="0" max="65500"> ms<br>
|
||||
<i>Random Cycle</i> Palette Time: <input name="TP" type="number" class="m" min="1" max="255"> s<br>
|
||||
Default transition time: <input name="TD" type="number" class="xl" min="0" max="65500"> ms<br><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Random Palettes</h3>
|
||||
Use harmonic colors in <i>Random palettes</i>: <input type="checkbox" name="TH"><br>
|
||||
<i>Random Palette</i> Cycle Time: <input name="TP" type="number" class="m" min="1" max="255"> s<br><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Timed light</h3>
|
||||
Default duration: <input name="TL" type="number" class="m" min="1" max="255" required> min<br>
|
||||
Default target brightness: <input name="TB" type="number" class="m" min="0" max="255" required><br>
|
||||
@@ -977,24 +1160,9 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
<option value="2">Fade Color</option>
|
||||
<option value="3">Sunrise</option>
|
||||
</select>
|
||||
<h3>White management</h3>
|
||||
White Balance correction: <input type="checkbox" name="CCT"><br>
|
||||
<div id="wc">
|
||||
Global override for Auto-calculate white:<br>
|
||||
<select name="AW">
|
||||
<option value=255>Disabled</option>
|
||||
<option value=0>None</option>
|
||||
<option value=1>Brighter</option>
|
||||
<option value=2>Accurate</option>
|
||||
<option value=3>Dual</option>
|
||||
<option value=4>Max</option>
|
||||
</select>
|
||||
<br>
|
||||
Calculate CCT from RGB: <input type="checkbox" name="CR"><br>
|
||||
CCT IC used (Athom 15W): <input type="checkbox" name="IC"><br>
|
||||
CCT additive blending: <input type="number" class="s" min="0" max="100" name="CB" onchange="UI()" required> %<br>
|
||||
<i class="warn">WARNING: When using H-bridge for reverse polarity (2-wire) CCT LED strip<br><b>make sure this value is 0</b>.<br>(ESP32 variants only, ESP8266 does not support H-bridges)</i>
|
||||
</div>
|
||||
<br><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Advanced</h3>
|
||||
Palette wrapping:
|
||||
<select name="PB">
|
||||
@@ -1003,16 +1171,16 @@ Swap: <select id="xw${s}" name="XW${s}">
|
||||
<option value="2">Linear (never wrap)</option>
|
||||
<option value="3">None (not recommended)</option>
|
||||
</select><br>
|
||||
Use harmonic <i>Random Cycle</i> palette: <input type="checkbox" name="TH"><br>
|
||||
Target refresh rate: <input type="number" class="s" min="0" max="250" name="FR" oninput="UI()" required> FPS
|
||||
<div id="fpsNone" class="warn" style="display: none;">⚠ Unlimited FPS Mode is experimental ⚠<br></div>
|
||||
<div id="fpsHigh" class="warn" style="display: none;">⚠ High FPS Mode is experimental.<br></div>
|
||||
<div id="fpsWarn" class="warn" style="display: none;">Please <a class="lnk" href="sec#backup">backup</a> WLED configuration and presets first!<br></div>
|
||||
<hr class="sml">
|
||||
<div id="cfg">Config template: <input type="file" name="data2" accept=".json"><button type="button" class="sml" onclick="loadCfg(d.Sf.data2)">Apply</button><br></div>
|
||||
<hr>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button>
|
||||
</form>
|
||||
<div id="toast"></div>
|
||||
<br><br>
|
||||
</div>
|
||||
<div id="cfg">Config template: <input type="file" name="data2" accept=".json"><button type="button" class="sml" onclick="loadCfg(d.Sf.data2)">Apply</button><br></div>
|
||||
<hr>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button>
|
||||
</form>
|
||||
<div id="toast"></div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -14,10 +14,12 @@
|
||||
</head>
|
||||
<body onload="d.getElementsByName('PIN')[0].focus()">
|
||||
<form id="form_s" name="Sf" method="post">
|
||||
<div class="sec">
|
||||
<h2>Please enter settings PIN code</h2>
|
||||
<input type="password" name="PIN" size="4" maxlength="4" minlength="4" pattern="[0-9]*" inputmode="numeric" autofocus>
|
||||
<hr>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Submit</button>
|
||||
</div>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,101 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
|
||||
<title>Pin Info</title>
|
||||
<script>
|
||||
// load common.js with retry on error
|
||||
(function loadFiles() {
|
||||
const l = document.createElement('script');
|
||||
l.src = 'common.js';
|
||||
l.onload = () => loadResources(['style.css'], S); // load style.css then call S()
|
||||
l.onerror = () => setTimeout(loadFiles, 100);
|
||||
document.head.appendChild(l);
|
||||
})();
|
||||
var pinsTimer=null, gpioInfo={};
|
||||
function S() {
|
||||
getLoc();
|
||||
loadJS(getURL('/settings/s.js?p=11'), false, ()=>{
|
||||
d.um_p = [];
|
||||
d.rsvd = [];
|
||||
d.ro_gpio = [];
|
||||
d.max_gpio = 50;
|
||||
d.touch = [];
|
||||
}, ()=>{
|
||||
// Load extended GPIO info and start pin polling
|
||||
loadPins();
|
||||
pinsTimer = setInterval(loadPins, 250);
|
||||
});
|
||||
}
|
||||
|
||||
function B(){window.open(getURL('/settings'),'_self');} // back button
|
||||
|
||||
function getOwnerName(o,t,n) {
|
||||
// Use firmware-provided name if available
|
||||
if(n) return n;
|
||||
if(!o) return "System"; // no owner provided
|
||||
if(o===0x85){ return getBtnTypeName(t); } // button pin
|
||||
return "UM #"+o;
|
||||
}
|
||||
function getBtnTypeName(t) {
|
||||
var n=["None","Reserved","Push","Push Inv","Switch","PIR","Touch","Analog","Analog Inv","Touch Switch"];
|
||||
var label = n[t] || "?";
|
||||
return 'Button <span style="font-size:10px;color:#888">'+label+'</span>';
|
||||
}
|
||||
function getCaps(p,c) {
|
||||
var r=[];
|
||||
// Use touch info from settings endpoint
|
||||
if(d.touch && d.touch.includes(p)) r.push("Touch");
|
||||
if(d.ro_gpio && d.ro_gpio.includes(p)) r.push("Input Only");
|
||||
// Use other caps from JSON (Analog, Boot, Input Only)
|
||||
if(c&0x02) r.push("Analog");
|
||||
if(c&0x08) r.push("Flash Boot");
|
||||
if(c&0x10) r.push("Bootstrap");
|
||||
return r.length?r.join(", "):"-";
|
||||
}
|
||||
function loadPins() {
|
||||
fetch(getURL('/json/pins'),{method:'get'})
|
||||
.then(r=>r.json())
|
||||
.then(j=>{
|
||||
var cn="",pins=j.pins||[];
|
||||
if(!pins.length) {
|
||||
cn="No pins available.";
|
||||
}else{
|
||||
cn='<table><tr><th>Pin</th><th>Used by</th><th>Pin Notes</th></tr>';
|
||||
for(var p of pins){
|
||||
var st=""; // button state indicator
|
||||
var rv=""; // raw value (touch / analog)
|
||||
if(typeof p.s!=='undefined'){
|
||||
st='<span class="bs" style="background:'+(p.s?'#0B4':'#666')+'"></span> '; // button state dot, gray=off, green=on
|
||||
if(typeof p.r!=='undefined') rv=' <span class="rv">'+p.r+'</span>'; // add raw touch reading if available
|
||||
}
|
||||
var ow=p.a?getOwnerName(p.o, p.t, p.n):(d.um_p && d.um_p.includes(p.p)) ? "Usermod":'<span style="color:#08d">Available</span>';
|
||||
//if(typeof p.u!=='undefined')ow+=p.u?' (PU)':' (No PU)';
|
||||
cn+='<tr><td>GPIO'+p.p+'</td><td>'+st+ow+rv+'</td><td>'+getCaps(p.p,p.c||0)+'</td></tr>';
|
||||
}
|
||||
cn+='</table>';
|
||||
}
|
||||
gId('pins').innerHTML=cn;
|
||||
})
|
||||
.catch(e=>{gId('pins').innerHTML='Error loading pin info';});
|
||||
}
|
||||
</script>
|
||||
<style>
|
||||
body{text-align:center;background:#222;margin:auto;padding:10px;max-width: 550px}
|
||||
table{width:100%;border-collapse:collapse;margin:10px 0;font-size:14px;border-radius:6px;overflow:hidden;}
|
||||
th,td{padding:8px;border:3px solid #444;color:#fff}
|
||||
th{background:#444}
|
||||
tr:nth-child(even){background:#222}
|
||||
tr:nth-child(odd){background:#111}
|
||||
.bs{display:inline-block;width:14px;height:14px;border-radius:50%} /* button state dot */
|
||||
.rv{display:inline-block;font-size:10px;color:#888;min-width:6ch;text-align:right;} /* raw value (touch / analog) */
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<button type="button" onclick="B()">Back</button>
|
||||
<h2>Pin Info</h2>
|
||||
<div id="pins">Loading...</div>
|
||||
<button type="button" onclick="B()">Back</button>
|
||||
</body>
|
||||
</html>
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
|
||||
<meta charset="utf-8">
|
||||
<title>Misc Settings</title>
|
||||
<title>Security & Update Setup</title>
|
||||
<style> html { visibility: hidden; } </style> <!-- prevent white & ugly display while loading, unhidden in loadResources() -->
|
||||
<script>
|
||||
// load common.js with retry on error
|
||||
@@ -40,12 +40,13 @@
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<form id="form_s" name="Sf" method="post">
|
||||
<div class="toprow">
|
||||
<div class="helpB"><button type="button" onclick="H('features/settings/#security-settings')">?</button></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button><hr>
|
||||
</div>
|
||||
<h2>Security & Update setup</h2>
|
||||
<form id="form_s" name="Sf" method="post">
|
||||
<div class="toprow">
|
||||
<div class="helpB"><button type="button" onclick="H('features/settings/#security-settings')">?</button></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button><hr>
|
||||
</div>
|
||||
<h2>Security & Update Setup</h2>
|
||||
<div class="sec">
|
||||
Settings PIN: <input type="password" id="PIN" name="PIN" size="4" maxlength="4" minlength="4" onkeydown="checkNum(this)" pattern="[0-9]*" inputmode="numeric" title="Please enter a 4 digit number"><br>
|
||||
<div class="warn">⚠ Unencrypted transmission. Be prudent when selecting PIN, do NOT use your banking, door, SIM, etc. pin!</div><br>
|
||||
Lock wireless (OTA) software update: <input type="checkbox" name="NO"><br>
|
||||
@@ -58,14 +59,16 @@
|
||||
Factory reset: <input type="checkbox" name="RS"><br>
|
||||
All settings and presets will be erased.<br><br>
|
||||
<div class="warn">⚠ Unencrypted transmission. An attacker on the same network can intercept form data!</div>
|
||||
<span id="OTA"><hr>
|
||||
</div>
|
||||
<div class="sec" id="OTA">
|
||||
<h3>Software Update</h3>
|
||||
<button type="button" onclick="U()">Manual OTA Update</button><br>
|
||||
<div id="aOTA">Enable ArduinoOTA: <input type="checkbox" name="AO"></div>
|
||||
Only allow update from same network/WiFi: <input type="checkbox" name="SU"><br>
|
||||
<i class="warn">⚠ If you are using multiple VLANs (i.e. IoT or guest network) either set PIN or disable this option.<br>
|
||||
Disabling this option will make your device less secure.</i><br></span>
|
||||
<hr id="backup">
|
||||
</div>
|
||||
<div class="sec" id="backup">
|
||||
<h3>Backup & Restore</h3>
|
||||
<div class="warn">⚠ Restoring presets/configuration will OVERWRITE your current presets/configuration.<br>
|
||||
Incorrect upload or configuration may require a factory reset or re-flashing of your ESP.<br>
|
||||
@@ -74,14 +77,16 @@
|
||||
<div>Restore presets<br><input type="file" name="data" accept=".json"> <button type="button" onclick="uploadFile(d.Sf.data,'/presets.json');">Upload</button><br></div><br>
|
||||
<a class="btn lnk" id="bckpresets" href="/cfg.json" download="cfg">Backup configuration</a><br>
|
||||
<div>Restore configuration<br><input type="file" name="data2" accept=".json"> <button type="button" onclick="uploadFile(d.Sf.data2,'/cfg.json');">Upload</button><br></div>
|
||||
<hr>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>About</h3>
|
||||
<a href="https://github.com/wled-dev/WLED/" target="_blank">WLED</a> version ##VERSION##<!-- Autoreplaced from package.json --><br><br>
|
||||
<a href="https://kno.wled.ge/about/contributors/" target="_blank">Contributors, dependencies and special thanks</a><br>
|
||||
A huge thank you to everyone who helped me create WLED!<br><br>
|
||||
(c) 2016-2024 Christian Schwinne <br>
|
||||
<i>Licensed under the <a href="https://github.com/wled-dev/WLED/blob/main/LICENSE" target="_blank">EUPL v1.2 license</a></i><br><br>
|
||||
Installed version: <span class="sip">WLED ##VERSION##</span><hr>
|
||||
Installed version: <span class="sip">WLED ##VERSION##</span>
|
||||
</div>
|
||||
<div id="toast"></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button>
|
||||
</form>
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
}
|
||||
function hideDMXInput(){gId("dmxInput").style.display="none";}
|
||||
function hideNoDMXInput(){gId("dmxInputOff").style.display="none";}
|
||||
function hideNoDMXOutput(){gId("dmxOnOffOutput").style.display="none";}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
@@ -59,15 +60,21 @@
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button><hr>
|
||||
</div>
|
||||
<h2>Sync setup</h2>
|
||||
<div class="sec">
|
||||
<h3>WLED Broadcast</h3>
|
||||
UDP Port: <input name="UP" type="number" min="1" max="65535" class="d5" required><br>
|
||||
2nd Port: <input name="U2" type="number" min="1" max="65535" class="d5" required><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>ESP-NOW</h3>
|
||||
<div id="NoESPNOW" class="hide">
|
||||
<i class="warn">ESP-NOW support is disabled.<br></i>
|
||||
<i class="warn">Disabled. Enable ESP-NOW in WiFi settings.<br></i>
|
||||
</div>
|
||||
<div id="ESPNOW">
|
||||
Use ESP-NOW sync: <input type="checkbox" name="EN"><br><i>(in AP mode or no WiFi)</i><br>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Sync groups</h3>
|
||||
<input name="GS" id="GS" type="number" style="display: none;"><!-- hidden inputs for bitwise group checkboxes -->
|
||||
<input name="GR" id="GR" type="number" style="display: none;">
|
||||
@@ -106,9 +113,13 @@ Use ESP-NOW sync: <input type="checkbox" name="EN"><br><i>(in AP mode or no WiFi
|
||||
<td><input type="checkbox" id="R8" name="R8"></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Receive</h3>
|
||||
<nowrap><input type="checkbox" name="RB">Brightness,</nowrap> <nowrap><input type="checkbox" name="RC">Color,</nowrap> <nowrap><input type="checkbox" name="RX">Effects,</nowrap> <nowrap>and <input type="checkbox" name="RP">Palette</nowrap><br>
|
||||
<input type="checkbox" name="SO"> Segment options, <input type="checkbox" name="SG"> bounds
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Send</h3>
|
||||
Enable Sync on start: <input type="checkbox" name="SS"><br>
|
||||
Send notifications on direct change: <input type="checkbox" name="SD"><br>
|
||||
@@ -117,11 +128,13 @@ Send Alexa notifications: <input type="checkbox" name="SA"><br>
|
||||
Send Philips Hue change notifications: <input type="checkbox" name="SH"><br>
|
||||
UDP packet retransmissions: <input name="UR" type="number" min="0" max="30" class="d5" required><br><br>
|
||||
<i>Reboot required to apply changes. </i>
|
||||
<hr class="sml">
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Instance List</h3>
|
||||
Enable instance list: <input type="checkbox" name="NL"><br>
|
||||
Make this instance discoverable: <input type="checkbox" name="NB">
|
||||
<hr class="sml">
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Realtime</h3>
|
||||
Receive UDP realtime: <input type="checkbox" name="RD"><br>
|
||||
Use main segment only: <input type="checkbox" name="MO"><br>
|
||||
@@ -168,12 +181,13 @@ Realtime LED offset: <input name="WO" type="number" min="-255" max="255" require
|
||||
DMX Port: <input name="IDMP" type="number" min="1" max="2"><br/>
|
||||
</div>
|
||||
<div id="dmxInputOff">
|
||||
<br><em style="color:darkorange">This firmware build does not include DMX Input support. <br></em>
|
||||
<br><i class="warn">This firmware build does not include DMX Input support. <br></i>
|
||||
</div>
|
||||
<div id="dmxOnOff2">
|
||||
<br><em style="color:darkorange">This firmware build does not include DMX output support. <br></em>
|
||||
<div id="dmxOnOffOutput">
|
||||
<br><i class="warn">This firmware build does not include DMX output support. <br></i>
|
||||
</div>
|
||||
<hr class="sml">
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Alexa Voice Assistant</h3>
|
||||
<div id="NoAlexa" class="hide">
|
||||
<i class="warn">This firmware build does not include Alexa support.<br></i><br>
|
||||
@@ -183,13 +197,15 @@ Emulate Alexa device: <input type="checkbox" name="AL"><br>
|
||||
Alexa invocation name: <input type="text" name="AI" maxlength="32"><br>
|
||||
Also emulate devices to call the first <input name="AP" type="number" class="s" min="0" max="9"> presets<br><br>
|
||||
</div>
|
||||
<hr class="sml">
|
||||
<div class="warn">⚠ <b>MQTT and Hue sync all connect to external hosts!<br>
|
||||
</div>
|
||||
|
||||
<div class="warn">⚠ <b>MQTT and Hue sync connect to external hosts!<br>
|
||||
This may impact the responsiveness of WLED.</b><br>
|
||||
</div>
|
||||
For best results, only use one of these services at a time.<br>
|
||||
(alternatively, connect a second ESP to them and use the UDP sync)
|
||||
<hr class="sml">
|
||||
|
||||
<div class="sec">
|
||||
<h3>MQTT</h3>
|
||||
<div id="NoMQTT" class="hide">
|
||||
<i class="warn">This firmware build does not include MQTT support.<br></i>
|
||||
@@ -209,6 +225,8 @@ Publish on button press: <input type="checkbox" name="BM"><br>
|
||||
Retain brightness & color messages: <input type="checkbox" name="RT"><br>
|
||||
<i>Reboot required to apply changes. </i><a href="https://kno.wled.ge/interfaces/mqtt/" target="_blank">MQTT info</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Philips Hue</h3>
|
||||
<div id="NoHue" class="hide">
|
||||
<em class="warn">This firmware build does not include Philips Hue support.<br></em>
|
||||
@@ -226,6 +244,8 @@ Hue Bridge IP:<br>
|
||||
(when first connecting)<br>
|
||||
Hue status: <span class="sip"> Disabled in this build </span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Serial</h3>
|
||||
<div id="NoSerial" class="hide">
|
||||
<em class="warn">This firmware build does not support Serial interface.<br></em>
|
||||
@@ -244,6 +264,7 @@ Baud rate:
|
||||
</select><br>
|
||||
<i>Keep at 115200 to use Improv. Some boards may not support high rates.</i>
|
||||
</div>
|
||||
</div>
|
||||
<hr>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button>
|
||||
</form>
|
||||
|
||||
+262
-92
@@ -8,6 +8,13 @@
|
||||
<script>
|
||||
var el=false;
|
||||
var ms=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
|
||||
var timerCount = 0;
|
||||
var maxTimers;
|
||||
var presets = {};
|
||||
var sortedPresetOptions = '';
|
||||
const TIMER_SUNRISE = 255;
|
||||
const TIMER_SUNSET = 254;
|
||||
const TIMER_WEEKDAYS_ALL = 255;
|
||||
// load common.js with retry on error
|
||||
(function loadFiles() {
|
||||
const l = document.createElement('script');
|
||||
@@ -19,13 +26,63 @@
|
||||
|
||||
function S() {
|
||||
getLoc();
|
||||
populatePresets(true);
|
||||
loadJS(getURL('/settings/s.js?p=5'), false, ()=>{BTa();}, ()=>{
|
||||
updLatLon();
|
||||
Cs();
|
||||
FC();
|
||||
}); // If we set async false, file is loaded and executed, then next statement is processed
|
||||
});
|
||||
if (loc) d.Sf.action = getURL('/settings/time');
|
||||
}
|
||||
function populatePresets(fromls) {
|
||||
let json = null;
|
||||
if (fromls) {
|
||||
try {
|
||||
json = JSON.parse(localStorage.getItem("wledP"));
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
if (!json) {
|
||||
showToast("Please visit the main UI first to load presets", true);
|
||||
return;
|
||||
}
|
||||
|
||||
onPresetsLoaded(json);
|
||||
}
|
||||
function onPresetsLoaded(json) {
|
||||
presets = json;
|
||||
delete presets["0"];
|
||||
bSPO();
|
||||
pMP();
|
||||
rTOPO();
|
||||
rBPO();
|
||||
}
|
||||
function bSPO() { // buildSortedPresetOptions
|
||||
sortedPresetOptions = '';
|
||||
for (var p of Object.entries(presets)) {
|
||||
var id = p[0];
|
||||
var name = p[1].n || ("Preset " + id);
|
||||
sortedPresetOptions += `<option value="${id}">${id}: ${name}</option>`;
|
||||
}
|
||||
}
|
||||
function sPSV(sel, value, attrName) { // setPresetSelectValue
|
||||
var v = (value === undefined || value === null || value === "") ? "0" : String(value);
|
||||
sel.setAttribute(attrName, v);
|
||||
sel.value = v;
|
||||
if (sel.value === "") sel.value = "0";
|
||||
}
|
||||
function rPS(sel, presetOpts, attrName) { // refreshPresetSelect
|
||||
var currentVal = sel.value;
|
||||
var initialVal = sel.getAttribute(attrName);
|
||||
var val = currentVal;
|
||||
if ((val === "" || val === "0") && initialVal !== null && initialVal !== "" && initialVal !== "0") {
|
||||
val = initialVal;
|
||||
}
|
||||
if (val === "") val = "0";
|
||||
sel.innerHTML = presetOpts;
|
||||
sel.value = val;
|
||||
if (sel.value === "" && initialVal !== null && initialVal !== "") sel.value = initialVal;
|
||||
if (sel.value === "") sel.value = "0";
|
||||
}
|
||||
function expand(o,i)
|
||||
{
|
||||
var t = gId("WD"+i);
|
||||
@@ -35,79 +92,189 @@
|
||||
function Cs() { gId("cac").style.display=(gN("OL").checked)?"block":"none"; }
|
||||
function BTa()
|
||||
{
|
||||
var ih="<thead><tr><th>En.</th><th>Hour</th><th>Minute</th><th>Preset</th><th></th></tr></thead>";
|
||||
for (i=0;i<8;i++) {
|
||||
ih+=`<tr><td><input name="W${i}" id="W${i}" type="hidden"><input id="W${i}0" type="checkbox"></td>
|
||||
<td><input name="H${i}" class="xs" type="number" min="0" max="24"></td>
|
||||
<td><input name="N${i}" class="xs" type="number" min="0" max="59"></td>
|
||||
<td><input name="T${i}" class="s" type="number" min="0" max="250"></td>
|
||||
<td><div id="CB${i}" onclick="expand(this,${i})" class="cal">📅</div></td></tr>`;
|
||||
ih+=`<tr><td colspan=5><div id="WD${i}" style="display:none;background-color:#444;"><hr>Run on weekdays`;
|
||||
ih+=`<table><tr><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th><th>S</th></tr><tr>`
|
||||
for (j=1;j<8;j++) ih+=`<td><input id="W${i}${j}" type="checkbox"></td>`;
|
||||
ih+=`</tr></table>from <select name="M${i}">`;
|
||||
for (j=0;j<12;j++) ih+=`<option value="${j+1}">${ms[j]}</option>`;
|
||||
ih+=`</select><input name="D${i}" class="xs" type="number" min="1" max="31"></input> to <select name="P${i}">`;
|
||||
for (j=0;j<12;j++) ih+=`<option value="${j+1}">${ms[j]}</option>`;
|
||||
ih+=`</select><input name="E${i}" class="xs" type="number" min="1" max="31"></input>
|
||||
<hr></div></td></tr>`;
|
||||
}
|
||||
ih+=`<tr><td><input name="W8" id="W8" type="hidden"><input id="W80" type="checkbox"></td>
|
||||
<td>Sunrise<input name="H8" value="255" type="hidden"></td>
|
||||
<td><input name="N8" class="xs" type="number" min="-59" max="59"></td>
|
||||
<td><input name="T8" class="s" type="number" min="0" max="250"></td>
|
||||
<td><div id="CB8" onclick="expand(this,8)" class="cal">📅</div></td></tr><tr><td colspan=5>`;
|
||||
ih+=`<div id="WD8" style="display:none;background-color:#444;"><hr><table><tr><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th><th>S</th></tr><tr>`;
|
||||
for (j=1;j<8;j++) ih+=`<td><input id="W8${j}" type="checkbox"></td>`;
|
||||
ih+="</tr></table><hr></div></td></tr>";
|
||||
ih+=`<tr><td><input name="W9" id="W9" type="hidden"><input id="W90" type="checkbox"></td>
|
||||
<td>Sunset<input name="H9" value="255" type="hidden"></td>
|
||||
<td><input name="N9" class="xs" type="number" min="-59" max="59"></td>
|
||||
<td><input name="T9" class="s" type="number" min="0" max="250"></td>
|
||||
<td><div id="CB9" onclick="expand(this,9)" class="cal">📅</div></td></tr><tr><td colspan=5>`;
|
||||
ih+=`<div id="WD9" style="display:none;background-color:#444;"><hr><table><tr><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th><th>S</th></tr><tr>`;
|
||||
for (j=1;j<8;j++) ih+=`<td><input id="W9${j}" type="checkbox"></td>`;
|
||||
ih+="</tr></table><hr></div></td></tr>";
|
||||
gId("TMT").innerHTML=ih;
|
||||
timerCount = 0;
|
||||
gId("TMT").innerHTML = "<thead><tr><th>En.</th><th>Type</th><th>Hour</th><th>Minute</th><th></th></tr></thead>";
|
||||
}
|
||||
function FC()
|
||||
{
|
||||
for(i=0;i<10;i++)
|
||||
{
|
||||
let wd = gId("W"+i).value;
|
||||
for(j=0;j<8;j++) {
|
||||
gId("W"+i+j).checked=wd>>j&1;
|
||||
function addTimerRow(hour, minute, preset, weekdays, monthStart, dayStart, monthEnd, dayEnd) {
|
||||
if (timerCount >= maxTimers) return;
|
||||
var i = timerCount++;
|
||||
var isSunrise = (hour === TIMER_SUNRISE);
|
||||
var isSunset = (hour === TIMER_SUNSET);
|
||||
var isSpecial = isSunrise || isSunset;
|
||||
if (hour === undefined) hour = 0;
|
||||
if (minute === undefined) minute = 0;
|
||||
if (preset === undefined) preset = 0;
|
||||
if (weekdays === undefined) weekdays = TIMER_WEEKDAYS_ALL;
|
||||
if (monthStart === undefined) monthStart = 1;
|
||||
if (dayStart === undefined) dayStart = 1;
|
||||
if (monthEnd === undefined) monthEnd = 12;
|
||||
if (dayEnd === undefined) dayEnd = 31;
|
||||
var enabled = weekdays & 1;
|
||||
var dow = weekdays >> 1;
|
||||
var container = gId("TMT");
|
||||
var hourVal = isSpecial ? 0 : hour;
|
||||
var presetOpts = '<option value="0">Delete Timer</option>' + sortedPresetOptions;
|
||||
|
||||
var weekdayTable = '<table class="tw"><tr><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th><th>S</th></tr><tr>';
|
||||
for (j=1;j<8;j++) weekdayTable += `<td><input id="W${i}${j}" type="checkbox" ${(dow>>(j-1))&1?'checked':''}></td>`;
|
||||
weekdayTable += '</tr></table>';
|
||||
|
||||
var dateRange = `<div id="DR${i}" class="tdr"><span class="tdf">from <select name="M${i}">`;
|
||||
for (j=0;j<12;j++) dateRange += `<option value="${j+1}" ${monthStart==j+1?'selected':''}>${ms[j]}</option>`;
|
||||
dateRange += `</select><input name="D${i}" class="xs" type="number" min="1" max="31" value="${dayStart}"></span><span class="tdf">to <select name="P${i}">`;
|
||||
for (j=0;j<12;j++) dateRange += `<option value="${j+1}" ${monthEnd==j+1?'selected':''}>${ms[j]}</option>`;
|
||||
dateRange += `</select><input name="E${i}" class="xs" type="number" min="1" max="31" value="${dayEnd}"></span></div>`;
|
||||
|
||||
var timerMain = `
|
||||
<tr>
|
||||
<td>
|
||||
<input name="W${i}" id="W${i}" type="hidden">
|
||||
<input id="W${i}0" type="checkbox" ${enabled ? "checked" : ""}>
|
||||
</td><td>
|
||||
<select id="TS${i}" class="s" onchange="TT(${i})">
|
||||
<option value="0" ${!isSpecial ? "selected" : ""}>Regular</option>
|
||||
<option value="${TIMER_SUNRISE}" ${isSunrise ? "selected" : ""}>Sunrise</option>
|
||||
<option value="${TIMER_SUNSET}" ${isSunset ? "selected" : ""}>Sunset</option>
|
||||
</select><br>
|
||||
</td><td>
|
||||
<input ${isSpecial ? "" : 'name="H'+i+'"'} id="H${i}" class="s" type="number" min="0" max="24" value="${hourVal}" ${isSpecial ? "disabled" : ""}>
|
||||
</td>
|
||||
<td><input name="N${i}" id="N${i}" class="l" type="number" min="${isSpecial ? -120 : 0}" max="${isSpecial ? 120 : 59}" value="${minute}"></td>
|
||||
<td><div id="CB${i}" onclick="expand(this,${i})" class="cal">📅</div></td>
|
||||
</tr><tr>
|
||||
<td colspan="5">
|
||||
<select name="T${i}" id="T${i}" class="s">${presetOpts}</select>
|
||||
</td>
|
||||
</tr><tr><td colspan="5"><hr></td></tr>
|
||||
`;
|
||||
|
||||
var timerExpanded = `
|
||||
<tr>
|
||||
<td colspan="5">
|
||||
<div id="WD${i}" style="display:none;background-color:#444;">
|
||||
<hr>Run on weekdays
|
||||
${weekdayTable}
|
||||
${dateRange}
|
||||
<hr>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
|
||||
container.insertAdjacentHTML("beforeend", timerMain + timerExpanded);
|
||||
var timerPresetSel = gId("T"+i);
|
||||
sPSV(timerPresetSel, preset, "data-preset");
|
||||
}
|
||||
function TT(i) {
|
||||
var sel = gId("TS"+i);
|
||||
var hour = gId("H"+i);
|
||||
var min = gId("N"+i);
|
||||
var isSpecial = sel.value != 0;
|
||||
hour.disabled = isSpecial;
|
||||
if (isSpecial) {
|
||||
// Save current hour value before switching to sunrise/sunset
|
||||
hour.setAttribute("data-regular-hour", hour.value);
|
||||
hour.removeAttribute("name");
|
||||
min.min = -120;
|
||||
min.max = 120;
|
||||
} else {
|
||||
// Restore saved hour value when switching back to regular
|
||||
var savedHour = hour.getAttribute("data-regular-hour");
|
||||
if (savedHour !== null && savedHour !== "") {
|
||||
hour.value = savedHour;
|
||||
}
|
||||
if ((wd&254) != 254 || (i<8 && (gN("M"+i).value != 1 || gN("D"+i).value != 1 || gN("P"+i).value != 12 || gN("E"+i).value != 31))) {
|
||||
expand(gId("CB"+i),i); //expand macros with custom DOW or date range set
|
||||
hour.setAttribute("name", "H"+i);
|
||||
min.min = 0;
|
||||
min.max = 59;
|
||||
if (min.value < 0 || min.value > 59) min.value = 0;
|
||||
}
|
||||
}
|
||||
function pMP() { // populateMacroPresets
|
||||
var presetOpts = '<option value="0">Default Action</option>' + sortedPresetOptions;
|
||||
var fields = ['A0','A1','MC','MN'];
|
||||
for (var f of fields) {
|
||||
var inp = gN(f);
|
||||
if (!inp) continue;
|
||||
var val = inp.getAttribute("data-preset-value");
|
||||
if (val === null || val === "") val = inp.value;
|
||||
if (inp.tagName === "SELECT") {
|
||||
sPSV(inp, val, "data-preset-value");
|
||||
rPS(inp, presetOpts, "data-preset-value");
|
||||
} else {
|
||||
var sel = document.createElement('select');
|
||||
sel.name = f;
|
||||
sel.className = inp.className;
|
||||
sel.required = inp.required;
|
||||
sPSV(sel, val, "data-preset-value");
|
||||
rPS(sel, presetOpts, "data-preset-value");
|
||||
inp.parentNode.replaceChild(sel, inp);
|
||||
}
|
||||
}
|
||||
}
|
||||
function rTOPO() { // refreshTimerPresetOptions
|
||||
var presetOpts = '<option value="0">Delete Timer</option>' + sortedPresetOptions;
|
||||
for (var i=0; i<timerCount; i++) {
|
||||
var sel = gId("T"+i);
|
||||
if (!sel) continue;
|
||||
rPS(sel, presetOpts, "data-preset");
|
||||
}
|
||||
}
|
||||
function rBPO() { // refreshButtonPresetOptions
|
||||
var presetOpts = '<option value="0">Default Action</option>' + sortedPresetOptions;
|
||||
var container = gId("macros");
|
||||
if (!container) return;
|
||||
var sels = container.querySelectorAll('select[name^="MP"],select[name^="ML"],select[name^="MD"]');
|
||||
for (var sel of sels) {
|
||||
rPS(sel, presetOpts, "data-preset");
|
||||
}
|
||||
}
|
||||
function Wd()
|
||||
{
|
||||
a = [0,0,0,0,0,0,0,0,0,0];
|
||||
for (i=0; i<10; i++) {
|
||||
m=1;
|
||||
for(j=0;j<8;j++) { a[i]+=gId(("W"+i)+j).checked*m; m*=2;}
|
||||
gId("W"+i).value=a[i];
|
||||
for (i=0; i<timerCount; i++) {
|
||||
var m=1, val=0;
|
||||
for(j=0;j<8;j++) { val+=gId(("W"+i)+j).checked*m; m*=2;}
|
||||
gId("W"+i).value=val;
|
||||
var sel = gId("TS"+i);
|
||||
var hour = gId("H"+i);
|
||||
if (sel && sel.value != 0) {
|
||||
// Re-add name attribute, remove disabled, and set value for sunrise/sunset before submission
|
||||
hour.setAttribute("name", "H"+i);
|
||||
hour.disabled = false;
|
||||
hour.value = sel.value;
|
||||
}
|
||||
}
|
||||
if (d.Sf.LTR.value==="S") { d.Sf.LT.value = -1*parseFloat(d.Sf.LT.value); }
|
||||
if (d.Sf.LNR.value==="W") { d.Sf.LN.value = -1*parseFloat(d.Sf.LN.value); }
|
||||
}
|
||||
function addRow(i,p,l,d) {
|
||||
var t = gId("macros"); // table
|
||||
var rCnt = t.rows.length; // get the number of rows.
|
||||
var tr = t.insertRow(rCnt); // table row.
|
||||
var b = String.fromCharCode((i<10?48:55)+i);
|
||||
var td = document.createElement('td'); // TABLE DEFINITION.
|
||||
td = tr.insertCell(0);
|
||||
td.innerHTML = `Button ${i}:`;
|
||||
td = tr.insertCell(1);
|
||||
td.innerHTML = `<input name="MP${b}" type="number" class="s" min="0" max="250" value="${p}" required>`;
|
||||
td = tr.insertCell(2);
|
||||
td.innerHTML = `<input name="ML${b}" type="number" class="s" min="0" max="250" value="${l}" required>`;
|
||||
td = tr.insertCell(3);
|
||||
td.innerHTML = `<input name="MD${b}" type="number" class="s" min="0" max="250" value="${d}" required>`;
|
||||
var presetOpts = '<option value="0">Default Action</option>' + sortedPresetOptions;
|
||||
var buttonBlock = document.createElement('div');
|
||||
buttonBlock.className = 'bb';
|
||||
buttonBlock.innerHTML = `
|
||||
<div class="bh">Button ${i}</div>
|
||||
<div class="bs">
|
||||
<div class="ba">
|
||||
<label>Push/Switch</label>
|
||||
<select name="MP${b}" class="s" required>${presetOpts}</select>
|
||||
</div>
|
||||
<div class="ba">
|
||||
<label>Short (on→off)</label>
|
||||
<select name="ML${b}" class="s" required>${presetOpts}</select>
|
||||
</div>
|
||||
<div class="ba">
|
||||
<label>Long (off→on)</label>
|
||||
<select name="MD${b}" class="s" required>${presetOpts}</select>
|
||||
</div>
|
||||
</div>
|
||||
<hr style="width:100%;margin:8px 0 0 0;">
|
||||
`;
|
||||
var buttonSels = buttonBlock.querySelectorAll("select");
|
||||
var buttonVals = [String(p), String(l), String(d)];
|
||||
for (var si=0; si<buttonSels.length; si++) {
|
||||
sPSV(buttonSels[si], buttonVals[si], "data-preset");
|
||||
}
|
||||
gId("macros").appendChild(buttonBlock);
|
||||
}
|
||||
function getLatLon() {
|
||||
if (!el) {
|
||||
@@ -130,12 +297,13 @@
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<form id="form_s" name="Sf" method="post" onsubmit="Wd()">
|
||||
<div class="toprow">
|
||||
<div class="helpB"><button type="button" onclick="H('features/settings/#time-settings')">?</button></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button><hr>
|
||||
</div>
|
||||
<h2>Time setup</h2>
|
||||
<form id="form_s" name="Sf" method="post" onsubmit="Wd()">
|
||||
<div class="toprow">
|
||||
<div class="helpB"><button type="button" onclick="H('features/settings/#time-settings')">?</button></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button><hr>
|
||||
</div>
|
||||
<h2>Time setup</h2>
|
||||
<div class="sec">
|
||||
Get time from NTP server: <input type="checkbox" name="NT"><br>
|
||||
<input type="text" name="NS" maxlength="32"><br>
|
||||
Use 24h format: <input type="checkbox" name="CF"><br>
|
||||
@@ -174,6 +342,8 @@
|
||||
<button type="button" id="locbtn" onclick="getLatLon()">Get location</button>
|
||||
<div><i>(opens new tab, only works in browser)</i></div>
|
||||
<div id="sun" class="times"></div>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Clock</h3>
|
||||
Analog Clock overlay: <input type="checkbox" name="OL" onchange="Cs()"><br>
|
||||
<div id="cac">
|
||||
@@ -187,34 +357,34 @@
|
||||
Countdown Goal:<br>
|
||||
Date: <nowrap>20<input name="CY" class="xs" type="number" min="0" max="99" required>-<input name="CI" class="xs" type="number" min="1" max="12" required>-<input name="CD" class="xs" type="number" min="1" max="31" required></nowrap><br>
|
||||
Time: <nowrap><input name="CH" class="xs" type="number" min="0" max="23" required>:<input name="CM" class="xs" type="number" min="0" max="59" required>:<input name="CS" class="xs" type="number" min="0" max="59" required></nowrap><br>
|
||||
<h3>Macro presets</h3>
|
||||
<b>Macros have moved!</b><br>
|
||||
<i>Presets now also can be used as macros to save both JSON and HTTP API commands.<br>
|
||||
Just enter the preset ID below!</i>
|
||||
<i>Use 0 for the default action instead of a preset</i><br>
|
||||
Alexa On/Off Preset: <input name="A0" class="m" type="number" min="0" max="250" required> <input name="A1" class="m" type="number" min="0" max="250" required><br>
|
||||
</div>
|
||||
<hr>
|
||||
<h2>Macro Presets</h2>
|
||||
<i>Presets can be used as macros for both JSON and HTTP API commands.<br>
|
||||
Enter the preset ID below.</i>
|
||||
<i>Use 0 for the default action instead of a preset</i><br>
|
||||
<a href="https://kno.wled.ge/interfaces/json-api/" target="_blank">JSON API</a><br>
|
||||
<a href="https://kno.wled.ge/interfaces/http-api/" target="_blank">HTTP API</a><br>
|
||||
<div class="sec">
|
||||
<h3>Timer & Alexa Presets</h3>
|
||||
Countdown-Over Preset: <input name="MC" class="m" type="number" min="0" max="250" required><br>
|
||||
Timed-Light-Over Presets: <input name="MN" class="m" type="number" min="0" max="250" required><br>
|
||||
<h3>Button actions</h3>
|
||||
<table style="margin: 0 auto;" id="macros">
|
||||
<thead>
|
||||
<tr>
|
||||
<td>push<br>switch</td>
|
||||
<td>short<br>on->off</td>
|
||||
<td>long<br>off->on</td>
|
||||
<td>double<br>N/A</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</tbody>
|
||||
</table>
|
||||
Alexa On/Off Preset: <input name="A0" class="m" type="number" min="0" max="250" required> <input name="A1" class="m" type="number" min="0" max="250" required><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Button Action Presets</h3>
|
||||
<div id="macros"></div>
|
||||
<a href="https://kno.wled.ge/features/macros/#analog-button" target="_blank">Analog Button setup</a>
|
||||
<h3>Time-controlled presets</h3>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<h3>Time-Controlled Presets</h3>
|
||||
<div style="display: inline-block">
|
||||
<table id="TMT" style="min-width:330px;"></table>
|
||||
<table id="TMT" style="min-width:330px;"></table>
|
||||
<button type="button" onclick="addTimerRow()">Add Timer</button>
|
||||
</div>
|
||||
<hr>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button>
|
||||
</form>
|
||||
</div>
|
||||
<hr>
|
||||
<button type="button" onclick="B()">Back</button><button type="submit">Save</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+21
-16
@@ -100,7 +100,7 @@
|
||||
str += `${lb}: <input class="agi" type="number" id=${fk} value=${s[i]}><br>`;
|
||||
} else if (t === 'string')
|
||||
{
|
||||
str += `${lb}:<br><input class="agi" id=${fk} value=${s[i]}><br>`;
|
||||
str += `${lb}:<br><input class="agi sml" id=${fk} value=${s[i]}><br>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,25 +219,28 @@
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<form id="form_s" name="Sf" method="post">
|
||||
<div class="toprow">
|
||||
<div class="helpB"><button type="button" onclick="H('features/settings/#user-interface-settings')">?</button></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="button" onclick="Save()">Save</button><br>
|
||||
<span id="lssuc" style="color:green; display:none">✔ Local UI settings saved!</span>
|
||||
<span id="lserr" style="color:red; display:none">⚠ Could not access local storage. Make sure it is enabled in your browser.</span><hr>
|
||||
</div>
|
||||
<h2>Web Setup</h2>
|
||||
Server description: <input type="text" name="DS" maxlength="32"><br>
|
||||
<!-- Sync button toggles both send and receive: <input type="checkbox" name="ST"><br> -->
|
||||
<form id="form_s" name="Sf" method="post">
|
||||
<div class="toprow">
|
||||
<div class="helpB"><button type="button" onclick="H('features/settings/#user-interface-settings')">?</button></div>
|
||||
<button type="button" onclick="B()">Back</button><button type="button" onclick="Save()">Save</button><br>
|
||||
<span id="lssuc" style="color:green; display:none">✔ Local UI settings saved!</span>
|
||||
<span id="lserr" style="color:red; display:none">⚠ Could not access local storage. Make sure it is enabled in your browser.</span><hr>
|
||||
</div>
|
||||
<h2>User Interface</h2>
|
||||
<div class="sec">
|
||||
Device Name: <input type="text" name="DS" maxlength="32"><br>
|
||||
Enable simplified UI: <input type="checkbox" name="SU"><br>
|
||||
</div>
|
||||
<div class="sec">
|
||||
<i>The following UI customization settings are unique both to the WLED device and this browser.<br>
|
||||
You will need to set them again if using a different browser, device or WLED IP address.<br>
|
||||
Refresh the main UI to apply changes.</i><br>
|
||||
|
||||
|
||||
<div id="gen">Loading settings...</div>
|
||||
|
||||
|
||||
<h3>UI Appearance</h3>
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_labels" class="agi cb"><br>
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_idsort" class="agi cb"><br>
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_pcmbot" class="agi cb"><br>
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_pid" class="agi cb"><br>
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_seglen" class="agi cb"><br>
|
||||
@@ -246,10 +249,13 @@
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_fxdef" class="agi cb"><br>
|
||||
<span class="l"></span>: <input type="number" min=0 max=250 step=1 id="comp_on" class="agi"><br>
|
||||
<span class="l"></span>: <input type="number" min=0 max=250 step=1 id="comp_off" class="agi"><br>
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_idsort" class="agi cb"><br>
|
||||
I hate dark mode: <input type="checkbox" id="dm" onchange="UI()"><br>
|
||||
<span id="idonthateyou" style="display:none"><i>Why would you? </i>🥺<br></span>
|
||||
<span class="l"></span>: <input type="number" min=0.0 max=1.0 step=0.01 id="theme_alpha_tab" class="agi"><br>
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_css" class="agi cb"><br>
|
||||
<div id="skin">Custom CSS: <input type="file" name="data" accept=".css"> <input type="button" value="Upload" onclick="uploadFile(d.Sf.data,'/skin.css');"><br></div>
|
||||
|
||||
<h3>UI Background</h3>
|
||||
<span class="l"></span>: <input type="number" min=0.0 max=1.0 step=0.01 id="theme_alpha_bg" class="agi"><br>
|
||||
<span class="l"></span>: <input type="text" id="theme_color_bg" maxlength="9" class="agi"><br>
|
||||
BG image: <input type="file" id="theme_bg_img" accept="image/*" onchange="ownBg(this)"> <input type="button" value="Remove" onclick="removeBgImg()"><br>
|
||||
@@ -265,10 +271,9 @@
|
||||
<span class="l"></span>: <input type="checkbox" id="theme_bg_rndBlur" class="agi cb" onchange="randomBg()"><br>
|
||||
</div>
|
||||
<input id="theme_base" class="agi" style="display:none">
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_css" class="agi cb"><br>
|
||||
<div id="skin">Custom CSS: <input type="file" name="data" accept=".css"> <input type="button" value="Upload" onclick="uploadFile(d.Sf.data,'/skin.css');"><br></div>
|
||||
<span class="l"></span>: <input type="checkbox" id="comp_hdays" class="agi cb"><br>
|
||||
<div id="holidays">Holidays: <input type="file" name="data2" accept=".json"> <input type="button" value="Upload" onclick="uploadFile(d.Sf.data2,'/holidays.json');"><br></div>
|
||||
</div>
|
||||
<div id="toast"></div>
|
||||
<hr><button type="button" onclick="cLS()">Clear local storage</button>
|
||||
<hr><button type="button" onclick="B()">Back</button><button type="button" onclick="Save()">Save</button>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user