Compare commits
6
Commits
97df6e3cbe
...
47f4eba0d6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47f4eba0d6 | ||
|
|
d32f3d69cf | ||
|
|
4b623bb156 | ||
|
|
9a04d28ecf | ||
|
|
89f996096c | ||
|
|
df43820acd |
No files matched your search
@@ -0,0 +1,8 @@
|
||||
# The following lines of boilerplate have to be in your project's CMakeLists
|
||||
# in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
|
||||
idf_build_set_property(MINIMAL_BUILD ON)
|
||||
project(led_driver)
|
||||
@@ -0,0 +1,80 @@
|
||||
# Top-level Makefile for the led_strip ESP-IDF project.
|
||||
# Thin wrapper around idf.py. Runs on Linux, macOS (bash) and Windows (GNU make with cmd.exe or sh).
|
||||
#
|
||||
# Override any variable on the command line, for example:
|
||||
# make flash PORT=/dev/ttyUSB0 # Linux
|
||||
# make flash PORT=/dev/cu.usbmodem101 # macOS
|
||||
# make flash PORT=COM4 # Windows
|
||||
|
||||
ifeq ($(OS),Windows_NT)
|
||||
HOST_OS := windows
|
||||
HOME_DIR := $(USERPROFILE)
|
||||
DEFAULT_PORT := COM3
|
||||
else
|
||||
HOST_OS := $(shell uname -s)
|
||||
HOME_DIR := $(HOME)
|
||||
ifeq ($(HOST_OS),Darwin)
|
||||
DEFAULT_PORT := /dev/cu.usbmodem101
|
||||
else
|
||||
DEFAULT_PORT := /dev/ttyACM0
|
||||
endif
|
||||
endif
|
||||
|
||||
IDF_PATH ?= $(HOME_DIR)/.espressif/v6.1/esp-idf
|
||||
IDF_PYTHON_ENV_PATH ?= $(HOME_DIR)/.espressif/python_env/idf6.1_py3.12_env
|
||||
PORT ?= $(DEFAULT_PORT)
|
||||
|
||||
export IDF_PATH
|
||||
export IDF_PYTHON_ENV_PATH
|
||||
|
||||
# Run idf.py in a shell that has sourced ESP-IDF's environment script (sets PATH and toolchains).
|
||||
ifeq ($(HOST_OS),windows)
|
||||
define idf
|
||||
cmd /c "$(subst /,\,$(IDF_PATH))\export.bat && idf.py $(1)"
|
||||
endef
|
||||
else
|
||||
define idf
|
||||
bash -c '. "$(IDF_PATH)/export.sh" >/dev/null 2>&1 && idf.py $(1)'
|
||||
endef
|
||||
endif
|
||||
|
||||
.PHONY: all build flash monitor flash-monitor menuconfig clean fullclean help
|
||||
|
||||
all: build
|
||||
|
||||
build:
|
||||
$(call idf,build)
|
||||
|
||||
flash: build
|
||||
$(call idf,-p $(PORT) flash)
|
||||
|
||||
monitor:
|
||||
$(call idf,-p $(PORT) monitor)
|
||||
|
||||
flash-monitor: build
|
||||
$(call idf,-p $(PORT) flash monitor)
|
||||
|
||||
menuconfig:
|
||||
$(call idf,menuconfig)
|
||||
|
||||
clean:
|
||||
$(call idf,clean)
|
||||
|
||||
fullclean:
|
||||
$(call idf,fullclean)
|
||||
|
||||
help:
|
||||
@echo Targets:
|
||||
@echo build Build the firmware
|
||||
@echo flash Build, then flash to the board on PORT
|
||||
@echo monitor Open the serial monitor on PORT
|
||||
@echo flash-monitor Build, flash, then open the serial monitor
|
||||
@echo menuconfig Open the project configuration menu
|
||||
@echo clean Remove build outputs
|
||||
@echo fullclean Delete the build directory entirely
|
||||
@echo help Show this help
|
||||
|
||||
# Over-the-air update over Wi-Fi (the access point or the home network): make ota HOST=<ip or name>
|
||||
ota: HOST ?= led.local
|
||||
ota: build
|
||||
python3 tools/ota.py $(HOST)
|
||||
@@ -50,3 +50,35 @@ led-driver/
|
||||
## Further reading
|
||||
|
||||
- **`docs/API.md`** — JSON message fields as used in examples (`pattern`, `colors`, …). The Pi app may send **short keys** (`p`, `c`, …); behaviour matches once normalised on device.
|
||||
|
||||
## C++ app (ESP-IDF)
|
||||
|
||||
The `cpp` branch is an ESP-IDF app for the ESP32-C3 at the repo root (`CMakeLists.txt`, `main/`, `web/`). It drives a 119-LED WS2812 strip on GPIO 10 (set in `main/patterns.cpp`).
|
||||
|
||||
### Web UI, access point and Wi-Fi client
|
||||
|
||||
The firmware runs three things at once:
|
||||
|
||||
- **Access point** `led-XXXXXX` (the last three bytes of the MAC), open, no password. Join it and browse to `http://192.168.4.1/`.
|
||||
- **Wi-Fi client**: set a network from the Settings tab (scan, pick, enter password). Credentials are saved to NVS, and the client reconnects with backoff after a drop.
|
||||
- **mDNS**: once on a network, the device answers as `http://led.local/`.
|
||||
|
||||
Patterns: solid, rainbow, chase, breathe, blink, pulse, transition and circle. The web UI is embedded in the firmware from `web/`.
|
||||
|
||||
JSON API (port 80):
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|--------|------|---------|
|
||||
| GET | `/api/status` | Current pattern and parameters, AP name, client state and IP |
|
||||
| POST | `/api/pattern` | `{"mode","c1":[r,g,b],"c2":[r,g,b],"speed_ms","brightness"}` |
|
||||
| GET | `/api/wifi` | Saved client SSID and connection state |
|
||||
| POST | `/api/wifi` | `{"ssid","password"}`: save and connect |
|
||||
| GET | `/api/wifi/scan` | Visible networks |
|
||||
|
||||
Build and flash for the ESP32-C3:
|
||||
|
||||
```bash
|
||||
. ~/.espressif/v6.1/esp-idf/export.sh
|
||||
idf.py set-target esp32c3
|
||||
idf.py build flash monitor
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
dependencies:
|
||||
espressif/cjson:
|
||||
component_hash: e788323270d90738662d66fffa910bfe1fba019bba087f01557e70c40485b469
|
||||
dependencies:
|
||||
- name: idf
|
||||
require: private
|
||||
version: '>=5.0'
|
||||
source:
|
||||
registry_url: https://components.espressif.com/
|
||||
type: service
|
||||
version: 1.7.19~2
|
||||
espressif/mdns:
|
||||
component_hash: 2fa43caa78cc170842255bc7bf71f306bc815cae12e9496bfb12372423019ac7
|
||||
dependencies:
|
||||
- name: idf
|
||||
require: private
|
||||
version: '>=5.0'
|
||||
source:
|
||||
registry_url: https://components.espressif.com/
|
||||
type: service
|
||||
version: 1.15.1
|
||||
idf:
|
||||
source:
|
||||
type: idf
|
||||
version: 6.1.0
|
||||
direct_dependencies:
|
||||
- espressif/cjson
|
||||
- espressif/mdns
|
||||
manifest_hash: d0a7e36d6cc4abacaa550a978cbc8f50812589b67060a807571ef39c1e829dfd
|
||||
target: esp32c3
|
||||
version: 3.0.0
|
||||
@@ -1,75 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
import serial
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def mpremote_base():
|
||||
"""mpremote on PATH, or same interpreter as this script (e.g. pipenv venv)."""
|
||||
exe = shutil.which("mpremote")
|
||||
if exe:
|
||||
return [exe]
|
||||
return [sys.executable, "-m", "mpremote"]
|
||||
|
||||
|
||||
print(sys.argv)
|
||||
|
||||
# Extract port (first arg if it's not a command)
|
||||
commands = ["src", "lib", "ls", "reset", "follow", "db", "test"]
|
||||
port = None
|
||||
if len(sys.argv) > 1 and sys.argv[1] not in commands:
|
||||
port = sys.argv[1]
|
||||
|
||||
|
||||
for cmd in sys.argv[1:]:
|
||||
print(cmd)
|
||||
match cmd:
|
||||
case "src":
|
||||
if port:
|
||||
subprocess.call(
|
||||
[*mpremote_base(), "connect", port, "fs", "cp", "-r", ".", ":"],
|
||||
cwd="src",
|
||||
)
|
||||
else:
|
||||
print("Error: Port required for 'src' command")
|
||||
case "lib":
|
||||
if port:
|
||||
subprocess.call([*mpremote_base(), "connect", port, "fs", "cp", "-r", "lib", ":"])
|
||||
else:
|
||||
print("Error: Port required for 'lib' command")
|
||||
case "ls":
|
||||
if port:
|
||||
subprocess.call([*mpremote_base(), "connect", port, "fs", "ls", ":"])
|
||||
else:
|
||||
print("Error: Port required for 'ls' command")
|
||||
case "reset":
|
||||
if port:
|
||||
with serial.Serial(port, baudrate=115200) as ser:
|
||||
ser.write(b'\x03\x03\x04')
|
||||
else:
|
||||
print("Error: Port required for 'reset' command")
|
||||
case "follow":
|
||||
if port:
|
||||
with serial.Serial(port, baudrate=115200) as ser:
|
||||
while True:
|
||||
if ser.in_waiting > 0: # Check if there is data in the buffer
|
||||
data = ser.readline().decode('utf-8').strip() # Read and decode the data
|
||||
print(data)
|
||||
else:
|
||||
print("Error: Port required for 'follow' command")
|
||||
case "db":
|
||||
if port:
|
||||
subprocess.call([*mpremote_base(), "connect", port, "fs", "cp", "-r", "db", ":"])
|
||||
else:
|
||||
print("Error: Port required for 'db' command")
|
||||
case "test":
|
||||
if port:
|
||||
# Single self-contained suite (tests/all.py); requires ``src`` on device first.
|
||||
subprocess.call(
|
||||
[*mpremote_base(), "connect", port, "run", "tests/all.py"]
|
||||
)
|
||||
else:
|
||||
print("Error: Port required for 'test' command")
|
||||
@@ -97,6 +97,13 @@ Presets define LED patterns with their configuration. Each preset has a name and
|
||||
- **`n3`**: Tail movement rate (LEDs per second)
|
||||
- **`n4`**: Minimum length
|
||||
|
||||
#### Gradient Wipe (`gradient_wipe`)
|
||||
One-shot: lights LEDs from `n1` to `n2` (backwards if `n1 > n2`) with a gradient from the first to the second colour, then stops.
|
||||
- **`n1`**: First LED
|
||||
- **`n2`**: Last LED
|
||||
- **`delay`**: Total time in milliseconds to sweep from `n1` to `n2`
|
||||
- **`background`**: Colour for the rest of the strip
|
||||
|
||||
## Select Messages
|
||||
|
||||
Select messages control which preset is active on which device. The format uses a list to support step synchronization.
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
|
||||
send_file # noqa: F401
|
||||
@@ -1,8 +0,0 @@
|
||||
try:
|
||||
from functools import wraps
|
||||
except ImportError: # pragma: no cover
|
||||
# MicroPython does not currently implement functools.wraps
|
||||
def wraps(wrapped):
|
||||
def _(wrapper):
|
||||
return wrapper
|
||||
return _
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,225 +0,0 @@
|
||||
try:
|
||||
import jwt
|
||||
HAS_JWT = True
|
||||
except ImportError:
|
||||
HAS_JWT = False
|
||||
try:
|
||||
import ubinascii
|
||||
except ImportError:
|
||||
import binascii as ubinascii
|
||||
try:
|
||||
import uhashlib as hashlib
|
||||
except ImportError:
|
||||
import hashlib
|
||||
try:
|
||||
import uhmac as hmac
|
||||
except ImportError:
|
||||
try:
|
||||
import hmac
|
||||
except ImportError:
|
||||
hmac = None
|
||||
import json
|
||||
|
||||
from microdot.microdot import invoke_handler
|
||||
from microdot.helpers import wraps
|
||||
|
||||
|
||||
class SessionDict(dict):
|
||||
"""A session dictionary.
|
||||
|
||||
The session dictionary is a standard Python dictionary that has been
|
||||
extended with convenience ``save()`` and ``delete()`` methods.
|
||||
"""
|
||||
def __init__(self, request, session_dict):
|
||||
super().__init__(session_dict)
|
||||
self.request = request
|
||||
|
||||
def save(self):
|
||||
"""Update the session cookie."""
|
||||
self.request.app._session.update(self.request, self)
|
||||
|
||||
def delete(self):
|
||||
"""Delete the session cookie."""
|
||||
self.request.app._session.delete(self.request)
|
||||
|
||||
|
||||
class Session:
|
||||
"""Session handling
|
||||
|
||||
:param app: The application instance.
|
||||
:param secret_key: The secret key, as a string or bytes object.
|
||||
:param cookie_options: A dictionary with cookie options to pass as
|
||||
arguments to :meth:`Response.set_cookie()
|
||||
<microdot.Response.set_cookie>`.
|
||||
"""
|
||||
secret_key = None
|
||||
|
||||
def __init__(self, app=None, secret_key=None, cookie_options=None):
|
||||
self.secret_key = secret_key
|
||||
self.cookie_options = cookie_options or {}
|
||||
if app is not None:
|
||||
self.initialize(app)
|
||||
|
||||
def initialize(self, app, secret_key=None, cookie_options=None):
|
||||
if secret_key is not None:
|
||||
self.secret_key = secret_key
|
||||
if cookie_options is not None:
|
||||
self.cookie_options = cookie_options
|
||||
if 'path' not in self.cookie_options:
|
||||
self.cookie_options['path'] = '/'
|
||||
if 'http_only' not in self.cookie_options:
|
||||
self.cookie_options['http_only'] = True
|
||||
app._session = self
|
||||
|
||||
def get(self, request):
|
||||
"""Retrieve the user session.
|
||||
|
||||
:param request: The client request.
|
||||
|
||||
The return value is a session dictionary with the data stored in the
|
||||
user's session, or ``{}`` if the session data is not available or
|
||||
invalid.
|
||||
"""
|
||||
if not self.secret_key:
|
||||
raise ValueError('The session secret key is not configured')
|
||||
if hasattr(request.g, '_session'):
|
||||
return request.g._session
|
||||
session = request.cookies.get('session')
|
||||
if session is None:
|
||||
request.g._session = SessionDict(request, {})
|
||||
return request.g._session
|
||||
request.g._session = SessionDict(request, self.decode(session))
|
||||
return request.g._session
|
||||
|
||||
def update(self, request, session):
|
||||
"""Update the user session.
|
||||
|
||||
:param request: The client request.
|
||||
:param session: A dictionary with the update session data for the user.
|
||||
|
||||
Applications would normally not call this method directly, instead they
|
||||
would use the :meth:`SessionDict.save` method on the session
|
||||
dictionary, which calls this method. For example::
|
||||
|
||||
@app.route('/')
|
||||
@with_session
|
||||
def index(request, session):
|
||||
session['foo'] = 'bar'
|
||||
session.save()
|
||||
return 'Hello, World!'
|
||||
|
||||
Calling this method adds a cookie with the updated session to the
|
||||
request currently being processed.
|
||||
"""
|
||||
if not self.secret_key:
|
||||
raise ValueError('The session secret key is not configured')
|
||||
|
||||
encoded_session = self.encode(session)
|
||||
|
||||
@request.after_request
|
||||
def _update_session(request, response):
|
||||
response.set_cookie('session', encoded_session,
|
||||
**self.cookie_options)
|
||||
return response
|
||||
|
||||
def delete(self, request):
|
||||
"""Remove the user session.
|
||||
|
||||
:param request: The client request.
|
||||
|
||||
Applications would normally not call this method directly, instead they
|
||||
would use the :meth:`SessionDict.delete` method on the session
|
||||
dictionary, which calls this method. For example::
|
||||
|
||||
@app.route('/')
|
||||
@with_session
|
||||
def index(request, session):
|
||||
session.delete()
|
||||
return 'Hello, World!'
|
||||
|
||||
Calling this method adds a cookie removal header to the request
|
||||
currently being processed.
|
||||
"""
|
||||
@request.after_request
|
||||
def _delete_session(request, response):
|
||||
response.delete_cookie('session', **self.cookie_options)
|
||||
return response
|
||||
|
||||
def encode(self, payload, secret_key=None):
|
||||
"""Encode session data using JWT if available, otherwise use simple HMAC."""
|
||||
if HAS_JWT:
|
||||
return jwt.encode(payload, secret_key or self.secret_key,
|
||||
algorithm='HS256')
|
||||
else:
|
||||
# Simple encoding for MicroPython: base64(json) + HMAC signature
|
||||
key = (secret_key or self.secret_key).encode() if isinstance(secret_key or self.secret_key, str) else (secret_key or self.secret_key)
|
||||
payload_json = json.dumps(payload)
|
||||
payload_b64 = ubinascii.b2a_base64(payload_json.encode()).decode().strip()
|
||||
|
||||
# Create HMAC signature
|
||||
if hmac:
|
||||
# Use hmac module if available
|
||||
h = hmac.new(key, payload_json.encode(), hashlib.sha256)
|
||||
else:
|
||||
# Fallback: simple SHA256(key + message)
|
||||
h = hashlib.sha256(key + payload_json.encode())
|
||||
signature = ubinascii.b2a_base64(h.digest()).decode().strip()
|
||||
|
||||
return f"{payload_b64}.{signature}"
|
||||
|
||||
def decode(self, session, secret_key=None):
|
||||
"""Decode session data using JWT if available, otherwise use simple HMAC."""
|
||||
if HAS_JWT:
|
||||
try:
|
||||
payload = jwt.decode(session, secret_key or self.secret_key,
|
||||
algorithms=['HS256'])
|
||||
except jwt.exceptions.PyJWTError: # pragma: no cover
|
||||
return {}
|
||||
return payload
|
||||
else:
|
||||
try:
|
||||
# Simple decoding for MicroPython
|
||||
if '.' not in session:
|
||||
return {}
|
||||
|
||||
payload_b64, signature = session.rsplit('.', 1)
|
||||
payload_json = ubinascii.a2b_base64(payload_b64).decode()
|
||||
|
||||
# Verify HMAC signature
|
||||
key = (secret_key or self.secret_key).encode() if isinstance(secret_key or self.secret_key, str) else (secret_key or self.secret_key)
|
||||
if hmac:
|
||||
# Use hmac module if available
|
||||
h = hmac.new(key, payload_json.encode(), hashlib.sha256)
|
||||
else:
|
||||
# Fallback: simple SHA256(key + message)
|
||||
h = hashlib.sha256(key + payload_json.encode())
|
||||
expected_signature = ubinascii.b2a_base64(h.digest()).decode().strip()
|
||||
|
||||
if signature != expected_signature:
|
||||
return {}
|
||||
|
||||
return json.loads(payload_json)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def with_session(f):
|
||||
"""Decorator that passes the user session to the route handler.
|
||||
|
||||
The session dictionary is passed to the decorated function as an argument
|
||||
after the request object. Example::
|
||||
|
||||
@app.route('/')
|
||||
@with_session
|
||||
def index(request, session):
|
||||
return 'Hello, World!'
|
||||
|
||||
Note that the decorator does not save the session. To update the session,
|
||||
call the :func:`session.save() <microdot.session.SessionDict.save>` method.
|
||||
"""
|
||||
@wraps(f)
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
return await invoke_handler(
|
||||
f, request, request.app._session.get(request), *args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
@@ -1,70 +0,0 @@
|
||||
from utemplate import recompile
|
||||
|
||||
_loader = None
|
||||
|
||||
|
||||
class Template:
|
||||
"""A template object.
|
||||
|
||||
:param template: The filename of the template to render, relative to the
|
||||
configured template directory.
|
||||
"""
|
||||
@classmethod
|
||||
def initialize(cls, template_dir='templates',
|
||||
loader_class=recompile.Loader):
|
||||
"""Initialize the templating subsystem.
|
||||
|
||||
:param template_dir: the directory where templates are stored. This
|
||||
argument is optional. The default is to load
|
||||
templates from a *templates* subdirectory.
|
||||
:param loader_class: the ``utemplate.Loader`` class to use when loading
|
||||
templates. This argument is optional. The default
|
||||
is the ``recompile.Loader`` class, which
|
||||
automatically recompiles templates when they
|
||||
change.
|
||||
"""
|
||||
global _loader
|
||||
_loader = loader_class(None, template_dir)
|
||||
|
||||
def __init__(self, template):
|
||||
if _loader is None: # pragma: no cover
|
||||
self.initialize()
|
||||
#: The name of the template
|
||||
self.name = template
|
||||
self.template = _loader.load(template)
|
||||
|
||||
def generate(self, *args, **kwargs):
|
||||
"""Return a generator that renders the template in chunks, with the
|
||||
given arguments."""
|
||||
return self.template(*args, **kwargs)
|
||||
|
||||
def render(self, *args, **kwargs):
|
||||
"""Render the template with the given arguments and return it as a
|
||||
string."""
|
||||
return ''.join(self.generate(*args, **kwargs))
|
||||
|
||||
def generate_async(self, *args, **kwargs):
|
||||
"""Return an asynchronous generator that renders the template in
|
||||
chunks, using the given arguments."""
|
||||
class sync_to_async_iter():
|
||||
def __init__(self, iter):
|
||||
self.iter = iter
|
||||
|
||||
def __aiter__(self):
|
||||
return self
|
||||
|
||||
async def __anext__(self):
|
||||
try:
|
||||
return next(self.iter)
|
||||
except StopIteration:
|
||||
raise StopAsyncIteration
|
||||
|
||||
return sync_to_async_iter(self.generate(*args, **kwargs))
|
||||
|
||||
async def render_async(self, *args, **kwargs):
|
||||
"""Render the template with the given arguments asynchronously and
|
||||
return it as a string."""
|
||||
response = ''
|
||||
async for chunk in self.generate_async(*args, **kwargs):
|
||||
response += chunk
|
||||
return response
|
||||
@@ -1,231 +0,0 @@
|
||||
import binascii
|
||||
import hashlib
|
||||
from microdot import Request, Response
|
||||
from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception
|
||||
from microdot.helpers import wraps
|
||||
|
||||
|
||||
class WebSocketError(Exception):
|
||||
"""Exception raised when an error occurs in a WebSocket connection."""
|
||||
pass
|
||||
|
||||
|
||||
class WebSocket:
|
||||
"""A WebSocket connection object.
|
||||
|
||||
An instance of this class is sent to handler functions to manage the
|
||||
WebSocket connection.
|
||||
"""
|
||||
CONT = 0
|
||||
TEXT = 1
|
||||
BINARY = 2
|
||||
CLOSE = 8
|
||||
PING = 9
|
||||
PONG = 10
|
||||
|
||||
#: Specify the maximum message size that can be received when calling the
|
||||
#: ``receive()`` method. Messages with payloads that are larger than this
|
||||
#: size will be rejected and the connection closed. Set to 0 to disable
|
||||
#: the size check (be aware of potential security issues if you do this),
|
||||
#: or to -1 to use the value set in
|
||||
#: ``Request.max_body_length``. The default is -1.
|
||||
#:
|
||||
#: Example::
|
||||
#:
|
||||
#: WebSocket.max_message_length = 4 * 1024 # up to 4KB messages
|
||||
max_message_length = -1
|
||||
|
||||
def __init__(self, request):
|
||||
self.request = request
|
||||
self.closed = False
|
||||
|
||||
async def handshake(self):
|
||||
response = self._handshake_response()
|
||||
await self.request.sock[1].awrite(
|
||||
b'HTTP/1.1 101 Switching Protocols\r\n')
|
||||
await self.request.sock[1].awrite(b'Upgrade: websocket\r\n')
|
||||
await self.request.sock[1].awrite(b'Connection: Upgrade\r\n')
|
||||
await self.request.sock[1].awrite(
|
||||
b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n')
|
||||
|
||||
async def receive(self):
|
||||
"""Receive a message from the client."""
|
||||
while True:
|
||||
opcode, payload = await self._read_frame()
|
||||
send_opcode, data = self._process_websocket_frame(opcode, payload)
|
||||
if send_opcode: # pragma: no cover
|
||||
await self.send(data, send_opcode)
|
||||
elif data: # pragma: no branch
|
||||
return data
|
||||
|
||||
async def send(self, data, opcode=None):
|
||||
"""Send a message to the client.
|
||||
|
||||
:param data: the data to send, given as a string or bytes.
|
||||
:param opcode: a custom frame opcode to use. If not given, the opcode
|
||||
is ``TEXT`` or ``BINARY`` depending on the type of the
|
||||
data.
|
||||
"""
|
||||
frame = self._encode_websocket_frame(
|
||||
opcode or (self.TEXT if isinstance(data, str) else self.BINARY),
|
||||
data)
|
||||
await self.request.sock[1].awrite(frame)
|
||||
|
||||
async def close(self):
|
||||
"""Close the websocket connection."""
|
||||
if not self.closed: # pragma: no cover
|
||||
self.closed = True
|
||||
await self.send(b'', self.CLOSE)
|
||||
|
||||
def _handshake_response(self):
|
||||
connection = False
|
||||
upgrade = False
|
||||
websocket_key = None
|
||||
for header, value in self.request.headers.items():
|
||||
h = header.lower()
|
||||
if h == 'connection':
|
||||
connection = True
|
||||
if 'upgrade' not in value.lower():
|
||||
return self.request.app.abort(400)
|
||||
elif h == 'upgrade':
|
||||
upgrade = True
|
||||
if not value.lower() == 'websocket':
|
||||
return self.request.app.abort(400)
|
||||
elif h == 'sec-websocket-key':
|
||||
websocket_key = value
|
||||
if not connection or not upgrade or not websocket_key:
|
||||
return self.request.app.abort(400)
|
||||
d = hashlib.sha1(websocket_key.encode())
|
||||
d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
|
||||
return binascii.b2a_base64(d.digest())[:-1]
|
||||
|
||||
@classmethod
|
||||
def _parse_frame_header(cls, header):
|
||||
fin = header[0] & 0x80
|
||||
opcode = header[0] & 0x0f
|
||||
if fin == 0 or opcode == cls.CONT: # pragma: no cover
|
||||
raise WebSocketError('Continuation frames not supported')
|
||||
has_mask = header[1] & 0x80
|
||||
length = header[1] & 0x7f
|
||||
if length == 126:
|
||||
length = -2
|
||||
elif length == 127:
|
||||
length = -8
|
||||
return fin, opcode, has_mask, length
|
||||
|
||||
def _process_websocket_frame(self, opcode, payload):
|
||||
if opcode == self.TEXT:
|
||||
payload = payload.decode()
|
||||
elif opcode == self.BINARY:
|
||||
pass
|
||||
elif opcode == self.CLOSE:
|
||||
raise WebSocketError('Websocket connection closed')
|
||||
elif opcode == self.PING:
|
||||
return self.PONG, payload
|
||||
elif opcode == self.PONG: # pragma: no branch
|
||||
return None, None
|
||||
return None, payload
|
||||
|
||||
@classmethod
|
||||
def _encode_websocket_frame(cls, opcode, payload):
|
||||
frame = bytearray()
|
||||
frame.append(0x80 | opcode)
|
||||
if opcode == cls.TEXT:
|
||||
payload = payload.encode()
|
||||
if len(payload) < 126:
|
||||
frame.append(len(payload))
|
||||
elif len(payload) < (1 << 16):
|
||||
frame.append(126)
|
||||
frame.extend(len(payload).to_bytes(2, 'big'))
|
||||
else:
|
||||
frame.append(127)
|
||||
frame.extend(len(payload).to_bytes(8, 'big'))
|
||||
frame.extend(payload)
|
||||
return frame
|
||||
|
||||
async def _read_frame(self):
|
||||
header = await self.request.sock[0].read(2)
|
||||
if len(header) != 2: # pragma: no cover
|
||||
raise WebSocketError('Websocket connection closed')
|
||||
fin, opcode, has_mask, length = self._parse_frame_header(header)
|
||||
if length == -2:
|
||||
length = await self.request.sock[0].read(2)
|
||||
length = int.from_bytes(length, 'big')
|
||||
elif length == -8:
|
||||
length = await self.request.sock[0].read(8)
|
||||
length = int.from_bytes(length, 'big')
|
||||
max_allowed_length = Request.max_body_length \
|
||||
if self.max_message_length == -1 else self.max_message_length
|
||||
if length > max_allowed_length:
|
||||
raise WebSocketError('Message too large')
|
||||
if has_mask: # pragma: no cover
|
||||
mask = await self.request.sock[0].read(4)
|
||||
payload = await self.request.sock[0].read(length)
|
||||
if has_mask: # pragma: no cover
|
||||
payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload))
|
||||
return opcode, payload
|
||||
|
||||
|
||||
async def websocket_upgrade(request):
|
||||
"""Upgrade a request handler to a websocket connection.
|
||||
|
||||
This function can be called directly inside a route function to process a
|
||||
WebSocket upgrade handshake, for example after the user's credentials are
|
||||
verified. The function returns the websocket object::
|
||||
|
||||
@app.route('/echo')
|
||||
async def echo(request):
|
||||
if not authenticate_user(request):
|
||||
abort(401)
|
||||
ws = await websocket_upgrade(request)
|
||||
while True:
|
||||
message = await ws.receive()
|
||||
await ws.send(message)
|
||||
"""
|
||||
ws = WebSocket(request)
|
||||
await ws.handshake()
|
||||
|
||||
@request.after_request
|
||||
async def after_request(request, response):
|
||||
return Response.already_handled
|
||||
|
||||
return ws
|
||||
|
||||
|
||||
def websocket_wrapper(f, upgrade_function):
|
||||
@wraps(f)
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
ws = await upgrade_function(request)
|
||||
try:
|
||||
await f(request, ws, *args, **kwargs)
|
||||
except OSError as exc:
|
||||
if exc.errno not in MUTED_SOCKET_ERRORS: # pragma: no cover
|
||||
raise
|
||||
except WebSocketError:
|
||||
pass
|
||||
except Exception as exc:
|
||||
print_exception(exc)
|
||||
finally: # pragma: no cover
|
||||
try:
|
||||
await ws.close()
|
||||
except Exception:
|
||||
pass
|
||||
return Response.already_handled
|
||||
return wrapper
|
||||
|
||||
|
||||
def with_websocket(f):
|
||||
"""Decorator to make a route a WebSocket endpoint.
|
||||
|
||||
This decorator is used to define a route that accepts websocket
|
||||
connections. The route then receives a websocket object as a second
|
||||
argument that it can use to send and receive messages::
|
||||
|
||||
@app.route('/echo')
|
||||
@with_websocket
|
||||
async def echo(request, ws):
|
||||
while True:
|
||||
message = await ws.receive()
|
||||
await ws.send(message)
|
||||
"""
|
||||
return websocket_wrapper(f, websocket_upgrade)
|
||||
Whitespace-only changes.
@@ -1,14 +0,0 @@
|
||||
class Loader:
|
||||
|
||||
def __init__(self, pkg, dir):
|
||||
if dir == ".":
|
||||
dir = ""
|
||||
else:
|
||||
dir = dir.replace("/", ".") + "."
|
||||
if pkg and pkg != "__main__":
|
||||
dir = pkg + "." + dir
|
||||
self.p = dir
|
||||
|
||||
def load(self, name):
|
||||
name = name.replace(".", "_")
|
||||
return __import__(self.p + name, None, None, (name,)).render
|
||||
@@ -1,21 +0,0 @@
|
||||
# (c) 2014-2020 Paul Sokolovsky. MIT license.
|
||||
try:
|
||||
from uos import stat, remove
|
||||
except:
|
||||
from os import stat, remove
|
||||
from . import source
|
||||
|
||||
|
||||
class Loader(source.Loader):
|
||||
|
||||
def load(self, name):
|
||||
o_path = self.pkg_path + self.compiled_path(name)
|
||||
i_path = self.pkg_path + self.dir + "/" + name
|
||||
try:
|
||||
o_stat = stat(o_path)
|
||||
i_stat = stat(i_path)
|
||||
if i_stat[8] > o_stat[8]:
|
||||
# input file is newer, remove output to force recompile
|
||||
remove(o_path)
|
||||
finally:
|
||||
return super().load(name)
|
||||
@@ -1,188 +0,0 @@
|
||||
# (c) 2014-2019 Paul Sokolovsky. MIT license.
|
||||
from . import compiled
|
||||
|
||||
|
||||
class Compiler:
|
||||
|
||||
START_CHAR = "{"
|
||||
STMNT = "%"
|
||||
STMNT_END = "%}"
|
||||
EXPR = "{"
|
||||
EXPR_END = "}}"
|
||||
|
||||
def __init__(self, file_in, file_out, indent=0, seq=0, loader=None):
|
||||
self.file_in = file_in
|
||||
self.file_out = file_out
|
||||
self.loader = loader
|
||||
self.seq = seq
|
||||
self._indent = indent
|
||||
self.stack = []
|
||||
self.in_literal = False
|
||||
self.flushed_header = False
|
||||
self.args = "*a, **d"
|
||||
|
||||
def indent(self, adjust=0):
|
||||
if not self.flushed_header:
|
||||
self.flushed_header = True
|
||||
self.indent()
|
||||
self.file_out.write("def render%s(%s):\n" % (str(self.seq) if self.seq else "", self.args))
|
||||
self.stack.append("def")
|
||||
self.file_out.write(" " * (len(self.stack) + self._indent + adjust))
|
||||
|
||||
def literal(self, s):
|
||||
if not s:
|
||||
return
|
||||
if not self.in_literal:
|
||||
self.indent()
|
||||
self.file_out.write('yield """')
|
||||
self.in_literal = True
|
||||
self.file_out.write(s.replace('"', '\\"'))
|
||||
|
||||
def close_literal(self):
|
||||
if self.in_literal:
|
||||
self.file_out.write('"""\n')
|
||||
self.in_literal = False
|
||||
|
||||
def render_expr(self, e):
|
||||
self.indent()
|
||||
self.file_out.write('yield str(' + e + ')\n')
|
||||
|
||||
def parse_statement(self, stmt):
|
||||
tokens = stmt.split(None, 1)
|
||||
if tokens[0] == "args":
|
||||
if len(tokens) > 1:
|
||||
self.args = tokens[1]
|
||||
else:
|
||||
self.args = ""
|
||||
elif tokens[0] == "set":
|
||||
self.indent()
|
||||
self.file_out.write(stmt[3:].strip() + "\n")
|
||||
elif tokens[0] == "include":
|
||||
if not self.flushed_header:
|
||||
# If there was no other output, we still need a header now
|
||||
self.indent()
|
||||
tokens = tokens[1].split(None, 1)
|
||||
args = ""
|
||||
if len(tokens) > 1:
|
||||
args = tokens[1]
|
||||
if tokens[0][0] == "{":
|
||||
self.indent()
|
||||
# "1" as fromlist param is uPy hack
|
||||
self.file_out.write('_ = __import__(%s.replace(".", "_"), None, None, 1)\n' % tokens[0][2:-2])
|
||||
self.indent()
|
||||
self.file_out.write("yield from _.render(%s)\n" % args)
|
||||
return
|
||||
|
||||
with self.loader.input_open(tokens[0][1:-1]) as inc:
|
||||
self.seq += 1
|
||||
c = Compiler(inc, self.file_out, len(self.stack) + self._indent, self.seq)
|
||||
inc_id = self.seq
|
||||
self.seq = c.compile()
|
||||
self.indent()
|
||||
self.file_out.write("yield from render%d(%s)\n" % (inc_id, args))
|
||||
elif len(tokens) > 1:
|
||||
if tokens[0] == "elif":
|
||||
assert self.stack[-1] == "if"
|
||||
self.indent(-1)
|
||||
self.file_out.write(stmt + ":\n")
|
||||
else:
|
||||
self.indent()
|
||||
self.file_out.write(stmt + ":\n")
|
||||
self.stack.append(tokens[0])
|
||||
else:
|
||||
if stmt.startswith("end"):
|
||||
assert self.stack[-1] == stmt[3:]
|
||||
self.stack.pop(-1)
|
||||
elif stmt == "else":
|
||||
assert self.stack[-1] == "if"
|
||||
self.indent(-1)
|
||||
self.file_out.write("else:\n")
|
||||
else:
|
||||
assert False
|
||||
|
||||
def parse_line(self, l):
|
||||
while l:
|
||||
start = l.find(self.START_CHAR)
|
||||
if start == -1:
|
||||
self.literal(l)
|
||||
return
|
||||
self.literal(l[:start])
|
||||
self.close_literal()
|
||||
sel = l[start + 1]
|
||||
#print("*%s=%s=" % (sel, EXPR))
|
||||
if sel == self.STMNT:
|
||||
end = l.find(self.STMNT_END)
|
||||
assert end > 0
|
||||
stmt = l[start + len(self.START_CHAR + self.STMNT):end].strip()
|
||||
self.parse_statement(stmt)
|
||||
end += len(self.STMNT_END)
|
||||
l = l[end:]
|
||||
if not self.in_literal and l == "\n":
|
||||
break
|
||||
elif sel == self.EXPR:
|
||||
# print("EXPR")
|
||||
end = l.find(self.EXPR_END)
|
||||
assert end > 0
|
||||
expr = l[start + len(self.START_CHAR + self.EXPR):end].strip()
|
||||
self.render_expr(expr)
|
||||
end += len(self.EXPR_END)
|
||||
l = l[end:]
|
||||
else:
|
||||
self.literal(l[start])
|
||||
l = l[start + 1:]
|
||||
|
||||
def header(self):
|
||||
self.file_out.write("# Autogenerated file\n")
|
||||
|
||||
def compile(self):
|
||||
self.header()
|
||||
for l in self.file_in:
|
||||
self.parse_line(l)
|
||||
self.close_literal()
|
||||
return self.seq
|
||||
|
||||
|
||||
class Loader(compiled.Loader):
|
||||
|
||||
def __init__(self, pkg, dir):
|
||||
super().__init__(pkg, dir)
|
||||
self.dir = dir
|
||||
if pkg == "__main__":
|
||||
# if pkg isn't really a package, don't bother to use it
|
||||
# it means we're running from "filesystem directory", not
|
||||
# from a package.
|
||||
pkg = None
|
||||
|
||||
self.pkg_path = ""
|
||||
if pkg:
|
||||
p = __import__(pkg)
|
||||
if isinstance(p.__path__, str):
|
||||
# uPy
|
||||
self.pkg_path = p.__path__
|
||||
else:
|
||||
# CPy
|
||||
self.pkg_path = p.__path__[0]
|
||||
self.pkg_path += "/"
|
||||
|
||||
def input_open(self, template):
|
||||
path = self.pkg_path + self.dir + "/" + template
|
||||
return open(path)
|
||||
|
||||
def compiled_path(self, template):
|
||||
return self.dir + "/" + template.replace(".", "_") + ".py"
|
||||
|
||||
def load(self, name):
|
||||
try:
|
||||
return super().load(name)
|
||||
except (OSError, ImportError):
|
||||
pass
|
||||
|
||||
compiled_path = self.pkg_path + self.compiled_path(name)
|
||||
|
||||
f_in = self.input_open(name)
|
||||
f_out = open(compiled_path, "w")
|
||||
c = Compiler(f_in, f_out, loader=self)
|
||||
c.compile()
|
||||
f_in.close()
|
||||
f_out.close()
|
||||
return super().load(name)
|
||||
@@ -0,0 +1,6 @@
|
||||
idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" "presets.cpp"
|
||||
"effects_util.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp"
|
||||
PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event
|
||||
esp_timer nvs_flash esp_http_server esp_http_client cjson mdns esp_hw_support app_update esp_app_format lwip
|
||||
INCLUDE_DIRS "."
|
||||
EMBED_TXTFILES "../web/index.html" "../web/app.js" "../web/style.css")
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <cstring>
|
||||
|
||||
#include "ddp.h"
|
||||
#include "esp_log.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "lwip/sockets.h"
|
||||
#include "patterns.h"
|
||||
|
||||
static const char *TAG = "ddp";
|
||||
|
||||
// Header: flags, sequence, data type, destination, data offset (4), data length (2); with the timecode
|
||||
// flag, 4 more bytes follow. Version 1 is flags bits 6-7 = 01.
|
||||
#define DDP_FLAG_VER1 0x40
|
||||
#define DDP_VER_MASK 0xC0
|
||||
#define DDP_FLAG_TIMECODE 0x10
|
||||
#define DDP_HEADER 10
|
||||
|
||||
static uint32_t be32(const uint8_t *p)
|
||||
{
|
||||
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
|
||||
}
|
||||
|
||||
static uint16_t be16(const uint8_t *p)
|
||||
{
|
||||
return (uint16_t)((p[0] << 8) | p[1]);
|
||||
}
|
||||
|
||||
static void ddp_task(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
|
||||
if (sock < 0) {
|
||||
ESP_LOGE(TAG, "socket failed");
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
struct sockaddr_in addr = {};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(DDP_PORT);
|
||||
addr.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
||||
ESP_LOGE(TAG, "bind to port %d failed", DDP_PORT);
|
||||
close(sock);
|
||||
vTaskDelete(NULL);
|
||||
return;
|
||||
}
|
||||
ESP_LOGI(TAG, "DDP listening on UDP port %d", DDP_PORT);
|
||||
|
||||
uint8_t buf[1500];
|
||||
while (true) {
|
||||
int n = recv(sock, buf, sizeof(buf), 0);
|
||||
if (n < DDP_HEADER) {
|
||||
continue;
|
||||
}
|
||||
uint8_t flags = buf[0];
|
||||
if ((flags & DDP_VER_MASK) != DDP_FLAG_VER1) {
|
||||
continue;
|
||||
}
|
||||
size_t hdr = DDP_HEADER + ((flags & DDP_FLAG_TIMECODE) ? 4 : 0);
|
||||
if ((size_t)n < hdr) {
|
||||
continue;
|
||||
}
|
||||
uint8_t dtype = buf[2];
|
||||
if (dtype != 0x00 && dtype != 0x01) {
|
||||
continue; // only 8-bit RGB
|
||||
}
|
||||
uint32_t offset = be32(buf + 4);
|
||||
size_t len = be16(buf + 8);
|
||||
if (len > (size_t)n - hdr) {
|
||||
len = (size_t)n - hdr;
|
||||
}
|
||||
patterns_ddp_write(offset, buf + hdr, len, (flags & 0x01) != 0);
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t ddp_start(void)
|
||||
{
|
||||
BaseType_t ok = xTaskCreate(ddp_task, "ddp", 4096, NULL, 4, NULL);
|
||||
return ok == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* DDP (Distributed Display Protocol) receiver: RGB pixels over UDP, port 4048. Packets fill the strip
|
||||
* while they keep arriving (see patterns.cpp).
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
|
||||
#define DDP_PORT 4048
|
||||
|
||||
/** @brief Start listening for DDP packets. */
|
||||
esp_err_t ddp_start(void);
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Pattern engine shared by the effect files. Ports the MicroPython led-driver patterns: each pattern
|
||||
* gets the same preset fields (colours, delay d, brightness b, auto a, reverse, n1..n6) and renders into
|
||||
* a shadow frame, which patterns.cpp shows (with crossfade) on the strip.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "patterns.h"
|
||||
|
||||
#define FX_LEDS_MAX 512 // largest strip the engine supports (per-LED buffers are sized at run time)
|
||||
|
||||
struct rgb {
|
||||
int r, g, b;
|
||||
};
|
||||
|
||||
// Per-frame view handed to a pattern
|
||||
struct fx_t {
|
||||
int n; // LEDs in the strip
|
||||
const preset_t *pr; // the running preset (copy)
|
||||
uint32_t now; // ms now
|
||||
uint32_t t; // ms since the pattern started
|
||||
rgb *px; // shadow frame, physical order; persists between frames (n entries)
|
||||
};
|
||||
|
||||
// Per-pattern state. Patterns run one at a time, so one instance is reset on each select.
|
||||
struct flake_t { int pos, ci, wj; };
|
||||
struct star_t { int h, ci; };
|
||||
struct spark_t { int p, lv, ci; };
|
||||
struct bug_t { int pos, ph; };
|
||||
struct drop_t { int pos, age; };
|
||||
|
||||
struct st_t {
|
||||
bool done; // one-shot finished: hold the frame
|
||||
bool started; // one-time setup done
|
||||
uint32_t last, aux; // timers
|
||||
uint32_t t0; // start time
|
||||
int ci; // colour index
|
||||
int phase, dir, pause; // animation state
|
||||
int head, tail; // moving head / tail
|
||||
int p1, p2; // comet heads
|
||||
int cnt; // counters
|
||||
int sc; // chase step count
|
||||
int stage; // state machine stage
|
||||
int flash_idx;
|
||||
int rise; // flame
|
||||
int cj[8]; // flame cluster jitter
|
||||
uint32_t breath_origin, last_cluster, next_spark, spark_start;
|
||||
int spark_dur;
|
||||
bool spark_active;
|
||||
int breath_ms, lo, hi, gap_lo, gap_hi;
|
||||
bool sparks_on;
|
||||
int centers[32];
|
||||
int ncent;
|
||||
int *glow; // per-LED buffers, n entries each (see frame_alloc)
|
||||
flake_t flakes[64];
|
||||
int nflakes;
|
||||
star_t stars[8];
|
||||
int nstars;
|
||||
spark_t sparks[32];
|
||||
int nsparks;
|
||||
bug_t bugs[16];
|
||||
int nbugs;
|
||||
drop_t drops[32];
|
||||
int ndrops;
|
||||
uint8_t *on, *next_on;
|
||||
int *col_i, *next_ci;
|
||||
int *light, *dark;
|
||||
int nlight, ndark;
|
||||
float *m; // rig: position of each LED along the pattern
|
||||
int *shade; // rig: shade of each LED
|
||||
};
|
||||
|
||||
extern st_t g_st;
|
||||
|
||||
// Allocate the per-LED buffers for n LEDs (frame and pattern state). False if out of memory, in which
|
||||
// case the old buffers are kept. Call with the pattern lock held.
|
||||
bool frame_alloc(int n);
|
||||
|
||||
// Reset the pattern state for a new pattern, keeping the buffers and clearing them.
|
||||
void st_reset(void);
|
||||
|
||||
// ---- helpers ------------------------------------------------------------------------------
|
||||
|
||||
int clampi(int v, int lo, int hi);
|
||||
int fdiv(int a, int b); // floor division, as Python's //
|
||||
int pmod(int a, int m); // non-negative modulo, as Python's %
|
||||
int nz(int v, int def); // v when v > 0, else def
|
||||
rgb mk(int r, int g, int b); // clamped
|
||||
rgb ab(rgb c, int level); // c scaled by level/255
|
||||
rgb mix(rgb a, rgb b, int k); // a -> b, k 0..255
|
||||
int sgn(const fx_t &f, int v); // v, negated when reversed
|
||||
int led_at(const fx_t &f, int i); // logical index -> physical (reverse)
|
||||
void put(fx_t &f, int phys, rgb c);
|
||||
void putl(fx_t &f, int logical, rgb c);
|
||||
void fill(fx_t &f, rgb c);
|
||||
bool due(uint32_t now, uint32_t &last, uint32_t d); // true (and last += d) once d ms have passed
|
||||
uint32_t dur(const fx_t &f, int v); // ms, or quarter beats with beat_time
|
||||
int get_colours(const fx_t &f, const rgb *def, int ndef, rgb *out); // preset colours or the default
|
||||
int rnd(int lo, int hi); // random integer, inclusive
|
||||
rgb grad_at(const rgb *cols, int ncols, float t); // colour at t (0..1) along the list
|
||||
rgb wheel(int pos); // hue wheel, 0..255 -> colour
|
||||
|
||||
// Colour table for the rig patterns: shades of the colour list, at LEVELS brightness steps
|
||||
#define RIG_SHADES 16
|
||||
#define RIG_LEVELS 16
|
||||
rgb rig_entry(const fx_t &f, const rgb *cols, int ncols, int shades, int shade, int level);
|
||||
|
||||
// Pattern entry points (return true once a one-shot has finished)
|
||||
bool fx_off(fx_t &f, st_t &s);
|
||||
bool fx_on(fx_t &f, st_t &s);
|
||||
bool fx_blink(fx_t &f, st_t &s);
|
||||
bool fx_aurora(fx_t &f, st_t &s);
|
||||
bool fx_bar_graph(fx_t &f, st_t &s);
|
||||
bool fx_blizzard(fx_t &f, st_t &s);
|
||||
bool fx_candle_glow(fx_t &f, st_t &s);
|
||||
bool fx_chase(fx_t &f, st_t &s);
|
||||
bool fx_circle(fx_t &f, st_t &s);
|
||||
bool fx_clock_sweep(fx_t &f, st_t &s);
|
||||
bool fx_colour_cycle(fx_t &f, st_t &s);
|
||||
bool fx_flicker(fx_t &f, st_t &s);
|
||||
bool fx_gradient_wipe(fx_t &f, st_t &s);
|
||||
bool fx_hit(fx_t &f, st_t &s);
|
||||
bool fx_icicles(fx_t &f, st_t &s);
|
||||
bool fx_keyframes(fx_t &f, st_t &s);
|
||||
bool fx_orbit(fx_t &f, st_t &s);
|
||||
bool fx_pulse(fx_t &f, st_t &s);
|
||||
bool fx_transition(fx_t &f, st_t &s);
|
||||
bool fx_strobe_burst(fx_t &f, st_t &s);
|
||||
bool fx_plasma(fx_t &f, st_t &s);
|
||||
|
||||
bool fx_meteor(fx_t &f, st_t &s);
|
||||
bool fx_particles(fx_t &f, st_t &s);
|
||||
bool fx_sparkle(fx_t &f, st_t &s);
|
||||
bool fx_rain_drops(fx_t &f, st_t &s);
|
||||
bool fx_rime(fx_t &f, st_t &s);
|
||||
bool fx_twinkle(fx_t &f, st_t &s);
|
||||
bool fx_radiate(fx_t &f, st_t &s);
|
||||
bool fx_palette_morph(fx_t &f, st_t &s);
|
||||
bool fx_flame(fx_t &f, st_t &s);
|
||||
|
||||
bool fx_field_wave(fx_t &f, st_t &s);
|
||||
bool fx_grow(fx_t &f, st_t &s);
|
||||
bool fx_ripple(fx_t &f, st_t &s);
|
||||
bool fx_spin(fx_t &f, st_t &s);
|
||||
bool fx_sweep(fx_t &f, st_t &s);
|
||||
@@ -0,0 +1,897 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Basic and colour patterns, ported from the MicroPython led-driver (patterns folder).
|
||||
*/
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
|
||||
#include "effects.h"
|
||||
|
||||
static const rgb WHITE = { 255, 255, 255 };
|
||||
static const rgb BLACK = { 0, 0, 0 };
|
||||
|
||||
static bool first_call(st_t &s)
|
||||
{
|
||||
if (s.started) {
|
||||
return false;
|
||||
}
|
||||
s.started = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- off, on, blink ----------------------------------------------------------------------------
|
||||
|
||||
bool fx_off(fx_t &f, st_t &)
|
||||
{
|
||||
fill(f, BLACK);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool fx_on(fx_t &f, st_t &)
|
||||
{
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, &WHITE, 1, c);
|
||||
fill(f, ab(c[0], f.pr->brightness));
|
||||
(void)nc;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool fx_blink(fx_t &f, st_t &s)
|
||||
{
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, &WHITE, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
s.stage = 1; // on
|
||||
}
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (due(f.now, s.last, d)) {
|
||||
if (s.stage) {
|
||||
fill(f, ab(c[s.ci % nc], b));
|
||||
s.ci++;
|
||||
} else {
|
||||
fill(f, bgc);
|
||||
}
|
||||
s.stage = !s.stage;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- aurora ------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_aurora(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb bands_def[3] = { { 40, 200, 140 }, { 80, 120, 255 }, { 160, 80, 220 } };
|
||||
const rgb north_def[3] = { { 20, 55, 120 }, { 60, 140, 220 }, { 180, 220, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS + 1];
|
||||
bool northern = f.pr->n[6] == 1;
|
||||
int nc = get_colours(f, northern ? north_def : bands_def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
|
||||
if (!northern) {
|
||||
int bands = nz(f.pr->n[1], 3);
|
||||
int shimmer = clampi(nz(f.pr->n[2], 40), 0, 255);
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < nled; i++) {
|
||||
int idx = (((i * bands) / (nled > 0 ? nled : 1)) + s.phase / 32) % nc;
|
||||
rgb col = ab(c[idx], b);
|
||||
int w = 255 - abs(128 - ((i * 8 + s.phase) & 255)) * 2;
|
||||
w = clampi(w + shimmer, 0, 255);
|
||||
rgb px = { col.r * w / 255, col.g * w / 255, col.b * w / 255 };
|
||||
putl(f, i, px);
|
||||
}
|
||||
s.phase = pmod(s.phase + sgn(f, 1), 256);
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// Northern wave: a sine of brightness along the strip, blended through the colours
|
||||
int period = nz(f.pr->n[1], 20);
|
||||
if (period < 4) period = 4;
|
||||
int contrast = clampi(nz(f.pr->n[2], 200), 1, 255);
|
||||
int drift = nz(f.pr->n[3], 2);
|
||||
if (nc < 2) {
|
||||
c[nc] = mk(120, 180, 255);
|
||||
nc++;
|
||||
}
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
const float twopi = 6.2831853f;
|
||||
for (int i = 0; i < nled; i++) {
|
||||
float t = (i * twopi / period) + (s.phase * twopi / 256.0f);
|
||||
float w = (sinf(t) + 1.0f) * 0.5f;
|
||||
int u = (int)(w * (nc - 1) * 256.0f);
|
||||
int fi = u >> 8;
|
||||
int frac = u & 255;
|
||||
if (fi >= nc - 1) {
|
||||
fi = nc - 2;
|
||||
frac = 255;
|
||||
}
|
||||
rgb peak = ab(mix(c[fi], c[fi + 1], frac), b);
|
||||
int mixf = (int)(w * contrast * 2);
|
||||
mixf = mixf >> 1;
|
||||
if (mixf > 255) mixf = 255;
|
||||
putl(f, i, mix(bgc, peak, mixf));
|
||||
}
|
||||
s.phase = pmod(s.phase + sgn(f, drift), 256);
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// ---- bar graph ---------------------------------------------------------------------------------
|
||||
|
||||
bool fx_bar_graph(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[2] = { { 0, 255, 0 }, { 255, 80, 0 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 2, c);
|
||||
(void)nc;
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
int b = f.pr->brightness;
|
||||
int level = clampi(f.pr->n[1], 0, 100);
|
||||
int target = (f.n * level) / 100;
|
||||
rgb lit = ab(c[0], b);
|
||||
rgb unlit = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
put(f, i, i < target ? lit : unlit);
|
||||
}
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// ---- blizzard ----------------------------------------------------------------------------------
|
||||
|
||||
bool fx_blizzard(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[3] = { { 255, 255, 255 }, { 200, 230, 255 }, { 180, 210, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
int density = nz(f.pr->n[1], 90);
|
||||
int speed = nz(f.pr->n[2], 2);
|
||||
int wraw = f.pr->n[3];
|
||||
int wind = wraw <= 0 ? 0 : clampi(fdiv(wraw - 128, 20), -4, 4);
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < nled; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
if (rnd(0, 255) < density && s.nflakes < 64) {
|
||||
flake_t fl = { nled - 1, rnd(0, nc - 1), wind == 0 ? 0 : rnd(-1, 1) };
|
||||
s.flakes[s.nflakes++] = fl;
|
||||
}
|
||||
int keep = 0;
|
||||
for (int k = 0; k < s.nflakes; k++) {
|
||||
flake_t fl = s.flakes[k];
|
||||
int p = fl.pos;
|
||||
int lateral = wind + fl.wj;
|
||||
p -= sgn(f, speed);
|
||||
p += sgn(f, lateral);
|
||||
if (p < -2 || p >= nled + 2) {
|
||||
continue;
|
||||
}
|
||||
int pi = clampi(p, 0, nled - 1);
|
||||
putl(f, pi, ab(c[fl.ci], b));
|
||||
s.flakes[keep] = { p, fl.ci, fl.wj };
|
||||
keep++;
|
||||
}
|
||||
s.nflakes = keep;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- candle glow -------------------------------------------------------------------------------
|
||||
|
||||
bool fx_candle_glow(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[3] = { { 255, 140, 40 }, { 255, 200, 120 }, { 255, 90, 20 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
if (first_call(s)) {
|
||||
int nc_candles = clampi(nz(f.pr->n[1], 4), 1, nled);
|
||||
if (nc_candles > 32) nc_candles = 32;
|
||||
s.ncent = nc_candles;
|
||||
for (int k = 0; k < nc_candles; k++) {
|
||||
s.centers[k] = rnd(0, nled > 0 ? nled - 1 : 0);
|
||||
}
|
||||
s.last = f.now;
|
||||
}
|
||||
int width = nz(f.pr->n[2], 3);
|
||||
int flicker = clampi(nz(f.pr->n[3], 90), 1, 255);
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < nled; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
int base_lo = 180 - flicker / 2;
|
||||
if (base_lo < 40) base_lo = 40;
|
||||
for (int ci = 0; ci < s.ncent; ci++) {
|
||||
int centre = s.centers[ci];
|
||||
rgb warmth = c[ci % nc];
|
||||
int pulse = clampi(base_lo + rnd(0, flicker), 0, 255);
|
||||
for (int off = -width; off <= width; off++) {
|
||||
int idx = centre + off;
|
||||
if (idx < 0 || idx >= nled) {
|
||||
continue;
|
||||
}
|
||||
int dist = abs(off);
|
||||
int fall = ((width - dist + 1) * 256) / (width + 1);
|
||||
int fac = (fall * pulse) / 256;
|
||||
rgb px = { warmth.r * fac / 255, warmth.g * fac / 255, warmth.b * fac / 255 };
|
||||
rgb lit = ab(px, b);
|
||||
rgb o = f.px[idx];
|
||||
f.px[idx] = { o.r > lit.r ? o.r : lit.r, o.g > lit.g ? o.g : lit.g, o.b > lit.b ? o.b : lit.b };
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- chase -------------------------------------------------------------------------------------
|
||||
|
||||
static void chase_draw(fx_t &f, int pos, int n1, int n2, int n3, int n4, rgb c0, rgb c1)
|
||||
{
|
||||
int seg = n1 + n2;
|
||||
(void)n3;
|
||||
(void)n4;
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
int rel = pmod(i - pos, seg);
|
||||
putl(f, i, rel < n1 ? c0 : c1);
|
||||
}
|
||||
}
|
||||
|
||||
bool fx_chase(fx_t &f, st_t &s)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
if (f.pr->n[6] == 1) {
|
||||
// Marquee: dashes that scroll
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
(void)nc;
|
||||
int on_len = nz(f.pr->n[1], 3);
|
||||
int off_len = nz(f.pr->n[2], 2);
|
||||
int step = abs(sgn(f, nz(f.pr->n[3], 1)));
|
||||
if (step < 1) step = 1;
|
||||
int period = on_len + off_len;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
rgb col = ab(c[0], b);
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < nled; i++) {
|
||||
int m = pmod(i + s.phase, period);
|
||||
putl(f, i, m < on_len ? col : bgc);
|
||||
}
|
||||
s.phase = pmod(s.phase + sgn(f, step), period);
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// Chase: two colours moving along the strip, n1/n2 segment lengths, n3/n4 steps
|
||||
const rgb def[2] = { WHITE, WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 2, c);
|
||||
rgb color0 = ab(c[0], b);
|
||||
rgb color1 = ab(nc > 1 ? c[1] : c[0], b);
|
||||
int n1 = nz(f.pr->n[1], 1);
|
||||
int n2 = nz(f.pr->n[2], 1);
|
||||
int n3 = sgn(f, f.pr->n[3]);
|
||||
int n4 = sgn(f, f.pr->n[4]);
|
||||
int seg = n1 + n2;
|
||||
int max_pos = nled + seg;
|
||||
auto position = [&](int sc) {
|
||||
int pos;
|
||||
if (sc % 2 == 0) {
|
||||
pos = (sc / 2) * (n3 + n4) + n3;
|
||||
} else {
|
||||
pos = ((sc + 1) / 2) * (n3 + n4);
|
||||
}
|
||||
return pmod(pos, max_pos);
|
||||
};
|
||||
if (!f.pr->autorun) {
|
||||
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
|
||||
s.sc = (s.sc + 1) % 2;
|
||||
return true;
|
||||
}
|
||||
uint32_t dur_ms = f.pr->delay < 10 ? 10 : f.pr->delay;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now - dur_ms; // the first step is immediate
|
||||
}
|
||||
if ((int32_t)(f.now - s.last) >= (int32_t)dur_ms) {
|
||||
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
|
||||
s.sc = (s.sc + 1) % 2;
|
||||
s.last += dur_ms;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- circle ------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_circle(fx_t &f, st_t &s)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
rgb color0, color1;
|
||||
if (f.pr->ncol == 0) {
|
||||
color0 = color1 = ab(WHITE, b);
|
||||
} else {
|
||||
color0 = ab(mk(f.pr->col[0][0], f.pr->col[0][1], f.pr->col[0][2]), b);
|
||||
color1 = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
}
|
||||
int nled = f.n;
|
||||
int head_rate = nz(f.pr->n[1], 1);
|
||||
int max_length = nz(f.pr->n[2], 1);
|
||||
int tail_rate = nz(f.pr->n[3], 1);
|
||||
int min_length = f.pr->n[4] > 0 ? f.pr->n[4] : 0;
|
||||
if (first_call(s)) {
|
||||
s.aux = f.now; // head timer
|
||||
s.last = f.now; // tail timer
|
||||
s.phase = 0; // 0 growing, 1 shrinking, 2 off
|
||||
}
|
||||
// Draw the ring: background, then the segment from the tail to the head
|
||||
int seg = pmod(s.head - s.tail, nled);
|
||||
if (seg == 0 && s.head != s.tail) {
|
||||
seg = nled;
|
||||
}
|
||||
for (int i = 0; i < nled; i++) {
|
||||
put(f, i, color1);
|
||||
}
|
||||
for (int i = 0; i <= seg; i++) {
|
||||
put(f, (s.tail + i) % nled, color0);
|
||||
}
|
||||
// Head moves at n1 LEDs per second
|
||||
uint32_t head_delay = 1000u / (uint32_t)head_rate;
|
||||
if ((int32_t)(f.now - s.aux) >= (int32_t)head_delay) {
|
||||
s.aux += head_delay;
|
||||
s.head = (s.head + 1) % nled;
|
||||
}
|
||||
// Tail behaviour by phase
|
||||
if (s.phase == 0) {
|
||||
if (seg >= max_length) {
|
||||
s.phase = 1;
|
||||
}
|
||||
} else if (s.phase == 1) {
|
||||
uint32_t tail_delay = 1000u / (uint32_t)tail_rate;
|
||||
if ((int32_t)(f.now - s.last) >= (int32_t)tail_delay) {
|
||||
s.last += tail_delay;
|
||||
s.tail = (s.tail + 1) % nled;
|
||||
int cur = pmod(s.head - s.tail, nled);
|
||||
if (cur == 0 && s.head != s.tail) {
|
||||
cur = nled;
|
||||
}
|
||||
if (min_length == 0 && cur <= 1) {
|
||||
s.phase = 2;
|
||||
} else if (min_length > 0 && cur <= min_length) {
|
||||
s.phase = 0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
s.tail = s.head;
|
||||
s.phase = 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- clock sweep -------------------------------------------------------------------------------
|
||||
|
||||
bool fx_clock_sweep(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[2] = { WHITE, { 60, 60, 60 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
get_colours(f, def, 2, c);
|
||||
int width = nz(f.pr->n[1], 1);
|
||||
int marker = f.pr->n[2] > 0 ? f.pr->n[2] : 0;
|
||||
int b = f.pr->brightness;
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
rgb fg = ab(c[0], b);
|
||||
rgb dim = { bgc.r * 2 / 3, bgc.g * 2 / 3, bgc.b * 2 / 3 };
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
put(f, i, bgc);
|
||||
if (marker > 0 && i % marker == 0) {
|
||||
put(f, i, dim);
|
||||
}
|
||||
}
|
||||
for (int w = 0; w < width; w++) {
|
||||
put(f, (s.phase + w) % f.n, fg);
|
||||
}
|
||||
s.phase = (s.phase + 1) % (f.n > 0 ? f.n : 1);
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// ---- colour cycle ------------------------------------------------------------------------------
|
||||
|
||||
static void gradient_render(fx_t &f, const rgb *cols, int nc, int phase)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
if (nc == 1) {
|
||||
fill(f, ab(cols[0], b));
|
||||
return;
|
||||
}
|
||||
int full_span = nc * 256;
|
||||
int phase_shift = (phase * full_span) / 256;
|
||||
for (int i = 0; i < nled; i++) {
|
||||
int pos = (((i * full_span) / nled) + phase_shift) % full_span;
|
||||
int idx = pos / 256;
|
||||
int frac = pos & 255;
|
||||
rgb c1 = cols[idx];
|
||||
rgb c2 = cols[(idx + 1) % nc];
|
||||
rgb blended = mix(c1, c2, frac);
|
||||
putl(f, i, ab(blended, b));
|
||||
}
|
||||
}
|
||||
|
||||
static void rainbow_render(fx_t &f, int phase)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
for (int i = 0; i < nled; i++) {
|
||||
int rc = (i * 256) / (nled > 0 ? nled : 1) + phase;
|
||||
putl(f, i, ab(wheel(rc & 255), b));
|
||||
}
|
||||
}
|
||||
|
||||
bool fx_colour_cycle(fx_t &f, st_t &s)
|
||||
{
|
||||
int step_amount = nz(f.pr->n[1], 1);
|
||||
if (f.pr->n[6] == 1) {
|
||||
// Fixed spectrum wheel, scrolling
|
||||
if (!f.pr->autorun) {
|
||||
rainbow_render(f, s.phase);
|
||||
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||
return true;
|
||||
}
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
rainbow_render(f, s.phase);
|
||||
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||
return false;
|
||||
}
|
||||
const rgb def[2] = { { 255, 0, 0 }, { 0, 0, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 2, c);
|
||||
if (!f.pr->autorun) {
|
||||
gradient_render(f, c, nc, s.phase);
|
||||
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||
return true;
|
||||
}
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
gradient_render(f, c, nc, s.phase);
|
||||
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- flicker -----------------------------------------------------------------------------------
|
||||
|
||||
bool fx_flicker(fx_t &f, st_t &s)
|
||||
{
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, &WHITE, 1, c);
|
||||
int lo = clampi(f.pr->n[1], 0, 255);
|
||||
int hi = clampi(f.pr->brightness, 0, 255);
|
||||
if (lo > hi) {
|
||||
int t = lo;
|
||||
lo = hi;
|
||||
hi = t;
|
||||
}
|
||||
if (!f.pr->autorun) {
|
||||
int level = rnd(lo, hi);
|
||||
fill(f, ab(c[s.ci % nc], level));
|
||||
return true;
|
||||
}
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
int level = rnd(lo, hi);
|
||||
fill(f, ab(c[s.ci % nc], level));
|
||||
s.ci++;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- gradient wipe (always one-shot) -----------------------------------------------------------
|
||||
|
||||
bool fx_gradient_wipe(fx_t &f, st_t &s)
|
||||
{
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, &WHITE, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
rgb c1 = c[0];
|
||||
rgb c2 = nc > 1 ? c[1] : c[0];
|
||||
int last = f.n > 0 ? f.n - 1 : 0;
|
||||
int n1 = clampi(f.pr->n[1], 0, last);
|
||||
int n2 = clampi(f.pr->n[2], 0, last);
|
||||
int count = abs(n2 - n1) + 1;
|
||||
int step = n2 >= n1 ? 1 : -1;
|
||||
uint32_t duration = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (first_call(s)) {
|
||||
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
|
||||
}
|
||||
if (s.cnt >= count) {
|
||||
return true;
|
||||
}
|
||||
int lit = (int)((f.t * (uint32_t)count) / duration) + 1;
|
||||
if (lit > count) {
|
||||
lit = count;
|
||||
}
|
||||
for (int k = s.cnt; k < lit; k++) {
|
||||
rgb col;
|
||||
if (count == 1) {
|
||||
col = c1;
|
||||
} else {
|
||||
float t = (float)k / (count - 1);
|
||||
col = { (int)(c1.r + (c2.r - c1.r) * t), (int)(c1.g + (c2.g - c1.g) * t),
|
||||
(int)(c1.b + (c2.b - c1.b) * t) };
|
||||
}
|
||||
putl(f, n1 + k * step, ab(col, b));
|
||||
}
|
||||
if (lit > s.cnt) {
|
||||
s.cnt = lit;
|
||||
}
|
||||
return s.cnt >= count;
|
||||
}
|
||||
|
||||
// ---- hit ---------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_hit(fx_t &f, st_t &s)
|
||||
{
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, &WHITE, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
if (first_call(s)) {
|
||||
s.aux = f.now;
|
||||
}
|
||||
for (int guard = 0; guard < 2; guard++) {
|
||||
int attack = (int)dur(f, f.pr->n[1]);
|
||||
int hold = (int)dur(f, f.pr->n[2]);
|
||||
int decay = (int)dur(f, f.pr->n[3]);
|
||||
int gap = f.pr->autorun ? (int)dur(f, (int)f.pr->delay) : 0;
|
||||
rgb base = c[s.ci % nc];
|
||||
int t = (int)(f.now - s.aux);
|
||||
if (t < attack) {
|
||||
rgb sc = { base.r * t / attack, base.g * t / attack, base.b * t / attack };
|
||||
fill(f, ab(sc, b));
|
||||
} else if (t < attack + hold) {
|
||||
fill(f, ab(base, b));
|
||||
} else if (t < attack + hold + decay) {
|
||||
int left = decay - (t - attack - hold);
|
||||
rgb sc = { base.r * left / decay, base.g * left / decay, base.b * left / decay };
|
||||
rgb v = ab(sc, b);
|
||||
rgb m = { v.r > bgc.r ? v.r : bgc.r, v.g > bgc.g ? v.g : bgc.g, v.b > bgc.b ? v.b : bgc.b };
|
||||
fill(f, m);
|
||||
} else if (!f.pr->autorun) {
|
||||
fill(f, f.pr->n[4] == 1 ? ab(base, b) : bgc);
|
||||
return true;
|
||||
} else if (t < attack + hold + decay + gap) {
|
||||
fill(f, bgc);
|
||||
} else {
|
||||
s.ci = (s.ci + 1) % nc;
|
||||
s.aux = f.now;
|
||||
continue; // the next flash starts on this frame
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- icicles -----------------------------------------------------------------------------------
|
||||
|
||||
bool fx_icicles(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[3] = { { 240, 248, 255 }, { 160, 210, 255 }, { 255, 255, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
int spacing = nz(f.pr->n[1], 12);
|
||||
int cap = nled / 4;
|
||||
if (cap > 14) cap = 14;
|
||||
if (cap < 3) cap = 3;
|
||||
int max_len = nz(f.pr->n[2], cap);
|
||||
if (max_len < 2) max_len = 2;
|
||||
if (max_len > (nled > 2 ? nled : 2)) max_len = nled > 2 ? nled : 2;
|
||||
int span = max_len * 2;
|
||||
int phase_step = nz(f.pr->n[3], 1);
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < nled; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
int aidx = 0;
|
||||
for (int anchor = 0; anchor < nled; anchor += spacing) {
|
||||
int tri_i = pmod(s.phase + aidx * 5, span);
|
||||
int ic_len = tri_i <= max_len ? tri_i : span - tri_i;
|
||||
rgb tip = ab(c[aidx % nc], b);
|
||||
for (int k = 0; k < ic_len; k++) {
|
||||
int idx = anchor + k;
|
||||
if (idx >= nled) {
|
||||
break;
|
||||
}
|
||||
int br = ((k + 1) * 255) / (ic_len > 1 ? ic_len : 1);
|
||||
rgb px = { (tip.r * br + bgc.r * (255 - br)) / 255, (tip.g * br + bgc.g * (255 - br)) / 255,
|
||||
(tip.b * br + bgc.b * (255 - br)) / 255 };
|
||||
putl(f, idx, px);
|
||||
}
|
||||
aidx++;
|
||||
}
|
||||
s.phase = pmod(s.phase + sgn(f, phase_step), span);
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// ---- keyframes ---------------------------------------------------------------------------------
|
||||
|
||||
static float ease_t(float t, int mode)
|
||||
{
|
||||
if (t <= 0) return 0;
|
||||
if (t >= 1) return 1;
|
||||
switch (mode) {
|
||||
case 1: return t * t * (3 - 2 * t); // in-out
|
||||
case 2: return 0; // step
|
||||
case 3: return t * t; // in
|
||||
case 4: return 1 - (1 - t) * (1 - t); // out
|
||||
default: return t; // linear
|
||||
}
|
||||
}
|
||||
|
||||
bool fx_keyframes(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
(void)s;
|
||||
int total = (int)dur(f, (int)f.pr->delay);
|
||||
if (total < 1) total = 1;
|
||||
bool loop = f.pr->autorun;
|
||||
int segs = loop ? nc : (nc - 1 > 1 ? nc - 1 : 1);
|
||||
int t = (int)f.t;
|
||||
if (!loop && t >= total) {
|
||||
if (f.pr->n[2] == 1) {
|
||||
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
|
||||
} else if (f.pr->n[2] == 2) {
|
||||
fill(f, BLACK);
|
||||
} else {
|
||||
fill(f, ab(c[nc - 1], b));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
float x = ((float)(t % total) / total) * segs;
|
||||
int i = (int)x;
|
||||
rgb a = c[i % nc];
|
||||
rgb bb = c[(i + 1) % nc];
|
||||
float k = ease_t(x - i, f.pr->n[1]);
|
||||
rgb m = { (int)(a.r + (bb.r - a.r) * k), (int)(a.g + (bb.g - a.g) * k), (int)(a.b + (bb.b - a.b) * k) };
|
||||
fill(f, ab(m, b));
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- orbit -------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_orbit(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[3] = { WHITE, { 0, 180, 255 }, { 255, 0, 120 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
int orbits = nz(f.pr->n[1], 3);
|
||||
int speed = nz(f.pr->n[2], 1);
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < nled; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
for (int k = 0; k < orbits; k++) {
|
||||
int idx = ((s.phase * (k + 1)) / 8 + (k * nled) / orbits) % (nled > 0 ? nled : 1);
|
||||
put(f, idx, ab(c[k % nc], b));
|
||||
}
|
||||
s.phase = (s.phase + speed) & 255;
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// ---- pulse -------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_pulse(fx_t &f, st_t &s)
|
||||
{
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, &WHITE, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
bool manual = !f.pr->autorun;
|
||||
if (first_call(s)) {
|
||||
fill(f, bgc);
|
||||
s.aux = f.now; // cycle start
|
||||
}
|
||||
int attack = nz(f.pr->n[1], 0);
|
||||
int hold = nz(f.pr->n[2], 0);
|
||||
int decay = nz(f.pr->n[3], 0);
|
||||
int delay = manual ? 0 : (int)f.pr->delay;
|
||||
int total = attack + hold + decay + delay;
|
||||
if (total <= 0) total = 1;
|
||||
int elapsed = (int)(f.now - s.aux);
|
||||
rgb base = c[s.ci % nc];
|
||||
if (elapsed < attack && attack > 0) {
|
||||
rgb col = { (int)(base.r * ((float)elapsed / attack)), (int)(base.g * ((float)elapsed / attack)),
|
||||
(int)(base.b * ((float)elapsed / attack)) };
|
||||
fill(f, ab(col, b));
|
||||
} else if (elapsed < attack + hold) {
|
||||
fill(f, ab(base, b));
|
||||
} else if (elapsed < attack + hold + decay && decay > 0) {
|
||||
float fac = 1.0f - (float)(elapsed - attack - hold) / decay;
|
||||
if (fac < 0) fac = 0;
|
||||
rgb col = { (int)(base.r * fac), (int)(base.g * fac), (int)(base.b * fac) };
|
||||
fill(f, ab(col, b));
|
||||
} else if (elapsed < total) {
|
||||
fill(f, bgc);
|
||||
} else {
|
||||
int nclr = nc > 1 ? nc : 1;
|
||||
s.ci = (s.ci + 1) % nclr;
|
||||
if (manual) {
|
||||
fill(f, bgc);
|
||||
return true;
|
||||
}
|
||||
s.aux = f.now;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- transition --------------------------------------------------------------------------------
|
||||
|
||||
bool fx_transition(fx_t &f, st_t &s)
|
||||
{
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, &WHITE, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
if (nc == 1) {
|
||||
fill(f, ab(c[0], b));
|
||||
return false;
|
||||
}
|
||||
if (first_call(s)) {
|
||||
s.aux = f.now;
|
||||
}
|
||||
int duration = f.pr->delay < 10 ? 10 : (int)f.pr->delay;
|
||||
int elapsed = (int)(f.now - s.aux);
|
||||
if (elapsed >= duration) {
|
||||
if (!f.pr->autorun) {
|
||||
fill(f, ab(c[(s.ci + 1) % nc], b));
|
||||
return true;
|
||||
}
|
||||
s.ci = (s.ci + 1) % nc;
|
||||
s.aux = f.now;
|
||||
return false;
|
||||
}
|
||||
rgb c1 = c[s.ci % nc];
|
||||
rgb c2 = c[(s.ci + 1) % nc];
|
||||
float factor = (float)elapsed / duration;
|
||||
rgb m = { (int)(c1.r + (c2.r - c1.r) * factor), (int)(c1.g + (c2.g - c1.g) * factor),
|
||||
(int)(c1.b + (c2.b - c1.b) * factor) };
|
||||
fill(f, ab(m, b));
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- strobe burst ------------------------------------------------------------------------------
|
||||
|
||||
bool fx_strobe_burst(fx_t &f, st_t &s)
|
||||
{
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, &WHITE, 1, c);
|
||||
(void)nc;
|
||||
int b = f.pr->brightness;
|
||||
if (first_call(s)) {
|
||||
s.stage = 0; // 0 flash on, 1 flash off, 2 cooldown
|
||||
s.flash_idx = 0;
|
||||
s.aux = f.now; // state start
|
||||
}
|
||||
int count = nz(f.pr->n[1], 3);
|
||||
int gap = nz(f.pr->n[2], 60);
|
||||
int cooldown = nz(f.pr->n[3], 400);
|
||||
int on_ms = (int)f.pr->delay / 2;
|
||||
if (on_ms < 1) on_ms = 1;
|
||||
rgb col = ab(c[0], b);
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
int since = (int)(f.now - s.aux);
|
||||
if (s.stage == 0) {
|
||||
fill(f, col);
|
||||
if (since >= on_ms) {
|
||||
s.stage = 1;
|
||||
s.aux += on_ms;
|
||||
}
|
||||
} else if (s.stage == 1) {
|
||||
fill(f, bgc);
|
||||
if (since >= gap) {
|
||||
s.flash_idx++;
|
||||
if (s.flash_idx >= count) {
|
||||
if (!f.pr->autorun) {
|
||||
return true;
|
||||
}
|
||||
s.stage = 2;
|
||||
s.flash_idx = 0;
|
||||
s.aux += gap;
|
||||
} else {
|
||||
s.stage = 0;
|
||||
s.aux += gap;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fill(f, bgc);
|
||||
if (since >= cooldown) {
|
||||
s.stage = 0;
|
||||
s.aux += cooldown;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- plasma ------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_plasma(fx_t &f, st_t &s)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
int scale = nz(f.pr->n[1], 6);
|
||||
int speed = nz(f.pr->n[2], 2);
|
||||
int contrast = nz(f.pr->n[3], 2);
|
||||
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
int t = s.phase;
|
||||
for (int i = 0; i < nled; i++) {
|
||||
int v = (i * scale + t) & 255;
|
||||
int v2 = ((i * scale) / contrast - t * 2) & 255;
|
||||
put(f, i, ab(wheel((v + v2) & 255), b));
|
||||
}
|
||||
s.phase = pmod(s.phase + speed, 256);
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
@@ -0,0 +1,894 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Moving lights, particles and sparkles, ported from the MicroPython led-driver (patterns folder).
|
||||
*/
|
||||
#include <cstdlib>
|
||||
|
||||
#include "effects.h"
|
||||
|
||||
static const rgb WHITE = { 255, 255, 255 };
|
||||
|
||||
static bool first_call(st_t &s)
|
||||
{
|
||||
if (s.started) {
|
||||
return false;
|
||||
}
|
||||
s.started = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
static uint32_t period_of(const fx_t &f)
|
||||
{
|
||||
return f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||
}
|
||||
|
||||
// Fade every LED's stored colour towards black (the shadow frame persists between frames)
|
||||
static void fade_frame(fx_t &f, int amount)
|
||||
{
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
rgb c = f.px[i];
|
||||
f.px[i] = { c.r * amount / 255, c.g * amount / 255, c.b * amount / 255 };
|
||||
}
|
||||
}
|
||||
|
||||
// ---- meteor / comet / scanner ------------------------------------------------------------------
|
||||
|
||||
static bool meteor_run(fx_t &f, st_t &s, const rgb *cols, int nc)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
int tail = nz(f.pr->n[1], 8);
|
||||
int speed = nz(f.pr->n[2], 1);
|
||||
int fade_amount = clampi(nz(f.pr->n[3], 192), 1, 255);
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
s.dir = f.pr->reverse ? -1 : 1;
|
||||
s.head = f.pr->reverse ? (f.n > 0 ? f.n - 1 : 0) : 0;
|
||||
s.ci = 0;
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
fade_frame(f, fade_amount);
|
||||
rgb lit = ab(cols[s.ci % nc], b);
|
||||
if (s.head >= 0 && s.head < f.n) {
|
||||
putl(f, s.head, lit);
|
||||
}
|
||||
s.head += sgn(f, s.dir * speed);
|
||||
if (s.head >= f.n + tail) {
|
||||
s.head = f.n - 1;
|
||||
s.dir = -1;
|
||||
s.ci++;
|
||||
} else if (s.head < -tail) {
|
||||
s.head = 0;
|
||||
s.dir = 1;
|
||||
s.ci++;
|
||||
}
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
static bool comet_run(fx_t &f, st_t &s, const rgb *cols, int nc)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
int tail = nz(f.pr->n[1], 6);
|
||||
int speed = nz(f.pr->n[2], 1);
|
||||
int gap = f.pr->n[3] > 0 ? f.pr->n[3] : 0;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
if (f.pr->reverse) {
|
||||
s.p1 = nled - 1;
|
||||
s.p2 = gap;
|
||||
} else {
|
||||
s.p1 = 0;
|
||||
s.p2 = nled - 1 - gap;
|
||||
}
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < nled; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
rgb c1 = ab(cols[0], b);
|
||||
rgb c2 = ab(nc > 1 ? cols[1] : cols[0], b);
|
||||
int denom = tail > 1 ? tail : 1;
|
||||
for (int t = 0; t < tail; t++) {
|
||||
int i1 = s.p1 - t;
|
||||
if (i1 >= 0 && i1 < nled) {
|
||||
int k = (255 * (tail - t)) / denom;
|
||||
putl(f, i1, { c1.r * k / 255, c1.g * k / 255, c1.b * k / 255 });
|
||||
}
|
||||
int i2 = s.p2 + t;
|
||||
if (i2 >= 0 && i2 < nled) {
|
||||
int k = (255 * (tail - t)) / denom;
|
||||
putl(f, i2, { c2.r * k / 255, c2.g * k / 255, c2.b * k / 255 });
|
||||
}
|
||||
}
|
||||
s.p1 += sgn(f, speed);
|
||||
s.p2 -= sgn(f, speed);
|
||||
if (s.p1 - tail > nled && s.p2 + tail < 0) {
|
||||
s.p1 = 0;
|
||||
s.p2 = nled - 1 - gap;
|
||||
}
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
static bool scanner_run(fx_t &f, st_t &s, const rgb *cols, int nc)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
int nled = f.n;
|
||||
int width = nz(f.pr->n[1], 4);
|
||||
int end_pause = f.pr->n[2] > 0 ? f.pr->n[2] : 0;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
s.ci = 0;
|
||||
s.pause = 0;
|
||||
s.dir = f.pr->reverse ? -1 : 1;
|
||||
s.head = f.pr->reverse ? (nled > 0 ? nled - 1 : 0) : 0; // centre
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
rgb base = ab(cols[s.ci % nc], b);
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
int denom = width > 1 ? width : 1;
|
||||
for (int i = 0; i < nled; i++) {
|
||||
int dist = abs(i - s.head);
|
||||
if (dist > width) {
|
||||
putl(f, i, bgc);
|
||||
} else {
|
||||
int sc = ((width - dist) * 255) / denom;
|
||||
putl(f, i, { base.r * sc / 255, base.g * sc / 255, base.b * sc / 255 });
|
||||
}
|
||||
}
|
||||
if (s.pause > 0) {
|
||||
s.pause--;
|
||||
} else {
|
||||
s.head += sgn(f, s.dir);
|
||||
if (s.head >= nled - 1) {
|
||||
s.head = nled - 1;
|
||||
s.dir = -1;
|
||||
s.pause = end_pause;
|
||||
s.ci++;
|
||||
} else if (s.head <= 0) {
|
||||
s.head = 0;
|
||||
s.dir = 1;
|
||||
s.pause = end_pause;
|
||||
s.ci++;
|
||||
}
|
||||
}
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
bool fx_meteor(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
switch (f.pr->n[6]) {
|
||||
case 1:
|
||||
return comet_run(f, s, c, nc);
|
||||
case 2:
|
||||
return scanner_run(f, s, c, nc);
|
||||
default:
|
||||
return meteor_run(f, s, c, nc);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- particles: snowfall and starfall ----------------------------------------------------------
|
||||
|
||||
static bool snow_run(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[2] = { WHITE, { 180, 220, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 2, c);
|
||||
int b = f.pr->brightness;
|
||||
int density = nz(f.pr->n[1], 20);
|
||||
int speed = abs(sgn(f, nz(f.pr->n[2], 1)));
|
||||
if (speed < 1) speed = 1;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
if (rnd(0, 255) < density && s.nflakes < 64) {
|
||||
s.flakes[s.nflakes++] = { f.n - 1, rnd(0, nc - 1), 0 };
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
int keep = 0;
|
||||
for (int k = 0; k < s.nflakes; k++) {
|
||||
flake_t fl = s.flakes[k];
|
||||
if (fl.pos >= 0 && fl.pos < f.n) {
|
||||
putl(f, fl.pos, ab(c[fl.ci], b));
|
||||
}
|
||||
fl.pos -= sgn(f, speed);
|
||||
if (fl.pos >= -1) {
|
||||
s.flakes[keep++] = fl;
|
||||
}
|
||||
}
|
||||
s.nflakes = keep;
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
static bool starfall_run(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[3] = { WHITE, { 200, 230, 255 }, { 255, 248, 220 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int rate = clampi(nz(f.pr->n[1], 14), 1, 255);
|
||||
int speed = abs(sgn(f, nz(f.pr->n[2], 2)));
|
||||
if (speed < 1) speed = 1;
|
||||
int tail = nz(f.pr->n[3], 10);
|
||||
if (tail < 2) tail = 2;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
if (s.nstars < 4 && rnd(0, 255) < rate) {
|
||||
int extra = f.n / 2;
|
||||
if (extra > 8) extra = 8;
|
||||
int top = f.n - 1 + rnd(0, extra);
|
||||
s.stars[s.nstars++] = { top, rnd(0, nc - 1) };
|
||||
}
|
||||
int keep = 0;
|
||||
for (int k = 0; k < s.nstars; k++) {
|
||||
star_t st = s.stars[k];
|
||||
for (int t = 0; t < tail; t++) {
|
||||
int idx = st.h + t;
|
||||
if (idx < 0 || idx >= f.n) {
|
||||
continue;
|
||||
}
|
||||
int fade = 255 - (t * 255) / (tail - 1 > 1 ? tail - 1 : 1);
|
||||
rgb base = c[st.ci];
|
||||
rgb lit = ab({ base.r * fade / 255, base.g * fade / 255, base.b * fade / 255 }, b);
|
||||
int pix = led_at(f, idx);
|
||||
rgb o = f.px[pix];
|
||||
f.px[pix] = { o.r > lit.r ? o.r : lit.r, o.g > lit.g ? o.g : lit.g, o.b > lit.b ? o.b : lit.b };
|
||||
}
|
||||
st.h -= sgn(f, speed);
|
||||
if (st.h >= -tail) {
|
||||
s.stars[keep++] = st;
|
||||
}
|
||||
}
|
||||
s.nstars = keep;
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
bool fx_particles(fx_t &f, st_t &s)
|
||||
{
|
||||
return f.pr->n[6] == 1 ? starfall_run(f, s) : snow_run(f, s);
|
||||
}
|
||||
|
||||
// ---- sparkle: trail, ice burst, fireflies ------------------------------------------------------
|
||||
|
||||
static bool sparkle_trail(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { { 120, 120, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
int density = nz(f.pr->n[1], 24);
|
||||
int decay = clampi(nz(f.pr->n[2], 210), 1, 255);
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
fade_frame(f, decay);
|
||||
int sparks = f.n * density / 255;
|
||||
if (sparks < 1) sparks = 1;
|
||||
for (int k = 0; k < sparks; k++) {
|
||||
int idx = rnd(0, f.n > 0 ? f.n - 1 : 0);
|
||||
put(f, idx, ab(c[rnd(0, nc - 1)], b));
|
||||
}
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
static bool sparkle_ice(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[3] = { { 240, 248, 255 }, { 200, 235, 255 }, { 255, 255, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int rate = clampi(nz(f.pr->n[1], 55), 1, 255);
|
||||
int decay = clampi(nz(f.pr->n[2], 140), 1, 255);
|
||||
int halo = clampi(f.pr->n[3], 0, 3);
|
||||
const int cap = 28;
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
int keep = 0;
|
||||
for (int k = 0; k < s.nsparks; k++) {
|
||||
spark_t sp = s.sparks[k];
|
||||
sp.lv -= decay;
|
||||
if (sp.lv > 0) {
|
||||
s.sparks[keep++] = sp;
|
||||
}
|
||||
}
|
||||
s.nsparks = keep;
|
||||
if (s.nsparks < cap && rnd(0, 255) < rate) {
|
||||
s.sparks[s.nsparks++] = { rnd(0, f.n > 0 ? f.n - 1 : 0), 255, rnd(0, nc - 1) };
|
||||
}
|
||||
for (int k = 0; k < s.nsparks; k++) {
|
||||
spark_t sp = s.sparks[k];
|
||||
rgb base = c[sp.ci];
|
||||
for (int off = -halo; off <= halo; off++) {
|
||||
int idx = sp.p + off;
|
||||
if (idx < 0 || idx >= f.n) {
|
||||
continue;
|
||||
}
|
||||
int dist = abs(off);
|
||||
int fac = dist == 0 ? sp.lv : (sp.lv * (halo - dist + 1)) / (halo + 1);
|
||||
rgb lit = ab({ base.r * fac / 255, base.g * fac / 255, base.b * fac / 255 }, b);
|
||||
rgb o = f.px[idx];
|
||||
f.px[idx] = { o.r + lit.r > 255 ? 255 : o.r + lit.r, o.g + lit.g > 255 ? 255 : o.g + lit.g,
|
||||
o.b + lit.b > 255 ? 255 : o.b + lit.b };
|
||||
}
|
||||
}
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
static bool sparkle_fireflies(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[2] = { { 255, 210, 80 }, { 120, 255, 120 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 2, c);
|
||||
int b = f.pr->brightness;
|
||||
int count = nz(f.pr->n[1], 6);
|
||||
if (count > 16) count = 16;
|
||||
int speed = nz(f.pr->n[2], 8);
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
s.nbugs = count;
|
||||
for (int k = 0; k < count; k++) {
|
||||
s.bugs[k] = { rnd(0, f.n > 0 ? f.n - 1 : 0), rnd(0, 255) };
|
||||
}
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
for (int k = 0; k < s.nbugs; k++) {
|
||||
bug_t &bg = s.bugs[k];
|
||||
int tri = 255 - abs(128 - bg.ph) * 2;
|
||||
rgb col = ab(c[bg.pos % nc], b);
|
||||
put(f, bg.pos, { col.r * tri / 255, col.g * tri / 255, col.b * tri / 255 });
|
||||
bg.ph = (bg.ph + speed) & 255;
|
||||
if (rnd(0, 31) == 0) {
|
||||
bg.pos = rnd(0, f.n > 0 ? f.n - 1 : 0);
|
||||
}
|
||||
}
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
bool fx_sparkle(fx_t &f, st_t &s)
|
||||
{
|
||||
switch (f.pr->n[6]) {
|
||||
case 1:
|
||||
return sparkle_ice(f, s);
|
||||
case 2:
|
||||
return sparkle_fireflies(f, s);
|
||||
default:
|
||||
return sparkle_trail(f, s);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- rain drops --------------------------------------------------------------------------------
|
||||
|
||||
bool fx_rain_drops(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { { 120, 180, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
int rate = nz(f.pr->n[1], 32);
|
||||
int width = nz(f.pr->n[2], 3);
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
put(f, i, bgc);
|
||||
}
|
||||
if (rnd(0, 255) < rate && s.ndrops < 32) {
|
||||
s.drops[s.ndrops++] = { rnd(0, f.n > 0 ? f.n - 1 : 0), 0 };
|
||||
}
|
||||
int keep = 0;
|
||||
int denom = width + 1;
|
||||
for (int k = 0; k < s.ndrops; k++) {
|
||||
drop_t dr = s.drops[k];
|
||||
for (int off = -width; off <= width; off++) {
|
||||
int idx = dr.pos + off;
|
||||
if (idx < 0 || idx >= f.n) {
|
||||
continue;
|
||||
}
|
||||
int lvl = 255 - (abs(off) * 255 / (denom > 1 ? denom : 1) + dr.age * 40);
|
||||
if (lvl < 0) lvl = 0;
|
||||
rgb base = ab(c[dr.age % nc], b);
|
||||
put(f, idx, { base.r * lvl / 255, base.g * lvl / 255, base.b * lvl / 255 });
|
||||
}
|
||||
dr.age++;
|
||||
if (dr.age < 8) {
|
||||
s.drops[keep++] = dr;
|
||||
}
|
||||
}
|
||||
s.ndrops = keep;
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// ---- rime: slow frost build-up -----------------------------------------------------------------
|
||||
|
||||
bool fx_rime(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[3] = { { 220, 235, 255 }, WHITE, { 185, 220, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int num = f.n;
|
||||
if (num <= 0) {
|
||||
return false;
|
||||
}
|
||||
int chill = clampi(nz(f.pr->n[1], 36), 1, 255);
|
||||
int melt = clampi(nz(f.pr->n[2], 12), 1, 255);
|
||||
int spark_cap = clampi(nz(f.pr->n[3], 3), 1, num);
|
||||
if (first_call(s)) {
|
||||
for (int i = 0; i < num; i++) {
|
||||
s.glow[i] = 0;
|
||||
}
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!due(f.now, s.last, period_of(f))) {
|
||||
return false;
|
||||
}
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
for (int i = 0; i < num; i++) {
|
||||
s.glow[i] = s.glow[i] > melt ? s.glow[i] - melt : 0;
|
||||
}
|
||||
int spawned = 0;
|
||||
int tries = spark_cap + num / 8;
|
||||
for (int t = 0; t < tries; t++) {
|
||||
if (spawned >= spark_cap) {
|
||||
break;
|
||||
}
|
||||
if (rnd(0, 255) >= chill) {
|
||||
continue;
|
||||
}
|
||||
int j = rnd(0, num - 1);
|
||||
int g = s.glow[j] + rnd(80, 200);
|
||||
s.glow[j] = g > 255 ? 255 : g;
|
||||
spawned++;
|
||||
}
|
||||
for (int i = 0; i < num; i++) {
|
||||
int g = clampi(s.glow[i], 0, 255);
|
||||
rgb hi = ab(c[i % nc], b);
|
||||
rgb px = { (hi.r * g + bgc.r * (255 - g)) / 255, (hi.g * g + bgc.g * (255 - g)) / 255,
|
||||
(hi.b * g + bgc.b * (255 - g)) / 255 };
|
||||
put(f, i, px);
|
||||
}
|
||||
return !f.pr->autorun;
|
||||
}
|
||||
|
||||
// ---- twinkle -----------------------------------------------------------------------------------
|
||||
|
||||
static const rgb kCool[6] = {
|
||||
{ 120, 200, 255 }, { 80, 140, 255 }, { 180, 120, 255 },
|
||||
{ 100, 220, 240 }, { 160, 200, 255 }, { 90, 180, 220 },
|
||||
};
|
||||
|
||||
static int cluster_lo(const fx_t &f, int *hi_out)
|
||||
{
|
||||
int lo = f.pr->n[3];
|
||||
int hi = f.pr->n[4];
|
||||
int num = f.n;
|
||||
if (lo <= 0 && hi <= 0) {
|
||||
lo = 1;
|
||||
hi = num < 4 ? num : 4;
|
||||
} else {
|
||||
if (lo <= 0) lo = 1;
|
||||
if (hi <= 0) hi = lo;
|
||||
if (hi < lo) {
|
||||
int t = lo;
|
||||
lo = hi;
|
||||
hi = t;
|
||||
}
|
||||
}
|
||||
lo = clampi(lo, 1, num > 0 ? num : 1);
|
||||
hi = clampi(hi, lo, num > 0 ? num : 1);
|
||||
*hi_out = hi;
|
||||
return lo;
|
||||
}
|
||||
|
||||
static int cluster_len(const fx_t &f)
|
||||
{
|
||||
int hi;
|
||||
int lo = cluster_lo(f, &hi);
|
||||
return lo == hi ? lo : rnd(lo, hi);
|
||||
}
|
||||
|
||||
static int cluster_base(const fx_t &f, int start, int k)
|
||||
{
|
||||
k = clampi(k, 0, f.n);
|
||||
if (k <= 0) {
|
||||
return 0;
|
||||
}
|
||||
int b = start < f.n - k ? start : f.n - k;
|
||||
return b < 0 ? 0 : b;
|
||||
}
|
||||
|
||||
bool fx_twinkle(fx_t &f, st_t &s)
|
||||
{
|
||||
rgb palette[PATTERN_MAX_COLOURS];
|
||||
int np = get_colours(f, kCool, 6, palette);
|
||||
int b = f.pr->brightness;
|
||||
int num = f.n;
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
if (num <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (first_call(s)) {
|
||||
int dens0 = clampi(f.pr->n[2] > 0 ? f.pr->n[2] : 128, 0, 255);
|
||||
for (int i = 0; i < num; i++) {
|
||||
s.on[i] = rnd(0, 255) < dens0;
|
||||
s.col_i[i] = rnd(0, np - 1);
|
||||
}
|
||||
s.last = f.now;
|
||||
}
|
||||
if (!f.pr->autorun) {
|
||||
for (int i = 0; i < num; i++) {
|
||||
put(f, i, s.on[i] ? ab(palette[s.col_i[i] % np], b) : bgc);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
uint32_t d = period_of(f);
|
||||
if (!due(f.now, s.last, d)) {
|
||||
return false;
|
||||
}
|
||||
int rate = clampi(f.pr->n[1] > 0 ? f.pr->n[1] : 48, 1, 255);
|
||||
int dens = clampi(f.pr->n[2] > 0 ? f.pr->n[2] : 128, 0, 255);
|
||||
for (int i = 0; i < num; i++) {
|
||||
s.next_on[i] = s.on[i];
|
||||
s.next_ci[i] = s.col_i[i];
|
||||
}
|
||||
s.nlight = 0;
|
||||
s.ndark = 0;
|
||||
for (int i = 0; i < num; i++) {
|
||||
if (rnd(0, 255) < rate) {
|
||||
int r = rnd(0, 255);
|
||||
if (!s.on[i]) {
|
||||
if (r < dens) s.light[s.nlight++] = i;
|
||||
} else {
|
||||
if (r < 255 - dens) s.dark[s.ndark++] = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < s.ndark; k++) {
|
||||
int start = s.dark[k];
|
||||
int len = cluster_len(f);
|
||||
int base = cluster_base(f, start, len);
|
||||
for (int dj = 0; dj < len; dj++) {
|
||||
s.next_on[base + dj] = 0;
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < s.nlight; k++) {
|
||||
int start = s.light[k];
|
||||
int len = cluster_len(f);
|
||||
int base = cluster_base(f, start, len);
|
||||
for (int dj = 0; dj < len; dj++) {
|
||||
s.next_on[base + dj] = 1;
|
||||
s.next_ci[base + dj] = rnd(0, np - 1);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < num; i++) {
|
||||
put(f, i, s.next_on[i] ? ab(palette[s.next_ci[i] % np], b) : bgc);
|
||||
s.on[i] = s.next_on[i];
|
||||
s.col_i[i] = s.next_ci[i];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- radiate: pulses from nodes ----------------------------------------------------------------
|
||||
|
||||
static int radiate_front(int age, int outward, int ret, int maxd)
|
||||
{
|
||||
if (age <= outward) {
|
||||
return (age * maxd + outward - 1) / outward;
|
||||
}
|
||||
if (age <= outward + ret) {
|
||||
int rem = ret - (age - outward);
|
||||
return (rem * maxd + ret - 1) / ret;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool fx_radiate(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int b = f.pr->brightness;
|
||||
rgb off_c = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
int spacing = nz(f.pr->n[1], 1);
|
||||
int outward = nz(f.pr->n[2], 1);
|
||||
int ret = nz(f.pr->n[3], 1);
|
||||
int maxd = spacing / 2;
|
||||
int life = outward + ret;
|
||||
int num = f.n;
|
||||
|
||||
if (!f.pr->autorun) {
|
||||
// One pulse, then hold
|
||||
if (first_call(s)) {
|
||||
s.aux = f.now;
|
||||
}
|
||||
int age = (int)(f.now - s.aux);
|
||||
if (age < 1) age = 1;
|
||||
int front = radiate_front(age, outward, ret, maxd);
|
||||
if (front < 0) front = 0;
|
||||
rgb lit = ab(c[s.ci % nc], b);
|
||||
for (int i = 0; i < num; i++) {
|
||||
int offset = (i + spacing / 2) % spacing;
|
||||
int dist = offset < spacing - offset ? offset : spacing - offset;
|
||||
put(f, i, dist <= front ? lit : off_c);
|
||||
}
|
||||
if (age >= life) {
|
||||
s.ci++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t delay = period_of(f);
|
||||
if (first_call(s)) {
|
||||
s.last = f.now;
|
||||
s.ncent = 1;
|
||||
s.centers[0] = (int)f.now;
|
||||
}
|
||||
if ((int32_t)(f.now - s.last) >= (int32_t)delay) {
|
||||
s.ncent = 1;
|
||||
s.centers[0] = (int)f.now;
|
||||
s.last += delay;
|
||||
s.ci++;
|
||||
}
|
||||
int kept = 0;
|
||||
for (int k = 0; k < s.ncent; k++) {
|
||||
if ((int)(f.now - s.centers[k]) < life) {
|
||||
s.centers[kept++] = s.centers[k];
|
||||
}
|
||||
}
|
||||
s.ncent = kept;
|
||||
rgb lit = ab(c[s.ci % nc], b);
|
||||
for (int i = 0; i < num; i++) {
|
||||
int offset = (i + spacing / 2) % spacing;
|
||||
int dist = offset < spacing - offset ? offset : spacing - offset;
|
||||
bool on = false;
|
||||
for (int k = 0; k < s.ncent && !on; k++) {
|
||||
int age = (int)(f.now - s.centers[k]);
|
||||
if (age <= 0) {
|
||||
continue;
|
||||
}
|
||||
int front = radiate_front(age, outward, ret, maxd);
|
||||
if (front < 0) {
|
||||
continue;
|
||||
}
|
||||
if (dist <= front) {
|
||||
on = true;
|
||||
}
|
||||
}
|
||||
put(f, i, on ? lit : off_c);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- palette morph -----------------------------------------------------------------------------
|
||||
|
||||
bool fx_palette_morph(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[3] = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 3, c);
|
||||
int b = f.pr->brightness;
|
||||
int num = f.n;
|
||||
if (nc < 2) {
|
||||
fill(f, ab(c[0], b));
|
||||
return false;
|
||||
}
|
||||
int morph = nz(f.pr->n[1], 1200);
|
||||
if (morph < 50) morph = 50;
|
||||
int warp = nz(f.pr->n[2], 3);
|
||||
int turb = nz(f.pr->n[3], 24);
|
||||
if (first_call(s)) {
|
||||
s.aux = f.now; // morph start
|
||||
s.last = f.now; // frame timer
|
||||
s.ci = 0; // base colour index
|
||||
s.phase = 0;
|
||||
}
|
||||
uint32_t delay = period_of(f);
|
||||
if (!due(f.now, s.last, delay)) {
|
||||
return false;
|
||||
}
|
||||
int age = (int)(f.now - s.aux);
|
||||
int t = age < morph ? (age * 255) / morph : 255;
|
||||
rgb a = c[s.ci % nc];
|
||||
rgb bb = c[(s.ci + 1) % nc];
|
||||
rgb anchor = mix(a, bb, t);
|
||||
for (int i = 0; i < num; i++) {
|
||||
int pos = (i * 256) / (num > 0 ? num : 1);
|
||||
int wobble = (((pos * turb) / 32) + s.phase + (t / 2)) & 255;
|
||||
int breath = 255 - abs(128 - wobble) * 2;
|
||||
int local = (pos + breath / 3 + t / 4) % 256;
|
||||
int idx = (s.ci + ((local * nc) / 256)) % nc;
|
||||
int frac = (local * nc) & 255;
|
||||
rgb grad = mix(c[idx], c[(idx + 1) % nc], frac);
|
||||
rgb out = mix(grad, anchor, 80);
|
||||
put(f, i, ab(out, b));
|
||||
}
|
||||
if (age >= morph) {
|
||||
s.ci = (s.ci + 1) % nc;
|
||||
s.aux = f.now;
|
||||
if (!f.pr->autorun) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
s.phase = (s.phase + warp) & 255;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- flame -------------------------------------------------------------------------------------
|
||||
|
||||
static int tri255(uint32_t elapsed, uint32_t period)
|
||||
{
|
||||
if (period < 400) period = 400;
|
||||
uint32_t p = elapsed % period;
|
||||
uint32_t half = period >> 1;
|
||||
if (half == 0) return 128;
|
||||
if (p < half) return (int)((p * 255) / half);
|
||||
return (int)(((period - p) * 255) / (period - half));
|
||||
}
|
||||
|
||||
static rgb palette_sample(const rgb *pal, int n, int pos)
|
||||
{
|
||||
if (n == 1) return pal[0];
|
||||
int span = (n - 1) * pos;
|
||||
int seg = span >> 8;
|
||||
if (seg >= n - 1) return pal[n - 1];
|
||||
int frac = span & 0xFF;
|
||||
rgb a = pal[seg];
|
||||
rgb b = pal[seg + 1];
|
||||
rgb o = { a.r + (((b.r - a.r) * frac) >> 8), a.g + (((b.g - a.g) * frac) >> 8),
|
||||
a.b + (((b.b - a.b) * frac) >> 8) };
|
||||
return o;
|
||||
}
|
||||
|
||||
static void flame_frame(fx_t &f, st_t &s, const rgb *pal, int np, uint32_t breath_el, bool spark_on)
|
||||
{
|
||||
int num = f.n;
|
||||
int denom = num > 1 ? num - 1 : 1;
|
||||
int breathe = tri255(breath_el, (uint32_t)s.breath_ms);
|
||||
int base_level = s.lo + (((s.hi - s.lo) * breathe) >> 8);
|
||||
int micro = 232 + rnd(0, 35);
|
||||
int level = clampi((base_level * micro) >> 8, s.lo, s.hi);
|
||||
int boost = 0;
|
||||
rgb white = { 0, 0, 0 };
|
||||
if (spark_on && s.spark_dur > 0) {
|
||||
int el = (int)(f.now - s.spark_start);
|
||||
if (el < 0) el = 0;
|
||||
if (el < s.spark_dur) {
|
||||
int env = 255 - (el * 255) / s.spark_dur;
|
||||
boost = (env * 90) >> 8;
|
||||
white = { (env * 55) >> 8, (env * 50) >> 8, (env * 40) >> 8 };
|
||||
}
|
||||
}
|
||||
int cell = num >> 3;
|
||||
if (cell < 1) cell = 1;
|
||||
for (int i = 0; i < num; i++) {
|
||||
int h = (i * 256) / denom;
|
||||
int flow = (h + s.rise + (i / cell) * 17) & 255;
|
||||
int pos = (flow + s.cj[(i >> 2) & 7]) & 255;
|
||||
rgb c = palette_sample(pal, np, pos);
|
||||
if (boost) {
|
||||
c = { clampi(c.r + white.r + ((boost * 3) >> 2), 0, 255), clampi(c.g + white.g + (boost >> 1), 0, 255),
|
||||
clampi(c.b + white.b + (boost >> 2), 0, 255) };
|
||||
}
|
||||
put(f, i, ab(c, level));
|
||||
}
|
||||
}
|
||||
|
||||
bool fx_flame(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[4] = { { 90, 8, 8 }, { 200, 40, 12 }, { 255, 120, 30 }, { 255, 220, 140 } };
|
||||
rgb pal[PATTERN_MAX_COLOURS];
|
||||
int np = get_colours(f, def, 4, pal);
|
||||
int lo = clampi(f.pr->n[1], 0, 255);
|
||||
int hi = clampi(f.pr->brightness, 0, 255);
|
||||
if (lo > hi) {
|
||||
int t = lo;
|
||||
lo = hi;
|
||||
hi = t;
|
||||
}
|
||||
int bp = f.pr->n[2];
|
||||
int breath_ms = bp > 0 ? bp : 2500;
|
||||
if (breath_ms < 800) breath_ms = 800;
|
||||
int gap_lo = f.pr->n[3];
|
||||
int gap_hi = f.pr->n[4];
|
||||
if (gap_lo == 0 && gap_hi == 0) {
|
||||
gap_lo = 10000;
|
||||
gap_hi = 30000;
|
||||
} else {
|
||||
if (gap_lo < 500) gap_lo = 500;
|
||||
}
|
||||
if (gap_hi < gap_lo) gap_hi = gap_lo;
|
||||
uint32_t delay = f.pr->delay < 16 ? 16 : f.pr->delay;
|
||||
|
||||
if (first_call(s)) {
|
||||
s.breath_ms = breath_ms;
|
||||
s.lo = lo;
|
||||
s.hi = hi;
|
||||
s.rise = rnd(0, 255);
|
||||
for (int k = 0; k < 8; k++) {
|
||||
s.cj[k] = rnd(-18, 18);
|
||||
}
|
||||
s.last = f.now; // last frame
|
||||
s.breath_origin = f.now;
|
||||
s.last_cluster = f.now;
|
||||
s.spark_active = false;
|
||||
s.spark_dur = 0;
|
||||
s.next_spark = f.now + (uint32_t)rnd(gap_lo, gap_hi);
|
||||
}
|
||||
s.lo = lo;
|
||||
s.hi = hi;
|
||||
s.breath_ms = breath_ms;
|
||||
|
||||
if (!f.pr->autorun) {
|
||||
flame_frame(f, s, pal, np, 0, false);
|
||||
return true;
|
||||
}
|
||||
if ((int32_t)(f.now - s.last) < (int32_t)delay) {
|
||||
return false;
|
||||
}
|
||||
s.last += delay;
|
||||
s.rise = (s.rise + rnd(-10, 12)) & 255;
|
||||
if ((int32_t)(f.now - s.last_cluster) >= (int32_t)(delay * 4)) {
|
||||
s.last_cluster = f.now;
|
||||
for (int k = 0; k < 8; k++) {
|
||||
s.cj[k] = rnd(-18, 18);
|
||||
}
|
||||
}
|
||||
if (s.spark_active) {
|
||||
if ((int)(f.now - s.spark_start) >= s.spark_dur) {
|
||||
s.spark_active = false;
|
||||
s.next_spark = f.now + (uint32_t)rnd(gap_lo, gap_hi);
|
||||
}
|
||||
} else if ((int32_t)(f.now - s.next_spark) >= 0) {
|
||||
s.spark_active = true;
|
||||
s.spark_start = f.now;
|
||||
s.spark_dur = rnd(180, 360);
|
||||
}
|
||||
flame_frame(f, s, pal, np, f.now - s.breath_origin, s.spark_active);
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Patterns that span the rig, ported from the MicroPython led-driver (rig.py and patterns folder).
|
||||
* The rig geometry is the MicroPython default for a lone strip: the bar runs from (-1, 0) to (1, 0), so
|
||||
* LED i sits at x = -1 + 2 (i + 0.5) / n. The rig placement (place) is not configurable on this board.
|
||||
*/
|
||||
#include <cmath>
|
||||
|
||||
#include "effects.h"
|
||||
|
||||
static const rgb WHITE = { 255, 255, 255 };
|
||||
|
||||
static bool first_call(st_t &s)
|
||||
{
|
||||
if (s.started) {
|
||||
return false;
|
||||
}
|
||||
s.started = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Position of LED i on the bar
|
||||
static float led_x(int i, int n)
|
||||
{
|
||||
return -1.0f + 2.0f * (i + 0.5f) / n;
|
||||
}
|
||||
|
||||
// Distance from the centre, 0..1
|
||||
static float led_r(int i, int n)
|
||||
{
|
||||
float x = led_x(i, n);
|
||||
return x < 0 ? -x : x;
|
||||
}
|
||||
|
||||
// Angle round the centre, 0..1 of a turn: the left half is at 1/2, the right at 0
|
||||
static float led_a(int i, int n)
|
||||
{
|
||||
return led_x(i, n) < 0 ? 0.5f : 0.0f;
|
||||
}
|
||||
|
||||
// Position of LED i along a direction across the rig, 0..1
|
||||
static float along(int i, int n, float angle_deg)
|
||||
{
|
||||
float rad = angle_deg * 3.14159265f / 180.0f;
|
||||
return (led_x(i, n) * cosf(rad) + 1.0f) / 2.0f;
|
||||
}
|
||||
|
||||
static int shade_of(float p)
|
||||
{
|
||||
int s = (int)(p * (RIG_SHADES - 1) + 0.5f);
|
||||
return s < 0 ? 0 : (s > RIG_SHADES - 1 ? RIG_SHADES - 1 : s);
|
||||
}
|
||||
|
||||
// Shade of a brightness-free sine: 0..15
|
||||
static int sin_shade(int i)
|
||||
{
|
||||
float v = (sinf(i * 6.2831853f / 256.0f) + 1.0f) / 2.0f * (RIG_SHADES - 1) + 0.5f;
|
||||
return (int)v;
|
||||
}
|
||||
|
||||
// ---- field wave --------------------------------------------------------------------------------
|
||||
|
||||
bool fx_field_wave(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int n = f.n;
|
||||
int kind = f.pr->n[3];
|
||||
int lam = nz(f.pr->n[2], 1000);
|
||||
uint32_t period = dur(f, (int)f.pr->delay);
|
||||
if (period < 1) period = 1;
|
||||
(void)first_call(s);
|
||||
uint32_t t = f.t;
|
||||
bool done = !f.pr->autorun && t >= period;
|
||||
int ph = done ? 256 : (int)((t % period) * 256 / period);
|
||||
for (int i = 0; i < n; i++) {
|
||||
int shade;
|
||||
if (kind == 3) {
|
||||
// Plasma: two sines of the position, summed
|
||||
// Lone bar: y is always 0, so the second sine is taken at -p13
|
||||
int px = (int)(led_x(i, n) * 3 * 256000 / (lam * 6.283f));
|
||||
int p13 = ph * 13 / 10;
|
||||
float v = sinf(((px + ph) & 255) * 6.2831853f / 256.0f)
|
||||
+ sinf(((-p13) & 255) * 6.2831853f / 256.0f); // -2..2
|
||||
shade = sin_shade(((int)(v * 41) + ph) & 255);
|
||||
} else {
|
||||
float m = kind == 1 ? led_r(i, n) : (kind == 2 ? led_a(i, n) : along(i, n, (float)f.pr->n[1]));
|
||||
int mi = (int)(m * 256000 / lam);
|
||||
shade = sin_shade((mi - ph) & 255);
|
||||
}
|
||||
put(f, i, rig_entry(f, c, nc, RIG_SHADES, shade, RIG_LEVELS - 1));
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
// ---- grow --------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_grow(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int n = f.n;
|
||||
int mode = f.pr->n[1];
|
||||
const int top = RIG_LEVELS - 1;
|
||||
const float edge = 0.06f;
|
||||
(void)first_call(s);
|
||||
for (int i = 0; i < n; i++) {
|
||||
float m;
|
||||
if (mode == 1) {
|
||||
m = 1 - led_r(i, n);
|
||||
} else if (mode == 2) {
|
||||
m = led_a(i, n);
|
||||
} else if (mode == 3) {
|
||||
m = along(i, n, (float)f.pr->n[3]);
|
||||
} else {
|
||||
m = led_r(i, n);
|
||||
}
|
||||
s.m[i] = m;
|
||||
s.shade[i] = shade_of(m);
|
||||
}
|
||||
uint32_t total = dur(f, (int)f.pr->delay);
|
||||
if (total < 1) total = 1;
|
||||
bool empties = f.pr->n[2] == 1 || f.pr->n[2] == 2 || f.pr->autorun;
|
||||
int phases = empties ? 2 : 1;
|
||||
uint32_t t = f.t;
|
||||
if (!f.pr->autorun && t >= total * phases) {
|
||||
if (f.pr->n[2] == 3 || empties) {
|
||||
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), f.pr->brightness));
|
||||
} else {
|
||||
for (int i = 0; i < n; i++) {
|
||||
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], top));
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
float ph;
|
||||
if (f.pr->autorun) {
|
||||
ph = (float)(t % (total * phases)) / total;
|
||||
} else {
|
||||
ph = (float)t / total;
|
||||
if (ph > phases) ph = (float)phases;
|
||||
}
|
||||
float front;
|
||||
bool rising;
|
||||
if (ph <= 1) {
|
||||
front = ph * (1 + edge);
|
||||
rising = true;
|
||||
} else if (f.pr->n[2] == 2) {
|
||||
front = (ph - 1) * (1 + edge);
|
||||
rising = false;
|
||||
} else {
|
||||
front = (2 - ph) * (1 + edge);
|
||||
rising = true;
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
float v = (rising ? (front - s.m[i]) : (s.m[i] - front)) / edge;
|
||||
int lv = v <= 0 ? 0 : (v >= 1 ? top : (int)(v * top));
|
||||
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], lv));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- ripple ------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_ripple(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int n = f.n;
|
||||
int b = f.pr->brightness;
|
||||
const int top = RIG_LEVELS - 1;
|
||||
(void)first_call(s);
|
||||
uint32_t period = dur(f, (int)f.pr->delay);
|
||||
if (period < 1) period = 1;
|
||||
float hw = (f.pr->n[1] > 0 ? f.pr->n[1] : 150) / 2000.0f;
|
||||
int rings = f.pr->autorun ? nz(f.pr->n[2], 1) : 1;
|
||||
if (rings > 8) rings = 8;
|
||||
float fade = (f.pr->n[4] > 0 ? f.pr->n[4] : 0) / 1000.0f;
|
||||
uint32_t t = f.t;
|
||||
if (!f.pr->autorun && t >= period) {
|
||||
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
|
||||
return true;
|
||||
}
|
||||
float base = f.pr->autorun ? (float)(t % period) / period : (float)t / period;
|
||||
float span = 1 + 4 * hw;
|
||||
float rads[8];
|
||||
for (int k = 0; k < rings; k++) {
|
||||
float x = base + (float)k / rings;
|
||||
x = x - floorf(x);
|
||||
rads[k] = -2 * hw + x * span;
|
||||
}
|
||||
int shade = (int)((t / period) % (uint32_t)nc);
|
||||
for (int i = 0; i < n; i++) {
|
||||
float r = (f.pr->n[3] == 1) ? (1 - led_r(i, n)) : led_r(i, n);
|
||||
float best = 0;
|
||||
for (int k = 0; k < rings; k++) {
|
||||
float v = 1 - fabsf(r - rads[k]) / hw;
|
||||
if (v > best) best = v;
|
||||
}
|
||||
if (fade > 0 && best > 0) {
|
||||
best *= 1 - fade * r;
|
||||
if (best < 0) best = 0;
|
||||
}
|
||||
put(f, i, rig_entry(f, c, nc, nc, shade, (int)(best * top)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- spin --------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_spin(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int n = f.n;
|
||||
const int top = RIG_LEVELS - 1;
|
||||
(void)first_call(s);
|
||||
uint32_t period = dur(f, (int)f.pr->delay);
|
||||
if (period < 1) period = 1;
|
||||
float span = 1.0f / (f.pr->n[1] > 0 ? f.pr->n[1] : 1);
|
||||
float width = (f.pr->n[2] > 0 ? f.pr->n[2] : 20) / 360.0f;
|
||||
float tail = (f.pr->n[3] > 0 ? f.pr->n[3] : 90) / 360.0f;
|
||||
uint32_t t = f.t;
|
||||
if (!f.pr->autorun && t >= period) {
|
||||
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), f.pr->brightness));
|
||||
return true;
|
||||
}
|
||||
float rot = fmodf((float)t / period, 1.0f);
|
||||
for (int i = 0; i < n; i++) {
|
||||
float ang = f.pr->n[4] == 1 ? 1 - led_a(i, n) : led_a(i, n);
|
||||
float x = rot - ang;
|
||||
float behind = x - floorf(x / span) * span;
|
||||
if (behind < width) {
|
||||
put(f, i, rig_entry(f, c, nc, RIG_SHADES, 0, top));
|
||||
} else {
|
||||
float fr = (behind - width) / tail;
|
||||
if (fr >= 1) {
|
||||
put(f, i, rig_entry(f, c, nc, RIG_SHADES, 0, 0));
|
||||
} else {
|
||||
int shade = (int)(fr * (RIG_SHADES - 1));
|
||||
int lv = (int)((1 - fr) * top);
|
||||
put(f, i, rig_entry(f, c, nc, RIG_SHADES, shade, lv));
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---- sweep -------------------------------------------------------------------------------------
|
||||
|
||||
bool fx_sweep(fx_t &f, st_t &s)
|
||||
{
|
||||
const rgb def[1] = { WHITE };
|
||||
rgb c[PATTERN_MAX_COLOURS];
|
||||
int nc = get_colours(f, def, 1, c);
|
||||
int n = f.n;
|
||||
const int top = RIG_LEVELS - 1;
|
||||
(void)first_call(s);
|
||||
for (int i = 0; i < n; i++) {
|
||||
s.m[i] = along(i, n, (float)f.pr->n[1]);
|
||||
s.shade[i] = shade_of(s.m[i]);
|
||||
}
|
||||
uint32_t total = dur(f, (int)f.pr->delay);
|
||||
if (total < 1) total = 1;
|
||||
float hw = (f.pr->n[2] > 0 ? f.pr->n[2] : 200) / 2000.0f;
|
||||
float trail = (f.pr->n[3] > 0 ? f.pr->n[3] : 0) / 1000.0f;
|
||||
bool keep = f.pr->n[4] == 1;
|
||||
uint32_t t = f.t;
|
||||
bool done = !f.pr->autorun && t >= total;
|
||||
float p = done ? 1.0f : (float)(t % total) / total;
|
||||
float head = -hw + p * (1 + 2 * hw + trail);
|
||||
for (int i = 0; i < n; i++) {
|
||||
float d = s.m[i] - head;
|
||||
float k;
|
||||
if (d > hw) {
|
||||
k = 0;
|
||||
} else if (d >= -hw) {
|
||||
k = (keep && d < 0) ? 1.0f : 1 - fabsf(d) / hw;
|
||||
} else if (keep) {
|
||||
k = 1;
|
||||
} else if (trail > 0) {
|
||||
k = 1 + (d + hw) / trail;
|
||||
if (k < 0) k = 0;
|
||||
} else {
|
||||
k = 0;
|
||||
}
|
||||
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], (int)(k * top)));
|
||||
}
|
||||
return done;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Helpers shared by the pattern files: integer maths that matches Python's // and %, colour mixing,
|
||||
* random numbers and the rig colour table.
|
||||
*/
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
#include "esp_random.h"
|
||||
#include "effects.h"
|
||||
|
||||
int clampi(int v, int lo, int hi)
|
||||
{
|
||||
return v < lo ? lo : (v > hi ? hi : v);
|
||||
}
|
||||
|
||||
int fdiv(int a, int b)
|
||||
{
|
||||
int q = a / b;
|
||||
if ((a % b != 0) && ((a < 0) != (b < 0))) {
|
||||
q--;
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
int pmod(int a, int m)
|
||||
{
|
||||
int r = a % m;
|
||||
return r < 0 ? r + m : r;
|
||||
}
|
||||
|
||||
int nz(int v, int def)
|
||||
{
|
||||
return v > 0 ? v : def;
|
||||
}
|
||||
|
||||
rgb mk(int r, int g, int b)
|
||||
{
|
||||
rgb c = { clampi(r, 0, 255), clampi(g, 0, 255), clampi(b, 0, 255) };
|
||||
return c;
|
||||
}
|
||||
|
||||
rgb ab(rgb c, int level)
|
||||
{
|
||||
rgb o = { fdiv(c.r * level, 255), fdiv(c.g * level, 255), fdiv(c.b * level, 255) };
|
||||
return o;
|
||||
}
|
||||
|
||||
rgb mix(rgb a, rgb b, int k)
|
||||
{
|
||||
rgb o = {
|
||||
a.r + fdiv((b.r - a.r) * k, 255),
|
||||
a.g + fdiv((b.g - a.g) * k, 255),
|
||||
a.b + fdiv((b.b - a.b) * k, 255),
|
||||
};
|
||||
return o;
|
||||
}
|
||||
|
||||
int sgn(const fx_t &f, int v)
|
||||
{
|
||||
return f.pr->reverse ? -v : v;
|
||||
}
|
||||
|
||||
int led_at(const fx_t &f, int i)
|
||||
{
|
||||
return (f.pr->reverse && i >= 0 && i < f.n) ? f.n - 1 - i : i;
|
||||
}
|
||||
|
||||
void put(fx_t &f, int phys, rgb c)
|
||||
{
|
||||
if (phys >= 0 && phys < f.n) {
|
||||
f.px[phys] = c;
|
||||
}
|
||||
}
|
||||
|
||||
void putl(fx_t &f, int logical, rgb c)
|
||||
{
|
||||
put(f, led_at(f, logical), c);
|
||||
}
|
||||
|
||||
void fill(fx_t &f, rgb c)
|
||||
{
|
||||
for (int i = 0; i < f.n; i++) {
|
||||
f.px[i] = c;
|
||||
}
|
||||
}
|
||||
|
||||
bool due(uint32_t now, uint32_t &last, uint32_t d)
|
||||
{
|
||||
if ((int32_t)(now - last) >= (int32_t)d) {
|
||||
last += d;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// The beat is 500 ms here (there is no beat source on this board)
|
||||
uint32_t dur(const fx_t &f, int v)
|
||||
{
|
||||
if (v < 0) {
|
||||
v = 0;
|
||||
}
|
||||
return f.pr->beat_time ? (uint32_t)(v * 500 / 4) : (uint32_t)v;
|
||||
}
|
||||
|
||||
int get_colours(const fx_t &f, const rgb *def, int ndef, rgb *out)
|
||||
{
|
||||
if (f.pr->ncol > 0) {
|
||||
int n = f.pr->ncol > PATTERN_MAX_COLOURS ? PATTERN_MAX_COLOURS : f.pr->ncol;
|
||||
for (int i = 0; i < n; i++) {
|
||||
out[i] = mk(f.pr->col[i][0], f.pr->col[i][1], f.pr->col[i][2]);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
for (int i = 0; i < ndef; i++) {
|
||||
out[i] = def[i];
|
||||
}
|
||||
return ndef;
|
||||
}
|
||||
|
||||
int rnd(int lo, int hi)
|
||||
{
|
||||
if (hi <= lo) {
|
||||
return lo;
|
||||
}
|
||||
return lo + (int)(esp_random() % (uint32_t)(hi - lo + 1));
|
||||
}
|
||||
|
||||
rgb grad_at(const rgb *cols, int m, float t)
|
||||
{
|
||||
if (m == 1 || t <= 0) {
|
||||
return cols[0];
|
||||
}
|
||||
if (t >= 1) {
|
||||
return cols[m - 1];
|
||||
}
|
||||
float x = t * (m - 1);
|
||||
int j = (int)x;
|
||||
float f = x - j;
|
||||
rgb a = cols[j];
|
||||
rgb b = cols[j + 1];
|
||||
rgb o = { (int)(a.r + (b.r - a.r) * f), (int)(a.g + (b.g - a.g) * f), (int)(a.b + (b.b - a.b) * f) };
|
||||
return o;
|
||||
}
|
||||
|
||||
// Colour of one entry of the rig table: a shade of the colour list at a brightness level (0..15),
|
||||
// over the background. Mirrors rig.Lut in the MicroPython driver.
|
||||
rgb rig_entry(const fx_t &f, const rgb *cols, int ncols, int shades, int shade, int level)
|
||||
{
|
||||
int b = f.pr->brightness;
|
||||
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||
rgb c = (shades > 1) ? grad_at(cols, ncols, (float)shade / (shades - 1)) : cols[0];
|
||||
rgb sc = { fdiv((int)c.r * b, 255), fdiv((int)c.g * b, 255), fdiv((int)c.b * b, 255) };
|
||||
int top = RIG_LEVELS - 1;
|
||||
rgb o = {
|
||||
bgc.r + fdiv((sc.r - bgc.r) * level, top),
|
||||
bgc.g + fdiv((sc.g - bgc.g) * level, top),
|
||||
bgc.b + fdiv((sc.b - bgc.b) * level, top),
|
||||
};
|
||||
return o;
|
||||
}
|
||||
|
||||
// Hue wheel, 0..255 -> colour
|
||||
rgb wheel(int pos)
|
||||
{
|
||||
pos &= 255;
|
||||
rgb c;
|
||||
if (pos < 85) {
|
||||
c.r = pos * 3;
|
||||
c.g = 255 - pos * 3;
|
||||
c.b = 0;
|
||||
} else if (pos < 170) {
|
||||
pos -= 85;
|
||||
c.r = 255 - pos * 3;
|
||||
c.g = 0;
|
||||
c.b = pos * 3;
|
||||
} else {
|
||||
pos -= 170;
|
||||
c.r = 0;
|
||||
c.g = pos * 3;
|
||||
c.b = 255 - pos * 3;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
dependencies:
|
||||
espressif/mdns:
|
||||
version: "^1.4.0"
|
||||
espressif/cjson:
|
||||
version: "^1.7.19"
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
|
||||
#include "ddp.h"
|
||||
#include "net.h"
|
||||
#include "ota.h"
|
||||
#include "patterns.h"
|
||||
#include "presets.h"
|
||||
#include "web.h"
|
||||
|
||||
static const char *TAG = "example";
|
||||
|
||||
extern "C" void app_main(void)
|
||||
{
|
||||
// NVS holds the saved Wi-Fi client credentials
|
||||
esp_err_t err = nvs_flash_init();
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
err = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(err);
|
||||
|
||||
hw_cfg_t hw;
|
||||
settings_load_hw(&hw);
|
||||
patterns_start(hw);
|
||||
ESP_ERROR_CHECK(presets_init());
|
||||
presets_apply_startup();
|
||||
ESP_ERROR_CHECK(net_start());
|
||||
ESP_ERROR_CHECK(web_start());
|
||||
ESP_ERROR_CHECK(ddp_start());
|
||||
ota_confirm_later();
|
||||
|
||||
char ssid[16];
|
||||
net_ap_ssid(ssid, sizeof(ssid));
|
||||
ESP_LOGI(TAG, "Ready: join Wi-Fi %s and open http://192.168.4.1/, or http://led.local/ on your network", ssid);
|
||||
}
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_mac.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_timer.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "mdns.h"
|
||||
#include "net.h"
|
||||
|
||||
static const char *TAG = "net";
|
||||
|
||||
#define AP_CHANNEL 1
|
||||
#define AP_MAX_CLIENTS 4
|
||||
#define RETRY_MAX_MS 30000
|
||||
|
||||
static esp_netif_t *s_ap_netif;
|
||||
static esp_netif_t *s_sta_netif;
|
||||
static esp_timer_handle_t s_retry_timer;
|
||||
static volatile bool s_sta_up;
|
||||
static esp_ip4_addr_t s_sta_ip;
|
||||
static int s_retries;
|
||||
|
||||
// Set the STA config from credentials. Empty password means an open network.
|
||||
static void apply_sta_config(const wifi_creds_t *c)
|
||||
{
|
||||
wifi_config_t cfg = {};
|
||||
strncpy((char *)cfg.sta.ssid, c->ssid, sizeof(cfg.sta.ssid) - 1);
|
||||
strncpy((char *)cfg.sta.password, c->pass, sizeof(cfg.sta.password) - 1);
|
||||
cfg.sta.threshold.authmode = c->pass[0] ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN;
|
||||
esp_wifi_set_config(WIFI_IF_STA, &cfg);
|
||||
}
|
||||
|
||||
// Client address: DHCP, or the static address from settings. Called before the client connects.
|
||||
static esp_err_t apply_client_ip(const net_cfg_t *c)
|
||||
{
|
||||
if (!c->use_static) {
|
||||
esp_err_t err = esp_netif_dhcpc_start(s_sta_netif);
|
||||
// Already running is fine
|
||||
return (err == ESP_OK || err == ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) ? ESP_OK : err;
|
||||
}
|
||||
esp_netif_ip_info_t info = {};
|
||||
if (esp_netif_str_to_ip4(c->ip, &info.ip) != ESP_OK ||
|
||||
esp_netif_str_to_ip4(c->netmask, &info.netmask) != ESP_OK ||
|
||||
esp_netif_str_to_ip4(c->gateway, &info.gw) != ESP_OK) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
esp_netif_dhcpc_stop(s_sta_netif); // ignore "not started"
|
||||
esp_err_t err = esp_netif_set_ip_info(s_sta_netif, &info);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
esp_netif_dns_info_t dns = {};
|
||||
const char *dns_str = c->dns[0] ? c->dns : c->gateway;
|
||||
if (esp_netif_str_to_ip4(dns_str, &dns.ip.u_addr.ip4) == ESP_OK) {
|
||||
dns.ip.type = ESP_IPADDR_TYPE_V4;
|
||||
esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
|
||||
}
|
||||
ESP_LOGI(TAG, "Client static IP %s/%s gw %s", c->ip, c->netmask, c->gateway);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void retry_cb(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
esp_wifi_connect();
|
||||
}
|
||||
|
||||
static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *data)
|
||||
{
|
||||
(void)arg;
|
||||
(void)base;
|
||||
(void)data;
|
||||
switch (id) {
|
||||
case WIFI_EVENT_STA_START: {
|
||||
wifi_creds_t c;
|
||||
if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) {
|
||||
net_cfg_t n;
|
||||
settings_load_net(&n);
|
||||
if (apply_client_ip(&n) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "Static IP settings are invalid; using DHCP");
|
||||
n.use_static = false;
|
||||
apply_client_ip(&n);
|
||||
}
|
||||
esp_wifi_connect();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case WIFI_EVENT_STA_DISCONNECTED: {
|
||||
// Back off 1 s, 2 s, 4 s ... up to RETRY_MAX_MS
|
||||
s_sta_up = false;
|
||||
uint32_t delay_ms = 1000u << (s_retries < 5 ? s_retries : 5);
|
||||
if (delay_ms > RETRY_MAX_MS) delay_ms = RETRY_MAX_MS;
|
||||
s_retries++;
|
||||
esp_timer_stop(s_retry_timer);
|
||||
esp_timer_start_once(s_retry_timer, (uint64_t)delay_ms * 1000);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void on_ip_event(void *arg, esp_event_base_t base, int32_t id, void *data)
|
||||
{
|
||||
(void)arg;
|
||||
(void)base;
|
||||
(void)id;
|
||||
ip_event_got_ip_t *e = (ip_event_got_ip_t *)data;
|
||||
s_sta_ip = e->ip_info.ip;
|
||||
s_sta_up = true;
|
||||
s_retries = 0;
|
||||
ESP_LOGI(TAG, "Client IP " IPSTR, IP2STR(&e->ip_info.ip));
|
||||
}
|
||||
|
||||
void net_ap_ssid(char *buf, size_t len)
|
||||
{
|
||||
uint8_t mac[6];
|
||||
esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP);
|
||||
snprintf(buf, len, "led-%02X%02X%02X", mac[3], mac[4], mac[5]);
|
||||
}
|
||||
|
||||
esp_err_t net_start(void)
|
||||
{
|
||||
ESP_ERROR_CHECK(esp_netif_init());
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
s_ap_netif = esp_netif_create_default_wifi_ap();
|
||||
s_sta_netif = esp_netif_create_default_wifi_sta();
|
||||
|
||||
wifi_init_config_t init_cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&init_cfg));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, on_wifi_event, NULL, NULL));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_ip_event, NULL, NULL));
|
||||
|
||||
const esp_timer_create_args_t timer_args = {
|
||||
.callback = retry_cb,
|
||||
.arg = NULL,
|
||||
.dispatch_method = ESP_TIMER_TASK,
|
||||
.name = "wifi_retry",
|
||||
.skip_unhandled_events = false,
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &s_retry_timer));
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
|
||||
|
||||
// Open access point named led-XXXXXX
|
||||
char ssid[16];
|
||||
net_ap_ssid(ssid, sizeof(ssid));
|
||||
wifi_config_t ap = {};
|
||||
strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1);
|
||||
ap.ap.ssid_len = strlen(ssid);
|
||||
ap.ap.channel = AP_CHANNEL;
|
||||
ap.ap.max_connection = AP_MAX_CLIENTS;
|
||||
ap.ap.authmode = WIFI_AUTH_OPEN;
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap));
|
||||
|
||||
// Client credentials, if any were saved
|
||||
wifi_creds_t c;
|
||||
if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) {
|
||||
apply_sta_config(&c);
|
||||
}
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
ESP_LOGI(TAG, "AP %s started", ssid);
|
||||
|
||||
// mDNS: <hostname>.local, with an HTTP service on port 80
|
||||
net_cfg_t n;
|
||||
settings_load_net(&n);
|
||||
ESP_ERROR_CHECK(mdns_init());
|
||||
ESP_ERROR_CHECK(mdns_hostname_set(n.hostname));
|
||||
ESP_ERROR_CHECK(mdns_instance_name_set("LED controller"));
|
||||
// app=led-strip lets other drivers' discovery (GET /api/devices) pick out LED drivers from other HTTP devices
|
||||
static mdns_txt_item_t txt[] = { { "app", "led-strip" } };
|
||||
ESP_ERROR_CHECK(mdns_service_add(NULL, "_http", "_tcp", 80, txt, 1));
|
||||
ESP_LOGI(TAG, "mDNS: %s.local", n.hostname);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
bool net_sta_status(char *ip, size_t ip_len)
|
||||
{
|
||||
if (ip_len) {
|
||||
ip[0] = '\0';
|
||||
}
|
||||
if (!s_sta_up) {
|
||||
return false;
|
||||
}
|
||||
snprintf(ip, ip_len, IPSTR, IP2STR(&s_sta_ip));
|
||||
return true;
|
||||
}
|
||||
|
||||
esp_err_t net_sta_connect(const wifi_creds_t *c)
|
||||
{
|
||||
esp_err_t err = settings_save_wifi(c);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
esp_timer_stop(s_retry_timer);
|
||||
esp_wifi_disconnect();
|
||||
s_retries = 0;
|
||||
apply_sta_config(c);
|
||||
return esp_wifi_connect();
|
||||
}
|
||||
|
||||
esp_err_t net_save_network(const net_cfg_t *c)
|
||||
{
|
||||
esp_err_t err = settings_save_net(c);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
err = mdns_hostname_set(c->hostname);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
// Reconnect with the new address settings if a client is configured
|
||||
wifi_creds_t w;
|
||||
if (settings_load_wifi(&w) != ESP_OK || !w.ssid[0]) {
|
||||
return ESP_OK;
|
||||
}
|
||||
esp_timer_stop(s_retry_timer);
|
||||
esp_wifi_disconnect();
|
||||
s_retries = 0;
|
||||
err = apply_client_ip(c);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
return esp_wifi_connect();
|
||||
}
|
||||
|
||||
esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count)
|
||||
{
|
||||
esp_err_t err = esp_wifi_scan_start(NULL, true);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
uint16_t max = *count;
|
||||
err = esp_wifi_scan_get_ap_records(&max, recs);
|
||||
*count = max;
|
||||
return err;
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_wifi_types.h"
|
||||
#include "settings.h"
|
||||
|
||||
/** @brief Start Wi-Fi (AP `led-XXXXXX` plus an optional client), and mDNS. Needs NVS. */
|
||||
esp_err_t net_start(void);
|
||||
|
||||
/** @brief Fill buf with the AP SSID, e.g. "led-A1B2C3". */
|
||||
void net_ap_ssid(char *buf, size_t len);
|
||||
|
||||
/** @brief Client link state and its IPv4 address ("" if not connected). */
|
||||
bool net_sta_status(char *ip, size_t ip_len);
|
||||
|
||||
/** @brief Save credentials, then connect the client with them. */
|
||||
esp_err_t net_sta_connect(const wifi_creds_t *c);
|
||||
|
||||
/**
|
||||
* @brief Save network settings and apply them: mDNS name, static or DHCP client address.
|
||||
* A connected or configured client reconnects so the new address takes effect.
|
||||
*/
|
||||
esp_err_t net_save_network(const net_cfg_t *c);
|
||||
|
||||
/** @brief Scan for networks. On entry *count is the array size; on exit, the number found. */
|
||||
esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count);
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
#include "ota.h"
|
||||
#include "web.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_ota_ops.h"
|
||||
#include "esp_app_format.h"
|
||||
#include "esp_system.h"
|
||||
#include <string.h>
|
||||
#include "esp_timer.h"
|
||||
|
||||
static const char *TAG = "ota";
|
||||
|
||||
#define CHUNK 4096
|
||||
#define CONFIRM_AFTER_US (10 * 1000000LL)
|
||||
|
||||
static bool s_busy;
|
||||
|
||||
static void reboot_cb(void *arg)
|
||||
{
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
static void confirm_cb(void *arg)
|
||||
{
|
||||
esp_err_t err = esp_ota_mark_app_valid_cancel_rollback();
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "running image confirmed");
|
||||
}
|
||||
}
|
||||
|
||||
void ota_confirm_later(void)
|
||||
{
|
||||
esp_ota_img_states_t state;
|
||||
const esp_partition_t *run = esp_ota_get_running_partition();
|
||||
if (esp_ota_get_state_partition(run, &state) != ESP_OK || state != ESP_OTA_IMG_PENDING_VERIFY) {
|
||||
return;
|
||||
}
|
||||
static esp_timer_handle_t t;
|
||||
const esp_timer_create_args_t args = { .callback = confirm_cb, .name = "ota_confirm" };
|
||||
if (esp_timer_create(&args, &t) == ESP_OK) {
|
||||
esp_timer_start_once(t, CONFIRM_AFTER_US);
|
||||
}
|
||||
}
|
||||
|
||||
static esp_err_t fail(httpd_req_t *req, const char *status, const char *msg)
|
||||
{
|
||||
ESP_LOGE(TAG, "%s", msg);
|
||||
httpd_resp_set_status(req, status);
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
web_allow_lan_origin(req);
|
||||
char buf[160];
|
||||
snprintf(buf, sizeof(buf), "{\"error\":\"%s\"}", msg);
|
||||
return httpd_resp_sendstr(req, buf);
|
||||
}
|
||||
|
||||
static esp_err_t ota_post_handler(httpd_req_t *req)
|
||||
{
|
||||
if (req->content_len == 0) {
|
||||
return fail(req, "400 Bad Request", "empty body");
|
||||
}
|
||||
const esp_partition_t *part = esp_ota_get_next_update_partition(NULL);
|
||||
if (!part) {
|
||||
return fail(req, "500 Internal Server Error", "no update partition");
|
||||
}
|
||||
if (req->content_len > part->size) {
|
||||
return fail(req, "413 Payload Too Large", "image larger than the app slot");
|
||||
}
|
||||
if (s_busy) {
|
||||
return fail(req, "409 Conflict", "update already running");
|
||||
}
|
||||
s_busy = true;
|
||||
|
||||
char *buf = malloc(CHUNK);
|
||||
if (!buf) {
|
||||
s_busy = false;
|
||||
return fail(req, "500 Internal Server Error", "out of memory");
|
||||
}
|
||||
|
||||
esp_ota_handle_t handle = 0;
|
||||
esp_err_t err = esp_ota_begin(part, req->content_len, &handle);
|
||||
if (err != ESP_OK) {
|
||||
free(buf);
|
||||
s_busy = false;
|
||||
return fail(req, "500 Internal Server Error", "ota begin failed");
|
||||
}
|
||||
ESP_LOGI(TAG, "receiving %u bytes into %s", (unsigned)req->content_len, part->label);
|
||||
|
||||
size_t got = 0;
|
||||
const char *bad = NULL;
|
||||
while (got < req->content_len) {
|
||||
int want = req->content_len - got;
|
||||
int r = httpd_req_recv(req, buf, want > CHUNK ? CHUNK : want);
|
||||
if (r == HTTPD_SOCK_ERR_TIMEOUT) {
|
||||
continue;
|
||||
}
|
||||
if (r <= 0) {
|
||||
bad = "receive failed";
|
||||
break;
|
||||
}
|
||||
if (got == 0 && (r < (int)(sizeof(esp_image_header_t)) || (uint8_t)buf[0] != ESP_IMAGE_HEADER_MAGIC)) {
|
||||
bad = "not an ESP32 app image";
|
||||
break;
|
||||
}
|
||||
if (esp_ota_write(handle, buf, r) != ESP_OK) {
|
||||
bad = "flash write failed";
|
||||
break;
|
||||
}
|
||||
got += r;
|
||||
}
|
||||
free(buf);
|
||||
if (bad) {
|
||||
esp_ota_abort(handle);
|
||||
s_busy = false;
|
||||
return fail(req, "400 Bad Request", bad);
|
||||
}
|
||||
// esp_ota_end checks the image checksum and hash
|
||||
if (esp_ota_end(handle) != ESP_OK) {
|
||||
s_busy = false;
|
||||
return fail(req, "400 Bad Request", "image failed validation");
|
||||
}
|
||||
if (esp_ota_set_boot_partition(part) != ESP_OK) {
|
||||
s_busy = false;
|
||||
return fail(req, "500 Internal Server Error", "set boot partition failed");
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "update ok, rebooting");
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
web_allow_lan_origin(req);
|
||||
httpd_resp_sendstr(req, "{\"message\":\"update written, rebooting\"}");
|
||||
|
||||
static esp_timer_handle_t t;
|
||||
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "ota_reboot" };
|
||||
if (esp_timer_create(&args, &t) == ESP_OK) {
|
||||
esp_timer_start_once(t, 500 * 1000);
|
||||
} else {
|
||||
esp_restart();
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t ota_get_handler(httpd_req_t *req)
|
||||
{
|
||||
const esp_partition_t *run = esp_ota_get_running_partition();
|
||||
const esp_app_desc_t *app = esp_app_get_description();
|
||||
// The build date is only recompiled with its own file, so the ELF hash is what tells two builds apart
|
||||
char sha[17];
|
||||
for (int i = 0; i < 8; i++) {
|
||||
snprintf(sha + 2 * i, 3, "%02x", app->app_elf_sha256[i]);
|
||||
}
|
||||
char buf[288];
|
||||
snprintf(buf, sizeof(buf),
|
||||
"{\"partition\":\"%s\",\"version\":\"%s\",\"built\":\"%s %s\",\"idf\":\"%s\",\"sha\":\"%s\"}",
|
||||
run ? run->label : "?", app->version, app->date, app->time, app->idf_ver, sha);
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
web_allow_lan_origin(req);
|
||||
return httpd_resp_sendstr(req, buf);
|
||||
}
|
||||
|
||||
static esp_err_t reboot_post_handler(httpd_req_t *req)
|
||||
{
|
||||
ESP_LOGI(TAG, "reboot requested");
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
web_allow_lan_origin(req);
|
||||
httpd_resp_sendstr(req, "{\"message\":\"rebooting\"}");
|
||||
|
||||
static esp_timer_handle_t t;
|
||||
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "reboot" };
|
||||
if (esp_timer_create(&args, &t) == ESP_OK) {
|
||||
esp_timer_start_once(t, 500 * 1000);
|
||||
} else {
|
||||
esp_restart();
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// Browser preflight for a firmware upload from another device's page (octet-stream is not a simple request)
|
||||
static esp_err_t ota_preflight_handler(httpd_req_t *req)
|
||||
{
|
||||
web_allow_lan_origin(req);
|
||||
httpd_resp_set_hdr(req, "Access-Control-Allow-Methods", "POST");
|
||||
httpd_resp_set_hdr(req, "Access-Control-Allow-Headers", "Content-Type");
|
||||
httpd_resp_set_hdr(req, "Access-Control-Max-Age", "600");
|
||||
httpd_resp_set_status(req, "204 No Content");
|
||||
return httpd_resp_send(req, NULL, 0);
|
||||
}
|
||||
|
||||
esp_err_t ota_register(httpd_handle_t server)
|
||||
{
|
||||
const httpd_uri_t post = { .uri = "/ota", .method = HTTP_POST, .handler = ota_post_handler };
|
||||
const httpd_uri_t get = { .uri = "/ota", .method = HTTP_GET, .handler = ota_get_handler };
|
||||
const httpd_uri_t preflight = { .uri = "/ota", .method = HTTP_OPTIONS, .handler = ota_preflight_handler };
|
||||
esp_err_t err = httpd_register_uri_handler(server, &post);
|
||||
if (err == ESP_OK) {
|
||||
err = httpd_register_uri_handler(server, &get);
|
||||
}
|
||||
if (err == ESP_OK) {
|
||||
err = httpd_register_uri_handler(server, &preflight);
|
||||
}
|
||||
const httpd_uri_t reboot = { .uri = "/reboot", .method = HTTP_POST, .handler = reboot_post_handler };
|
||||
if (err == ESP_OK) {
|
||||
err = httpd_register_uri_handler(server, &reboot);
|
||||
}
|
||||
return err;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_http_server.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Register POST /ota (raw firmware .bin as the body) and GET /ota (running image info).
|
||||
// The web UI is part of the image, so one upload updates both.
|
||||
// POST /reboot restarts the board (replies first, reboots after 0.5 s).
|
||||
// A good upload is written to the idle app slot, becomes the boot image and the board reboots.
|
||||
esp_err_t ota_register(httpd_handle_t server);
|
||||
|
||||
// Call once at boot: confirms the running image after it has stayed up for a few seconds, so
|
||||
// a new image that crashes on start rolls back to the previous one.
|
||||
void ota_confirm_later(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,464 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Pattern engine: runs the selected pattern once per frame into a shadow frame, crossfades from the
|
||||
* previous frame when a preset asks for it, and shows the result on the WS2812 strip.
|
||||
*/
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#include "driver/gpio.h"
|
||||
#include "esp_heap_caps.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_timer.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
#include "effects.h"
|
||||
#include "patterns.h"
|
||||
#include "settings.h"
|
||||
#include "ws2812.h"
|
||||
|
||||
#define FRAME_MS 10
|
||||
|
||||
static const char *TAG = "patterns";
|
||||
|
||||
typedef bool (*fx_fn)(fx_t &, st_t &);
|
||||
struct pattern_def_t {
|
||||
const char *name;
|
||||
fx_fn fn;
|
||||
};
|
||||
|
||||
// Same names as the MicroPython led-driver patterns
|
||||
static const pattern_def_t kPatterns[] = {
|
||||
{ "off", fx_off },
|
||||
{ "on", fx_on },
|
||||
{ "blink", fx_blink },
|
||||
{ "aurora", fx_aurora },
|
||||
{ "bar_graph", fx_bar_graph },
|
||||
{ "blizzard", fx_blizzard },
|
||||
{ "candle_glow", fx_candle_glow },
|
||||
{ "chase", fx_chase },
|
||||
{ "circle", fx_circle },
|
||||
{ "clock_sweep", fx_clock_sweep },
|
||||
{ "colour_cycle", fx_colour_cycle },
|
||||
{ "field_wave", fx_field_wave },
|
||||
{ "flame", fx_flame },
|
||||
{ "flicker", fx_flicker },
|
||||
{ "gradient_wipe", fx_gradient_wipe },
|
||||
{ "grow", fx_grow },
|
||||
{ "hit", fx_hit },
|
||||
{ "icicles", fx_icicles },
|
||||
{ "keyframes", fx_keyframes },
|
||||
{ "meteor", fx_meteor },
|
||||
{ "orbit", fx_orbit },
|
||||
{ "palette_morph", fx_palette_morph },
|
||||
{ "particles", fx_particles },
|
||||
{ "plasma", fx_plasma },
|
||||
{ "pulse", fx_pulse },
|
||||
{ "radiate", fx_radiate },
|
||||
{ "rain_drops", fx_rain_drops },
|
||||
{ "rime", fx_rime },
|
||||
{ "ripple", fx_ripple },
|
||||
{ "sparkle", fx_sparkle },
|
||||
{ "spin", fx_spin },
|
||||
{ "strobe_burst", fx_strobe_burst },
|
||||
{ "sweep", fx_sweep },
|
||||
{ "transition", fx_transition },
|
||||
{ "twinkle", fx_twinkle },
|
||||
};
|
||||
#define PATTERN_COUNT ((int)(sizeof(kPatterns) / sizeof(kPatterns[0])))
|
||||
|
||||
static WS2812 *s_strip;
|
||||
static SemaphoreHandle_t s_lock;
|
||||
static preset_t s_cur; // the preset requested (under s_lock)
|
||||
static bool s_reset_pending; // a new pattern was selected (under s_lock)
|
||||
|
||||
static preset_t s_run; // the preset the task is running
|
||||
static fx_t s_fx; // shadow frame and timing for the running pattern
|
||||
st_t g_st; // state of the running pattern
|
||||
|
||||
// Crossfade: the last frame shown, and the frame it fades from
|
||||
static rgb *s_shown; // last frame shown (s_cap entries)
|
||||
static rgb *s_from; // frame the crossfade starts from
|
||||
static int s_cap; // LEDs the buffers are sized for
|
||||
static bool s_fading;
|
||||
|
||||
// DDP: pixels sent by a controller. While they keep arriving they replace the pattern.
|
||||
#define DDP_TIMEOUT_MS 2000
|
||||
static uint8_t s_ddp[FX_LEDS_MAX * 3];
|
||||
static uint32_t s_ddp_last_ms; // 0: never
|
||||
static bool s_ddp_was;
|
||||
static uint32_t s_ddp_packets;
|
||||
static uint32_t s_ddp_frames; // frames completed (PUSH seen)
|
||||
static uint32_t s_ddp_sum; // checksum of the last completed frame
|
||||
static uint32_t s_ddp_log_ms; // last serial summary
|
||||
static uint8_t s_max_brightness = 255;
|
||||
static uint8_t s_global = 255;
|
||||
static uint32_t s_fade_t0;
|
||||
static uint32_t s_fade_ms;
|
||||
|
||||
int patterns_count(void)
|
||||
{
|
||||
return PATTERN_COUNT;
|
||||
}
|
||||
|
||||
const char *patterns_name(int i)
|
||||
{
|
||||
return (i >= 0 && i < PATTERN_COUNT) ? kPatterns[i].name : "";
|
||||
}
|
||||
|
||||
int patterns_index(const char *name)
|
||||
{
|
||||
for (int i = 0; i < PATTERN_COUNT; i++) {
|
||||
if (strcmp(name, kPatterns[i].name) == 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void preset_defaults(preset_t *p, int pattern)
|
||||
{
|
||||
memset(p, 0, sizeof(*p));
|
||||
p->pattern = pattern;
|
||||
p->ncol = 0;
|
||||
p->delay = 100;
|
||||
p->brightness = 127;
|
||||
p->autorun = true;
|
||||
p->reverse = false;
|
||||
p->fade = 0;
|
||||
p->beat_time = false;
|
||||
}
|
||||
|
||||
// Keep a preset within the ranges the patterns expect
|
||||
static void sanitize(preset_t *p)
|
||||
{
|
||||
if (p->pattern < 0 || p->pattern >= PATTERN_COUNT) {
|
||||
p->pattern = 0;
|
||||
}
|
||||
if (p->delay < 10) p->delay = 10;
|
||||
if (p->delay > 10000) p->delay = 10000;
|
||||
if (p->ncol < 0) p->ncol = 0;
|
||||
if (p->ncol > PATTERN_MAX_COLOURS) p->ncol = PATTERN_MAX_COLOURS;
|
||||
if (p->fade > 10000) p->fade = 10000;
|
||||
for (int i = 1; i <= 6; i++) {
|
||||
if (p->n[i] < 0) p->n[i] = 0;
|
||||
if (p->n[i] > 100000) p->n[i] = 100000;
|
||||
}
|
||||
}
|
||||
|
||||
// Live update: a change of pattern restarts it (with a crossfade if the preset asks); other changes
|
||||
// take effect straight away, keeping the pattern's place
|
||||
void patterns_set(const preset_t &p)
|
||||
{
|
||||
preset_t q = p;
|
||||
sanitize(&q);
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
bool changed = q.pattern != s_cur.pattern;
|
||||
s_cur = q;
|
||||
if (changed) {
|
||||
s_reset_pending = true;
|
||||
}
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
// Select a preset: always restarts the pattern, crossfading in from the frame on the strip
|
||||
void patterns_select(const preset_t &p)
|
||||
{
|
||||
preset_t q = p;
|
||||
sanitize(&q);
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
s_cur = q;
|
||||
s_reset_pending = true;
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
void patterns_set_global(uint8_t level)
|
||||
{
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
s_global = level;
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
uint8_t patterns_get_global(void)
|
||||
{
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
uint8_t v = s_global;
|
||||
xSemaphoreGive(s_lock);
|
||||
return v;
|
||||
}
|
||||
|
||||
void patterns_get(preset_t *out)
|
||||
{
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
*out = s_cur;
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
static uint32_t now_ms(void)
|
||||
{
|
||||
return (uint32_t)(esp_timer_get_time() / 1000);
|
||||
}
|
||||
|
||||
// Show the shadow frame, crossfading from the previous frame while a fade runs
|
||||
static void output(uint32_t now)
|
||||
{
|
||||
int s_scale = s_global * s_max_brightness / 255; // global brightness under the ceiling
|
||||
int k = -1;
|
||||
if (s_fading) {
|
||||
uint32_t el = now - s_fade_t0;
|
||||
if (el >= s_fade_ms) {
|
||||
s_fading = false;
|
||||
} else {
|
||||
k = (int)((el * 256) / s_fade_ms);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < s_fx.n; i++) {
|
||||
rgb c = s_fx.px[i];
|
||||
c.r = c.r * s_scale / 255;
|
||||
c.g = c.g * s_scale / 255;
|
||||
c.b = c.b * s_scale / 255;
|
||||
if (k >= 0) {
|
||||
rgb a = s_from[i];
|
||||
c.r = (a.r * (256 - k) + c.r * k) >> 8;
|
||||
c.g = (a.g * (256 - k) + c.g * k) >> 8;
|
||||
c.b = (a.b * (256 - k) + c.b * k) >> 8;
|
||||
}
|
||||
s_strip->set(i, c.r, c.g, c.b);
|
||||
s_shown[i] = c;
|
||||
}
|
||||
esp_err_t err = s_strip->write();
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "LED write failed: %s", esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- per-LED buffers --------------------------------------------------------------------------
|
||||
|
||||
bool frame_alloc(int n)
|
||||
{
|
||||
if (n < 1) n = 1;
|
||||
if (n > FX_LEDS_MAX) n = FX_LEDS_MAX;
|
||||
void *fresh[12] = {
|
||||
calloc(n, sizeof(rgb)), calloc(n, sizeof(rgb)), calloc(n, sizeof(rgb)),
|
||||
calloc(n, sizeof(int)), calloc(n, sizeof(float)), calloc(n, sizeof(int)),
|
||||
calloc(n, 1), calloc(n, 1),
|
||||
calloc(n, sizeof(int)), calloc(n, sizeof(int)),
|
||||
calloc(n, sizeof(int)), calloc(n, sizeof(int)),
|
||||
};
|
||||
for (int k = 0; k < 12; k++) {
|
||||
if (!fresh[k]) {
|
||||
for (int j = 0; j < 12; j++) free(fresh[j]);
|
||||
ESP_LOGE(TAG, "Out of memory for %d LEDs", n);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
free(s_fx.px);
|
||||
free(s_shown);
|
||||
free(s_from);
|
||||
free(g_st.glow);
|
||||
free(g_st.m);
|
||||
free(g_st.shade);
|
||||
free(g_st.on);
|
||||
free(g_st.next_on);
|
||||
free(g_st.col_i);
|
||||
free(g_st.next_ci);
|
||||
free(g_st.light);
|
||||
free(g_st.dark);
|
||||
s_fx.px = (rgb *)fresh[0];
|
||||
s_shown = (rgb *)fresh[1];
|
||||
s_from = (rgb *)fresh[2];
|
||||
g_st.glow = (int *)fresh[3];
|
||||
g_st.m = (float *)fresh[4];
|
||||
g_st.shade = (int *)fresh[5];
|
||||
g_st.on = (uint8_t *)fresh[6];
|
||||
g_st.next_on = (uint8_t *)fresh[7];
|
||||
g_st.col_i = (int *)fresh[8];
|
||||
g_st.next_ci = (int *)fresh[9];
|
||||
g_st.light = (int *)fresh[10];
|
||||
g_st.dark = (int *)fresh[11];
|
||||
s_cap = n;
|
||||
return true;
|
||||
}
|
||||
|
||||
void st_reset(void)
|
||||
{
|
||||
int *glow = g_st.glow, *shade = g_st.shade, *col_i = g_st.col_i, *next_ci = g_st.next_ci;
|
||||
int *light = g_st.light, *dark = g_st.dark;
|
||||
float *m = g_st.m;
|
||||
uint8_t *on = g_st.on, *next_on = g_st.next_on;
|
||||
memset(&g_st, 0, sizeof(g_st));
|
||||
g_st.glow = glow;
|
||||
g_st.shade = shade;
|
||||
g_st.col_i = col_i;
|
||||
g_st.next_ci = next_ci;
|
||||
g_st.light = light;
|
||||
g_st.dark = dark;
|
||||
g_st.m = m;
|
||||
g_st.on = on;
|
||||
g_st.next_on = next_on;
|
||||
memset(glow, 0, s_cap * sizeof(int));
|
||||
memset(shade, 0, s_cap * sizeof(int));
|
||||
memset(col_i, 0, s_cap * sizeof(int));
|
||||
memset(next_ci, 0, s_cap * sizeof(int));
|
||||
memset(light, 0, s_cap * sizeof(int));
|
||||
memset(dark, 0, s_cap * sizeof(int));
|
||||
memset(m, 0, s_cap * sizeof(float));
|
||||
memset(on, 0, s_cap);
|
||||
memset(next_on, 0, s_cap);
|
||||
}
|
||||
|
||||
// The whole frame (pattern and output) runs under s_lock, so the buffers can't be replaced mid-frame
|
||||
static void patterns_task(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
s_fx.pr = &s_run;
|
||||
while (true) {
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
bool reset = s_reset_pending;
|
||||
s_reset_pending = false;
|
||||
s_run = s_cur;
|
||||
uint32_t now = now_ms();
|
||||
bool ddp_on = s_ddp_last_ms != 0 && now - s_ddp_last_ms < DDP_TIMEOUT_MS;
|
||||
if (!ddp_on && s_ddp_was) {
|
||||
reset = true; // the pattern starts again when the pixels stop
|
||||
}
|
||||
s_ddp_was = ddp_on;
|
||||
if (reset) {
|
||||
if (s_run.fade > 0) {
|
||||
memcpy(s_from, s_shown, s_fx.n * sizeof(rgb));
|
||||
s_fading = true;
|
||||
s_fade_t0 = now;
|
||||
s_fade_ms = s_run.fade;
|
||||
} else {
|
||||
s_fading = false;
|
||||
}
|
||||
st_reset();
|
||||
g_st.t0 = now;
|
||||
}
|
||||
s_fx.now = now;
|
||||
s_fx.t = now - g_st.t0;
|
||||
if (ddp_on) {
|
||||
for (int i = 0; i < s_fx.n; i++) {
|
||||
s_fx.px[i] = { s_ddp[3 * i], s_ddp[3 * i + 1], s_ddp[3 * i + 2] };
|
||||
}
|
||||
} else if (!g_st.done) {
|
||||
if (kPatterns[s_run.pattern].fn(s_fx, g_st)) {
|
||||
g_st.done = true;
|
||||
}
|
||||
}
|
||||
output(now);
|
||||
xSemaphoreGive(s_lock);
|
||||
vTaskDelay(pdMS_TO_TICKS(FRAME_MS));
|
||||
}
|
||||
}
|
||||
|
||||
static int clamp_leds(int n)
|
||||
{
|
||||
return n < 1 ? 1 : (n > FX_LEDS_MAX ? FX_LEDS_MAX : n);
|
||||
}
|
||||
|
||||
void patterns_start(const hw_cfg_t &hw)
|
||||
{
|
||||
s_lock = xSemaphoreCreateMutex();
|
||||
preset_defaults(&s_cur, 0);
|
||||
preset_defaults(&s_run, 0);
|
||||
s_cur.pattern = patterns_index("chase");
|
||||
s_cur.delay = 1000;
|
||||
s_cur.brightness = 16;
|
||||
s_cur.col[0][0] = 255;
|
||||
s_reset_pending = true;
|
||||
|
||||
int n = clamp_leds(hw.num_leds);
|
||||
if (!frame_alloc(n)) {
|
||||
ESP_ERROR_CHECK(ESP_ERR_NO_MEM);
|
||||
}
|
||||
s_fx.n = n;
|
||||
s_max_brightness = hw.max_brightness;
|
||||
s_global = hw.global_brightness;
|
||||
s_strip = new WS2812((gpio_num_t)hw.pin, n);
|
||||
s_strip->setOrder(hw.order);
|
||||
s_strip->setBrightness(255); // brightness is applied per colour by the patterns
|
||||
xTaskCreate(patterns_task, "patterns", 6144, NULL, 5, NULL);
|
||||
ESP_LOGI(TAG, "Started %d LEDs on GPIO %d (%s), %d patterns", n, hw.pin, hw.order, PATTERN_COUNT);
|
||||
}
|
||||
|
||||
// Change the strip: count, byte order and brightness ceiling. The buffers and the driver are replaced
|
||||
// under the lock the frame runs under; on out-of-memory the old strip is kept.
|
||||
esp_err_t patterns_set_hardware(const hw_cfg_t &hw)
|
||||
{
|
||||
int n = clamp_leds(hw.num_leds);
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
if (!frame_alloc(n)) {
|
||||
xSemaphoreGive(s_lock);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
s_fx.n = n;
|
||||
delete s_strip;
|
||||
s_strip = new WS2812((gpio_num_t)hw.pin, n);
|
||||
s_strip->setOrder(hw.order);
|
||||
s_strip->setBrightness(255);
|
||||
s_max_brightness = hw.max_brightness;
|
||||
s_fading = false;
|
||||
s_reset_pending = true;
|
||||
xSemaphoreGive(s_lock);
|
||||
ESP_LOGI(TAG, "LED strip: %d LEDs on GPIO %d, %s, max brightness %u, free heap %u", n, hw.pin, hw.order,
|
||||
(unsigned)hw.max_brightness, (unsigned)esp_get_free_heap_size());
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// ---- DDP ---------------------------------------------------------------------------------------
|
||||
|
||||
void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push)
|
||||
{
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
size_t cap = (size_t)s_fx.n * 3;
|
||||
if (offset < cap) {
|
||||
if (offset + len > cap) {
|
||||
len = cap - offset;
|
||||
}
|
||||
memcpy(s_ddp + offset, data, len);
|
||||
}
|
||||
uint32_t now = now_ms();
|
||||
s_ddp_last_ms = now | 1; // never 0
|
||||
s_ddp_packets++;
|
||||
if (push) {
|
||||
s_ddp_frames++;
|
||||
uint32_t sum = 0;
|
||||
for (size_t i = 0; i < cap; i++) {
|
||||
sum += s_ddp[i];
|
||||
}
|
||||
s_ddp_sum = sum;
|
||||
// Summary on the serial log, at most twice a second, so the test can check what was shown
|
||||
if (now - s_ddp_log_ms >= 500) {
|
||||
s_ddp_log_ms = now;
|
||||
ESP_LOGI(TAG, "DDP frames=%u packets=%u sum=%u led0=%u,%u,%u led_last=%u,%u,%u",
|
||||
(unsigned)s_ddp_frames, (unsigned)s_ddp_packets, (unsigned)s_ddp_sum,
|
||||
s_ddp[0], s_ddp[1], s_ddp[2],
|
||||
s_ddp[cap - 3], s_ddp[cap - 2], s_ddp[cap - 1]);
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
void patterns_ddp_status(bool *active, uint32_t *packets)
|
||||
{
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
*active = s_ddp_last_ms != 0 && now_ms() - s_ddp_last_ms < DDP_TIMEOUT_MS;
|
||||
*packets = s_ddp_packets;
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
void patterns_shown_pixel(int i, uint8_t out[3])
|
||||
{
|
||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||
if (i >= 0 && i < s_fx.n) {
|
||||
out[0] = (uint8_t)s_shown[i].r;
|
||||
out[1] = (uint8_t)s_shown[i].g;
|
||||
out[2] = (uint8_t)s_shown[i].b;
|
||||
}
|
||||
xSemaphoreGive(s_lock);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "esp_err.h"
|
||||
|
||||
#define PATTERN_MAX_COLOURS 8
|
||||
|
||||
// Preset fields follow the MicroPython presets: pattern, colours, background, delay (d), brightness (b),
|
||||
// auto (a), reverse, fade, beat_time (tb) and the pattern-specific numbers n1..n6 (n6 is the style).
|
||||
struct preset_t {
|
||||
char name[32]; // "" for the live settings
|
||||
int pattern; // index into the pattern table
|
||||
int ncol; // 0 uses each pattern's own default colours
|
||||
uint8_t col[PATTERN_MAX_COLOURS][3];
|
||||
uint8_t bg[3]; // background (d off colour)
|
||||
uint32_t delay; // d, ms
|
||||
uint8_t brightness; // b, 0-255
|
||||
bool autorun; // a: keep running; false runs one cycle and holds
|
||||
bool reverse; // run the other way along the strip
|
||||
uint32_t fade; // crossfade in from the previous frame, ms
|
||||
bool beat_time; // tb: durations are quarter beats (500 ms beat here)
|
||||
int n[7]; // n[1]..n[6]
|
||||
};
|
||||
|
||||
/** @brief Start the LED strip and the pattern task, with the strip settings. */
|
||||
void patterns_start(const struct hw_cfg_t &hw);
|
||||
|
||||
/** @brief Apply new strip settings (count, colour order, brightness ceiling) while running. */
|
||||
esp_err_t patterns_set_hardware(const struct hw_cfg_t &hw);
|
||||
|
||||
/** @brief Live update of the preset on the strip. A new pattern restarts; other changes keep its place. */
|
||||
void patterns_set(const preset_t &p);
|
||||
|
||||
/** @brief Select a preset: always restarts the pattern, crossfading from the frame on the strip. */
|
||||
void patterns_select(const preset_t &p);
|
||||
|
||||
/** @brief DDP pixel data for the strip: byte offset into the RGB buffer, data, length. Replaces the pattern. */
|
||||
void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push);
|
||||
|
||||
/** @brief Whether DDP pixels are arriving, and how many packets have come in. */
|
||||
void patterns_ddp_status(bool *active, uint32_t *packets);
|
||||
|
||||
/** @brief The colour last shown on LED i, as RGB. */
|
||||
void patterns_shown_pixel(int i, uint8_t out[3]);
|
||||
|
||||
/** @brief Live brightness for every pattern, 0-255 (applied under the max brightness ceiling). */
|
||||
void patterns_set_global(uint8_t level);
|
||||
uint8_t patterns_get_global(void);
|
||||
|
||||
/** @brief Copy of the preset being shown. */
|
||||
void patterns_get(preset_t *out);
|
||||
|
||||
/** @brief Number of patterns. */
|
||||
int patterns_count(void);
|
||||
|
||||
/** @brief Name of pattern i, e.g. "chase". */
|
||||
const char *patterns_name(int i);
|
||||
|
||||
/** @brief Index for a pattern name, or -1 if unknown. */
|
||||
int patterns_index(const char *name);
|
||||
|
||||
/** @brief Fill a preset with the defaults for a pattern: colours and timing as the MicroPython presets. */
|
||||
void preset_defaults(preset_t *p, int pattern);
|
||||
@@ -0,0 +1,391 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Named presets, stored in NVS as one JSON list (as the MicroPython presets.json), with a startup preset.
|
||||
*/
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#include "cJSON.h"
|
||||
#include "esp_log.h"
|
||||
#include "nvs.h"
|
||||
#include "presets.h"
|
||||
|
||||
static const char *TAG = "presets";
|
||||
static const char *NS = "presets";
|
||||
|
||||
static preset_t s_list[PRESETS_MAX];
|
||||
static size_t s_count;
|
||||
static char s_startup[32];
|
||||
static char s_selected[32];
|
||||
|
||||
static int find(const char *name)
|
||||
{
|
||||
for (size_t i = 0; i < s_count; i++) {
|
||||
if (strcmp(s_list[i].name, name) == 0) {
|
||||
return (int)i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static cJSON *rgb_json(const uint8_t *c)
|
||||
{
|
||||
cJSON *a = cJSON_CreateArray();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
cJSON_AddItemToArray(a, cJSON_CreateNumber(c[i]));
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
static bool read_rgb(const cJSON *a, uint8_t *out)
|
||||
{
|
||||
if (!cJSON_IsArray(a) || cJSON_GetArraySize(a) != 3) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < 3; i++) {
|
||||
cJSON *v = cJSON_GetArrayItem(a, i);
|
||||
if (!cJSON_IsNumber(v)) {
|
||||
return false;
|
||||
}
|
||||
int x = v->valueint;
|
||||
out[i] = (uint8_t)(x < 0 ? 0 : (x > 255 ? 255 : x));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
cJSON *preset_to_json(const preset_t *p)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "name", p->name);
|
||||
cJSON_AddStringToObject(o, "pattern", patterns_name(p->pattern));
|
||||
cJSON *colors = cJSON_AddArrayToObject(o, "colors");
|
||||
for (int i = 0; i < p->ncol; i++) {
|
||||
cJSON_AddItemToArray(colors, rgb_json(p->col[i]));
|
||||
}
|
||||
cJSON_AddItemToObject(o, "background", rgb_json(p->bg));
|
||||
cJSON_AddNumberToObject(o, "delay", p->delay);
|
||||
cJSON_AddNumberToObject(o, "brightness", p->brightness);
|
||||
cJSON_AddBoolToObject(o, "auto", p->autorun);
|
||||
cJSON_AddBoolToObject(o, "reverse", p->reverse);
|
||||
cJSON_AddNumberToObject(o, "fade", p->fade);
|
||||
cJSON_AddBoolToObject(o, "beat_time", p->beat_time);
|
||||
cJSON_AddNumberToObject(o, "n1", p->n[1]);
|
||||
cJSON_AddNumberToObject(o, "n2", p->n[2]);
|
||||
cJSON_AddNumberToObject(o, "n3", p->n[3]);
|
||||
cJSON_AddNumberToObject(o, "n4", p->n[4]);
|
||||
cJSON_AddNumberToObject(o, "mode", p->n[6]); // n6: the pattern's style
|
||||
return o;
|
||||
}
|
||||
|
||||
bool preset_from_json(const cJSON *o, preset_t *p)
|
||||
{
|
||||
if (!cJSON_IsObject(o)) {
|
||||
return false;
|
||||
}
|
||||
cJSON *v = cJSON_GetObjectItem(o, "name");
|
||||
if (cJSON_IsString(v)) {
|
||||
strncpy(p->name, v->valuestring, sizeof(p->name) - 1);
|
||||
p->name[sizeof(p->name) - 1] = '\0';
|
||||
}
|
||||
v = cJSON_GetObjectItem(o, "pattern");
|
||||
if (cJSON_IsString(v)) {
|
||||
int idx = patterns_index(v->valuestring);
|
||||
if (idx < 0) {
|
||||
return false;
|
||||
}
|
||||
p->pattern = idx;
|
||||
}
|
||||
v = cJSON_GetObjectItem(o, "colors");
|
||||
if (cJSON_IsArray(v)) {
|
||||
int n = cJSON_GetArraySize(v);
|
||||
if (n > PATTERN_MAX_COLOURS) n = PATTERN_MAX_COLOURS;
|
||||
p->ncol = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (read_rgb(cJSON_GetArrayItem(v, i), p->col[p->ncol])) {
|
||||
p->ncol++;
|
||||
}
|
||||
}
|
||||
}
|
||||
read_rgb(cJSON_GetObjectItem(o, "background"), p->bg);
|
||||
v = cJSON_GetObjectItem(o, "delay");
|
||||
if (cJSON_IsNumber(v)) p->delay = (uint32_t)(v->valueint < 0 ? 0 : v->valueint);
|
||||
v = cJSON_GetObjectItem(o, "brightness");
|
||||
if (cJSON_IsNumber(v)) p->brightness = (uint8_t)(v->valueint < 0 ? 0 : (v->valueint > 255 ? 255 : v->valueint));
|
||||
v = cJSON_GetObjectItem(o, "auto");
|
||||
if (cJSON_IsBool(v)) p->autorun = cJSON_IsTrue(v);
|
||||
v = cJSON_GetObjectItem(o, "reverse");
|
||||
if (cJSON_IsBool(v)) p->reverse = cJSON_IsTrue(v);
|
||||
v = cJSON_GetObjectItem(o, "fade");
|
||||
if (cJSON_IsNumber(v)) p->fade = (uint32_t)(v->valueint < 0 ? 0 : v->valueint);
|
||||
v = cJSON_GetObjectItem(o, "beat_time");
|
||||
if (cJSON_IsBool(v)) p->beat_time = cJSON_IsTrue(v);
|
||||
static const char *keys[] = { "n1", "n2", "n3", "n4" };
|
||||
for (int i = 0; i < 4; i++) {
|
||||
v = cJSON_GetObjectItem(o, keys[i]);
|
||||
if (cJSON_IsNumber(v)) p->n[i + 1] = v->valueint;
|
||||
}
|
||||
v = cJSON_GetObjectItem(o, "mode");
|
||||
if (cJSON_IsNumber(v)) p->n[6] = v->valueint;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Write the whole list to NVS as one JSON blob
|
||||
static esp_err_t save_list(void)
|
||||
{
|
||||
cJSON *arr = cJSON_CreateArray();
|
||||
for (size_t i = 0; i < s_count; i++) {
|
||||
cJSON_AddItemToArray(arr, preset_to_json(&s_list[i]));
|
||||
}
|
||||
char *s = cJSON_PrintUnformatted(arr);
|
||||
cJSON_Delete(arr);
|
||||
if (!s) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||
if (err == ESP_OK) {
|
||||
err = nvs_set_blob(h, "list", s, strlen(s));
|
||||
if (err == ESP_OK) err = nvs_set_str(h, "startup", s_startup);
|
||||
if (err == ESP_OK) err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
}
|
||||
cJSON_free(s);
|
||||
return err;
|
||||
}
|
||||
|
||||
// The presets a new board starts with (added by presets_add_defaults, and on a board that has none saved)
|
||||
static int build_defaults(preset_t *out, int max)
|
||||
{
|
||||
int n = 0;
|
||||
auto add = [&](const char *name, const char *pattern) -> preset_t * {
|
||||
if (n >= max) {
|
||||
return NULL;
|
||||
}
|
||||
preset_t *p = &out[n++];
|
||||
preset_defaults(p, patterns_index(pattern));
|
||||
strncpy(p->name, name, sizeof(p->name) - 1);
|
||||
p->name[sizeof(p->name) - 1] = '\0';
|
||||
return p;
|
||||
};
|
||||
preset_t *p;
|
||||
if ((p = add("Rainbow", "colour_cycle"))) {
|
||||
p->n[6] = 1; // rainbow wheel
|
||||
p->n[1] = 2;
|
||||
p->delay = 60;
|
||||
p->brightness = 160;
|
||||
}
|
||||
if ((p = add("Chase", "chase"))) {
|
||||
p->ncol = 2;
|
||||
p->col[0][0] = 255; p->col[0][1] = 80; p->col[0][2] = 0;
|
||||
p->col[1][0] = 0; p->col[1][1] = 120; p->col[1][2] = 255;
|
||||
p->n[1] = 4; p->n[2] = 4; p->n[3] = 1; p->n[4] = 1;
|
||||
p->delay = 150;
|
||||
p->brightness = 180;
|
||||
}
|
||||
if ((p = add("Aurora", "aurora"))) {
|
||||
p->n[1] = 3;
|
||||
p->n[2] = 40;
|
||||
p->delay = 40;
|
||||
p->brightness = 150;
|
||||
}
|
||||
if ((p = add("Candle", "candle_glow"))) {
|
||||
p->ncol = 3;
|
||||
p->col[0][0] = 255; p->col[0][1] = 140; p->col[0][2] = 40;
|
||||
p->col[1][0] = 255; p->col[1][1] = 200; p->col[1][2] = 120;
|
||||
p->col[2][0] = 255; p->col[2][1] = 90; p->col[2][2] = 20;
|
||||
p->n[1] = 4; p->n[2] = 3; p->n[3] = 90;
|
||||
p->delay = 120;
|
||||
p->brightness = 200;
|
||||
}
|
||||
if ((p = add("Twinkle", "twinkle"))) {
|
||||
p->ncol = 1;
|
||||
p->col[0][0] = 200; p->col[0][1] = 220; p->col[0][2] = 255;
|
||||
p->bg[2] = 20;
|
||||
p->n[1] = 48; p->n[2] = 128;
|
||||
p->delay = 100;
|
||||
p->brightness = 200;
|
||||
}
|
||||
if ((p = add("Flame", "flame"))) {
|
||||
p->delay = 40;
|
||||
p->brightness = 255;
|
||||
p->n[2] = 2500;
|
||||
}
|
||||
if ((p = add("Sweep", "sweep"))) {
|
||||
p->ncol = 2;
|
||||
p->col[0][0] = 255; p->col[0][1] = 0; p->col[0][2] = 120;
|
||||
p->col[1][0] = 0; p->col[1][1] = 200; p->col[1][2] = 255;
|
||||
p->n[1] = 90; p->n[2] = 200; p->n[3] = 200;
|
||||
p->delay = 2000;
|
||||
p->brightness = 200;
|
||||
}
|
||||
if ((p = add("Off", "off"))) {
|
||||
p->brightness = 255;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// Add the default presets whose names aren't in the list yet. Returns how many were added.
|
||||
int presets_add_defaults(void)
|
||||
{
|
||||
preset_t defs[16];
|
||||
int n = build_defaults(defs, 16);
|
||||
int added = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (find(defs[i].name) < 0 && s_count < PRESETS_MAX) {
|
||||
s_list[s_count++] = defs[i];
|
||||
added++;
|
||||
}
|
||||
}
|
||||
if (added > 0) {
|
||||
save_list();
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
esp_err_t presets_init(void)
|
||||
{
|
||||
s_count = 0;
|
||||
s_startup[0] = '\0';
|
||||
s_selected[0] = '\0';
|
||||
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
|
||||
presets_add_defaults(); // a new board
|
||||
return ESP_OK;
|
||||
}
|
||||
size_t len = 0;
|
||||
bool have_list = nvs_get_blob(h, "list", NULL, &len) == ESP_OK;
|
||||
if (have_list && len > 0) {
|
||||
char *buf = (char *)malloc(len + 1);
|
||||
if (buf && nvs_get_blob(h, "list", buf, &len) == ESP_OK) {
|
||||
buf[len] = '\0';
|
||||
cJSON *arr = cJSON_Parse(buf);
|
||||
cJSON *o;
|
||||
cJSON_ArrayForEach(o, arr) {
|
||||
if (s_count >= PRESETS_MAX) break;
|
||||
preset_t p;
|
||||
preset_defaults(&p, 0);
|
||||
if (preset_from_json(o, &p) && p.name[0]) {
|
||||
s_list[s_count++] = p;
|
||||
}
|
||||
}
|
||||
cJSON_Delete(arr);
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
len = sizeof(s_startup);
|
||||
if (nvs_get_str(h, "startup", s_startup, &len) != ESP_OK) {
|
||||
s_startup[0] = '\0';
|
||||
}
|
||||
nvs_close(h);
|
||||
if (!have_list) {
|
||||
presets_add_defaults(); // nothing saved yet: start with the defaults
|
||||
}
|
||||
ESP_LOGI(TAG, "%u presets loaded", (unsigned)s_count);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
size_t presets_count(void)
|
||||
{
|
||||
return s_count;
|
||||
}
|
||||
|
||||
const preset_t *presets_at(size_t i)
|
||||
{
|
||||
return i < s_count ? &s_list[i] : NULL;
|
||||
}
|
||||
|
||||
esp_err_t presets_save(const preset_t *preset)
|
||||
{
|
||||
int idx = find(preset->name);
|
||||
if (idx < 0) {
|
||||
if (s_count >= PRESETS_MAX) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
idx = (int)s_count++;
|
||||
}
|
||||
s_list[idx] = *preset;
|
||||
return save_list();
|
||||
}
|
||||
|
||||
esp_err_t presets_set_order(const char *const *names, size_t n)
|
||||
{
|
||||
// Static: this is too big for the HTTP server's task stack, and only that task calls it
|
||||
static preset_t fresh[PRESETS_MAX];
|
||||
bool used[PRESETS_MAX] = { false };
|
||||
size_t m = 0;
|
||||
for (size_t k = 0; k < n && m < s_count; k++) {
|
||||
int idx = find(names[k]);
|
||||
if (idx >= 0 && !used[idx]) {
|
||||
used[idx] = true;
|
||||
fresh[m++] = s_list[idx];
|
||||
}
|
||||
}
|
||||
for (size_t i = 0; i < s_count; i++) {
|
||||
if (!used[i]) {
|
||||
fresh[m++] = s_list[i];
|
||||
}
|
||||
}
|
||||
memcpy(s_list, fresh, m * sizeof(preset_t));
|
||||
s_count = m;
|
||||
return save_list();
|
||||
}
|
||||
|
||||
esp_err_t presets_delete(const char *name)
|
||||
{
|
||||
int idx = find(name);
|
||||
if (idx < 0) {
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
for (size_t i = (size_t)idx; i + 1 < s_count; i++) {
|
||||
s_list[i] = s_list[i + 1];
|
||||
}
|
||||
s_count--;
|
||||
if (strcmp(s_startup, name) == 0) {
|
||||
s_startup[0] = '\0';
|
||||
}
|
||||
if (strcmp(s_selected, name) == 0) {
|
||||
s_selected[0] = '\0';
|
||||
}
|
||||
return save_list();
|
||||
}
|
||||
|
||||
esp_err_t presets_select(const char *name)
|
||||
{
|
||||
int idx = find(name);
|
||||
if (idx < 0) {
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
patterns_select(s_list[idx]);
|
||||
strncpy(s_selected, name, sizeof(s_selected) - 1);
|
||||
s_selected[sizeof(s_selected) - 1] = '\0';
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
const char *presets_selected(void)
|
||||
{
|
||||
return s_selected;
|
||||
}
|
||||
|
||||
esp_err_t presets_set_startup(const char *name)
|
||||
{
|
||||
if (name[0] && find(name) < 0) {
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
strncpy(s_startup, name, sizeof(s_startup) - 1);
|
||||
s_startup[sizeof(s_startup) - 1] = '\0';
|
||||
return save_list();
|
||||
}
|
||||
|
||||
const char *presets_startup(void)
|
||||
{
|
||||
return s_startup;
|
||||
}
|
||||
|
||||
void presets_apply_startup(void)
|
||||
{
|
||||
if (s_startup[0] && presets_select(s_startup) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Startup preset: %s", s_startup);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include "cJSON.h"
|
||||
#include "esp_err.h"
|
||||
#include "patterns.h"
|
||||
|
||||
#define PRESETS_MAX 32
|
||||
|
||||
/** @brief Load the saved presets and the startup name from NVS. Call after NVS is initialised. */
|
||||
esp_err_t presets_init(void);
|
||||
|
||||
/** @brief Add the default presets whose names are not in the list yet. Returns how many were added. */
|
||||
int presets_add_defaults(void);
|
||||
|
||||
/** @brief Number of presets. */
|
||||
size_t presets_count(void);
|
||||
|
||||
/** @brief Preset at index i (0 <= i < presets_count()). */
|
||||
const preset_t *presets_at(size_t i);
|
||||
|
||||
/** @brief Create a preset, or update the one with the same name. ESP_ERR_NO_MEM when full. */
|
||||
esp_err_t presets_save(const preset_t *preset);
|
||||
|
||||
/** @brief Put the presets in this order. Names not given keep their place at the end. */
|
||||
esp_err_t presets_set_order(const char *const *names, size_t n);
|
||||
|
||||
/** @brief Delete a preset by name. Clears the startup name if it was that preset. */
|
||||
esp_err_t presets_delete(const char *name);
|
||||
|
||||
/** @brief Select a preset: crossfades in and restarts its pattern. ESP_ERR_NOT_FOUND if no such name. */
|
||||
esp_err_t presets_select(const char *name);
|
||||
|
||||
/** @brief Name of the last preset selected since boot, or "". */
|
||||
const char *presets_selected(void);
|
||||
|
||||
/** @brief Set the preset applied at boot. An empty name clears it. */
|
||||
esp_err_t presets_set_startup(const char *name);
|
||||
|
||||
/** @brief Name of the startup preset, or "". */
|
||||
const char *presets_startup(void);
|
||||
|
||||
/** @brief Apply the startup preset, if one is set and still exists. */
|
||||
void presets_apply_startup(void);
|
||||
|
||||
/** @brief A preset as JSON, with the MicroPython field names. The caller frees it with cJSON_Delete. */
|
||||
cJSON *preset_to_json(const preset_t *p);
|
||||
|
||||
/**
|
||||
* @brief Apply the fields present in JSON onto p; missing fields keep their value.
|
||||
* @return false if a field is malformed (an unknown pattern name, for example).
|
||||
*/
|
||||
bool preset_from_json(const cJSON *o, preset_t *p);
|
||||
@@ -0,0 +1,147 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <cstring>
|
||||
|
||||
#include "nvs.h"
|
||||
#include "settings.h"
|
||||
|
||||
static const char *NS = "led";
|
||||
|
||||
esp_err_t settings_load_wifi(wifi_creds_t *c)
|
||||
{
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
size_t len = sizeof(c->ssid);
|
||||
err = nvs_get_str(h, "sta_ssid", c->ssid, &len);
|
||||
if (err == ESP_OK) {
|
||||
len = sizeof(c->pass);
|
||||
err = nvs_get_str(h, "sta_pass", c->pass, &len);
|
||||
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
||||
c->pass[0] = '\0';
|
||||
err = ESP_OK;
|
||||
}
|
||||
}
|
||||
nvs_close(h);
|
||||
return err;
|
||||
}
|
||||
|
||||
esp_err_t settings_save_wifi(const wifi_creds_t *c)
|
||||
{
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
err = nvs_set_str(h, "sta_ssid", c->ssid);
|
||||
if (err == ESP_OK) err = nvs_set_str(h, "sta_pass", c->pass);
|
||||
if (err == ESP_OK) err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
return err;
|
||||
}
|
||||
|
||||
esp_err_t settings_load_hw(hw_cfg_t *c)
|
||||
{
|
||||
strncpy(c->order, "grb", sizeof(c->order));
|
||||
c->max_brightness = 255;
|
||||
c->num_leds = 119;
|
||||
c->pin = 10;
|
||||
c->global_brightness = 255;
|
||||
nvs_handle_t h;
|
||||
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
|
||||
return ESP_OK;
|
||||
}
|
||||
size_t len = sizeof(c->order);
|
||||
if (nvs_get_str(h, "rgb_order", c->order, &len) != ESP_OK) {
|
||||
strncpy(c->order, "grb", sizeof(c->order));
|
||||
}
|
||||
uint8_t mb;
|
||||
if (nvs_get_u8(h, "max_bright", &mb) == ESP_OK) {
|
||||
c->max_brightness = mb;
|
||||
}
|
||||
int32_t n;
|
||||
if (nvs_get_i32(h, "num_leds", &n) == ESP_OK) {
|
||||
c->num_leds = (int)n;
|
||||
}
|
||||
if (nvs_get_i32(h, "pin", &n) == ESP_OK) {
|
||||
c->pin = (int)n;
|
||||
}
|
||||
if (nvs_get_u8(h, "global_bright", &mb) == ESP_OK) {
|
||||
c->global_brightness = mb;
|
||||
}
|
||||
nvs_close(h);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t settings_save_hw(const hw_cfg_t *c)
|
||||
{
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
err = nvs_set_str(h, "rgb_order", c->order);
|
||||
if (err == ESP_OK) err = nvs_set_u8(h, "max_bright", c->max_brightness);
|
||||
if (err == ESP_OK) err = nvs_set_i32(h, "num_leds", c->num_leds);
|
||||
if (err == ESP_OK) err = nvs_set_i32(h, "pin", c->pin);
|
||||
if (err == ESP_OK) err = nvs_set_u8(h, "global_bright", c->global_brightness);
|
||||
if (err == ESP_OK) err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
return err;
|
||||
}
|
||||
|
||||
// Read a string key; use def when it is missing or unreadable
|
||||
static void get_str(nvs_handle_t h, const char *key, char *buf, size_t len, const char *def)
|
||||
{
|
||||
size_t n = len;
|
||||
if (nvs_get_str(h, key, buf, &n) != ESP_OK) {
|
||||
strncpy(buf, def, len - 1);
|
||||
buf[len - 1] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t settings_load_net(net_cfg_t *c)
|
||||
{
|
||||
memset(c, 0, sizeof(*c));
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
|
||||
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
||||
// Nothing saved yet: defaults
|
||||
strncpy(c->hostname, "led", sizeof(c->hostname) - 1);
|
||||
return ESP_OK;
|
||||
}
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
get_str(h, "hostname", c->hostname, sizeof(c->hostname), "led");
|
||||
char mode[8];
|
||||
get_str(h, "ip_mode", mode, sizeof(mode), "dhcp");
|
||||
c->use_static = strcmp(mode, "static") == 0;
|
||||
get_str(h, "ip", c->ip, sizeof(c->ip), "");
|
||||
get_str(h, "netmask", c->netmask, sizeof(c->netmask), "");
|
||||
get_str(h, "gateway", c->gateway, sizeof(c->gateway), "");
|
||||
get_str(h, "dns", c->dns, sizeof(c->dns), "");
|
||||
nvs_close(h);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t settings_save_net(const net_cfg_t *c)
|
||||
{
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
err = nvs_set_str(h, "hostname", c->hostname);
|
||||
if (err == ESP_OK) err = nvs_set_str(h, "ip_mode", c->use_static ? "static" : "dhcp");
|
||||
if (err == ESP_OK) err = nvs_set_str(h, "ip", c->ip);
|
||||
if (err == ESP_OK) err = nvs_set_str(h, "netmask", c->netmask);
|
||||
if (err == ESP_OK) err = nvs_set_str(h, "gateway", c->gateway);
|
||||
if (err == ESP_OK) err = nvs_set_str(h, "dns", c->dns);
|
||||
if (err == ESP_OK) err = nvs_commit(h);
|
||||
nvs_close(h);
|
||||
return err;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#include "esp_err.h"
|
||||
|
||||
struct wifi_creds_t {
|
||||
char ssid[33];
|
||||
char pass[65];
|
||||
};
|
||||
|
||||
struct net_cfg_t {
|
||||
char hostname[64]; // mDNS name, without ".local"
|
||||
bool use_static; // false: DHCP on the client interface
|
||||
char ip[16]; // static client address, dotted quad
|
||||
char netmask[16];
|
||||
char gateway[16];
|
||||
char dns[16]; // optional; empty uses the gateway
|
||||
};
|
||||
|
||||
/** @brief Read saved Wi-Fi client credentials. ESP_ERR_NVS_NOT_FOUND if none are saved. */
|
||||
esp_err_t settings_load_wifi(wifi_creds_t *c);
|
||||
|
||||
/** @brief Save Wi-Fi client credentials to NVS. */
|
||||
esp_err_t settings_save_wifi(const wifi_creds_t *c);
|
||||
|
||||
struct hw_cfg_t {
|
||||
char order[4]; // colour order of the strip: rgb, rbg, grb, gbr, brg or bgr
|
||||
uint8_t max_brightness; // ceiling for every output colour, 0-255
|
||||
int num_leds; // 1-512
|
||||
int pin; // GPIO for the data line
|
||||
uint8_t global_brightness; // live brightness for all patterns, 0-255 (under max_brightness)
|
||||
};
|
||||
|
||||
/** @brief Read the LED strip settings. Missing keys get their defaults (grb, 255, 119). */
|
||||
esp_err_t settings_load_hw(hw_cfg_t *c);
|
||||
|
||||
/** @brief Save the LED strip settings. */
|
||||
esp_err_t settings_save_hw(const hw_cfg_t *c);
|
||||
|
||||
/** @brief Read network settings. Missing keys get their defaults (hostname "led", DHCP). */
|
||||
esp_err_t settings_load_net(net_cfg_t *c);
|
||||
|
||||
/** @brief Save network settings to NVS. */
|
||||
esp_err_t settings_save_net(const net_cfg_t *c);
|
||||
+915
@@ -0,0 +1,915 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#include "cJSON.h"
|
||||
#include "esp_http_client.h"
|
||||
#include "mdns.h"
|
||||
#include "esp_http_server.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "net.h"
|
||||
#include "ota.h"
|
||||
#include "ddp.h"
|
||||
#include "patterns.h"
|
||||
#include "effects.h"
|
||||
#include "presets.h"
|
||||
#include "settings.h"
|
||||
#include "web.h"
|
||||
|
||||
static const char *TAG = "web";
|
||||
|
||||
// Files embedded from web/ (see main/CMakeLists.txt EMBED_TXTFILES)
|
||||
extern const char index_html_start[] asm("_binary_index_html_start");
|
||||
extern const char index_html_end[] asm("_binary_index_html_end");
|
||||
extern const char app_js_start[] asm("_binary_app_js_start");
|
||||
extern const char app_js_end[] asm("_binary_app_js_end");
|
||||
extern const char style_css_start[] asm("_binary_style_css_start");
|
||||
extern const char style_css_end[] asm("_binary_style_css_end");
|
||||
|
||||
static httpd_handle_t s_server;
|
||||
|
||||
#define MAX_BODY 1024
|
||||
#define MAX_SCAN 20
|
||||
|
||||
static esp_err_t send_embedded(httpd_req_t *req, const char *type, const char *start, const char *end)
|
||||
{
|
||||
httpd_resp_set_type(req, type);
|
||||
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
|
||||
// EMBED_TXTFILES includes the file's terminating NUL; don't send it
|
||||
size_t len = end - start;
|
||||
if (len > 0 && start[len - 1] == '\0') {
|
||||
len--;
|
||||
}
|
||||
return httpd_resp_send(req, start, len);
|
||||
}
|
||||
|
||||
// True for http://<private IPv4>, http://<name>.local and localhost, with an optional port.
|
||||
// Pages on the internet are refused, so only the LAN and this computer can read the API cross-origin.
|
||||
static bool origin_is_lan(const char *o)
|
||||
{
|
||||
static const char prefix[] = "http://";
|
||||
if (strncmp(o, prefix, sizeof(prefix) - 1) != 0) {
|
||||
return false;
|
||||
}
|
||||
char host[64];
|
||||
const char *p = o + sizeof(prefix) - 1;
|
||||
size_t n = 0;
|
||||
while (p[n] && p[n] != ':') {
|
||||
if (n + 1 >= sizeof(host)) {
|
||||
return false;
|
||||
}
|
||||
host[n] = p[n];
|
||||
n++;
|
||||
}
|
||||
host[n] = '\0';
|
||||
if (p[n] == ':') { // port: digits only
|
||||
for (const char *q = p + n + 1; *q; q++) {
|
||||
if (*q < '0' || *q > '9') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (n == 0) {
|
||||
return false;
|
||||
}
|
||||
if (strcmp(host, "localhost") == 0) {
|
||||
return true;
|
||||
}
|
||||
size_t len = strlen(host);
|
||||
if (len > 6 && strcmp(host + len - 6, ".local") == 0) {
|
||||
for (size_t i = 0; i < len - 6; i++) {
|
||||
char c = host[i];
|
||||
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '.';
|
||||
if (!ok) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
unsigned a, b, c, d;
|
||||
char extra;
|
||||
if (sscanf(host, "%u.%u.%u.%u%c", &a, &b, &c, &d, &extra) != 4) {
|
||||
return false;
|
||||
}
|
||||
for (const char *q = host; *q; q++) {
|
||||
if (!((*q >= '0' && *q <= '9') || *q == '.')) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (a > 255 || b > 255 || c > 255 || d > 255) {
|
||||
return false;
|
||||
}
|
||||
return a == 10 || (a == 192 && b == 168) || (a == 172 && b >= 16 && b <= 31);
|
||||
}
|
||||
|
||||
void web_allow_lan_origin(httpd_req_t *req)
|
||||
{
|
||||
// The httpd server runs one handler at a time, and the header keeps a pointer to this buffer
|
||||
// until the reply is sent, so a static buffer is safe here.
|
||||
static char origin[96];
|
||||
if (httpd_req_get_hdr_value_str(req, "Origin", origin, sizeof(origin)) != ESP_OK) {
|
||||
return;
|
||||
}
|
||||
if (!origin_is_lan(origin)) {
|
||||
return;
|
||||
}
|
||||
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", origin);
|
||||
httpd_resp_set_hdr(req, "Vary", "Origin");
|
||||
}
|
||||
|
||||
static esp_err_t send_json(httpd_req_t *req, cJSON *obj)
|
||||
{
|
||||
char *s = cJSON_PrintUnformatted(obj);
|
||||
cJSON_Delete(obj);
|
||||
web_allow_lan_origin(req);
|
||||
if (!s) {
|
||||
return httpd_resp_send_500(req);
|
||||
}
|
||||
httpd_resp_set_type(req, "application/json");
|
||||
esp_err_t err = httpd_resp_sendstr(req, s);
|
||||
cJSON_free(s);
|
||||
return err;
|
||||
}
|
||||
|
||||
static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg)
|
||||
{
|
||||
httpd_resp_set_status(req, status);
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "error", msg);
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// Read the request body into buf (NUL-terminated). False if missing, too big or unreadable.
|
||||
static bool read_body(httpd_req_t *req, char *buf, size_t cap)
|
||||
{
|
||||
int len = req->content_len;
|
||||
if (len <= 0 || (size_t)len >= cap) {
|
||||
return false;
|
||||
}
|
||||
int got = 0;
|
||||
while (got < len) {
|
||||
int r = httpd_req_recv(req, buf + got, len - got);
|
||||
if (r <= 0) {
|
||||
return false;
|
||||
}
|
||||
got += r;
|
||||
}
|
||||
buf[got] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
// Read a JSON body; NULL (no reply sent) if missing, too big or not JSON. Caller frees with cJSON_Delete.
|
||||
static cJSON *read_json(httpd_req_t *req)
|
||||
{
|
||||
char body[MAX_BODY];
|
||||
if (!read_body(req, body, sizeof(body))) {
|
||||
return NULL;
|
||||
}
|
||||
return cJSON_Parse(body);
|
||||
}
|
||||
|
||||
// GET / , /app.js , /style.css
|
||||
static esp_err_t index_get(httpd_req_t *req)
|
||||
{
|
||||
return send_embedded(req, "text/html", index_html_start, index_html_end);
|
||||
}
|
||||
|
||||
static esp_err_t app_js_get(httpd_req_t *req)
|
||||
{
|
||||
return send_embedded(req, "application/javascript", app_js_start, app_js_end);
|
||||
}
|
||||
|
||||
static esp_err_t style_css_get(httpd_req_t *req)
|
||||
{
|
||||
return send_embedded(req, "text/css", style_css_start, style_css_end);
|
||||
}
|
||||
|
||||
// GET /api/status : the running preset (same fields as a preset), plus device and network state
|
||||
static esp_err_t status_get(httpd_req_t *req)
|
||||
{
|
||||
preset_t p;
|
||||
patterns_get(&p);
|
||||
char ap[16], ip[16];
|
||||
net_ap_ssid(ap, sizeof(ap));
|
||||
bool up = net_sta_status(ip, sizeof(ip));
|
||||
|
||||
net_cfg_t n;
|
||||
settings_load_net(&n);
|
||||
cJSON *o = preset_to_json(&p);
|
||||
cJSON_AddStringToObject(o, "ap_ssid", ap);
|
||||
cJSON_AddStringToObject(o, "hostname", n.hostname);
|
||||
cJSON_AddBoolToObject(o, "sta_connected", up);
|
||||
cJSON_AddStringToObject(o, "sta_ip", ip);
|
||||
cJSON_AddStringToObject(o, "selected", presets_selected());
|
||||
cJSON_AddNumberToObject(o, "global_brightness", patterns_get_global());
|
||||
cJSON *modes = cJSON_AddArrayToObject(o, "patterns");
|
||||
for (int i = 0; i < patterns_count(); i++) {
|
||||
cJSON_AddItemToArray(modes, cJSON_CreateString(patterns_name(i)));
|
||||
}
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// POST /api/pattern : change the running settings. Fields missing from the body keep their value.
|
||||
static esp_err_t pattern_post(httpd_req_t *req)
|
||||
{
|
||||
cJSON *in = read_json(req);
|
||||
if (!in) {
|
||||
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||
}
|
||||
preset_t p;
|
||||
patterns_get(&p);
|
||||
bool ok = preset_from_json(in, &p);
|
||||
cJSON_Delete(in);
|
||||
if (!ok) {
|
||||
return send_error(req, "400 Bad Request", "unknown pattern");
|
||||
}
|
||||
patterns_set(p);
|
||||
return send_json(req, cJSON_CreateObject());
|
||||
}
|
||||
|
||||
// GET /api/wifi : saved client SSID and connection state
|
||||
static esp_err_t wifi_get(httpd_req_t *req)
|
||||
{
|
||||
wifi_creds_t c = {};
|
||||
settings_load_wifi(&c);
|
||||
char ip[16];
|
||||
bool up = net_sta_status(ip, sizeof(ip));
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "ssid", c.ssid);
|
||||
cJSON_AddBoolToObject(o, "connected", up);
|
||||
cJSON_AddStringToObject(o, "ip", ip);
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// POST /api/wifi {"ssid","password"} : save and connect
|
||||
static esp_err_t wifi_post(httpd_req_t *req)
|
||||
{
|
||||
char body[MAX_BODY];
|
||||
if (!read_body(req, body, sizeof(body))) {
|
||||
return send_error(req, "400 Bad Request", "empty or too large body");
|
||||
}
|
||||
cJSON *in = cJSON_Parse(body);
|
||||
if (!in) {
|
||||
return send_error(req, "400 Bad Request", "invalid JSON");
|
||||
}
|
||||
cJSON *ssid = cJSON_GetObjectItem(in, "ssid");
|
||||
cJSON *pass = cJSON_GetObjectItem(in, "password");
|
||||
const char *pw = cJSON_IsString(pass) ? pass->valuestring : "";
|
||||
if (!cJSON_IsString(ssid) || !ssid->valuestring[0] || strlen(ssid->valuestring) > 32) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "SSID must be 1-32 characters");
|
||||
}
|
||||
size_t plen = strlen(pw);
|
||||
if (plen > 0 && (plen < 8 || plen > 64)) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "password must be empty or 8-64 characters");
|
||||
}
|
||||
wifi_creds_t c = {};
|
||||
strncpy(c.ssid, ssid->valuestring, sizeof(c.ssid) - 1);
|
||||
strncpy(c.pass, pw, sizeof(c.pass) - 1);
|
||||
cJSON_Delete(in);
|
||||
|
||||
esp_err_t err = net_sta_connect(&c);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "Connect to %s failed: %s", c.ssid, esp_err_to_name(err));
|
||||
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "saved; connecting");
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// GET /api/wifi/scan : visible networks
|
||||
static esp_err_t wifi_scan_get(httpd_req_t *req)
|
||||
{
|
||||
static wifi_ap_record_t recs[MAX_SCAN];
|
||||
uint16_t count = MAX_SCAN;
|
||||
esp_err_t err = net_scan(recs, &count);
|
||||
if (err != ESP_OK) {
|
||||
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
||||
}
|
||||
cJSON *arr = cJSON_CreateArray();
|
||||
for (int i = 0; i < count; i++) {
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "ssid", (const char *)recs[i].ssid);
|
||||
cJSON_AddNumberToObject(o, "rssi", recs[i].rssi);
|
||||
cJSON_AddBoolToObject(o, "open", recs[i].authmode == WIFI_AUTH_OPEN);
|
||||
cJSON_AddItemToArray(arr, o);
|
||||
}
|
||||
cJSON *root = cJSON_CreateObject();
|
||||
cJSON_AddItemToObject(root, "networks", arr);
|
||||
return send_json(req, root);
|
||||
}
|
||||
|
||||
// A DNS label: 1-63 letters, digits or hyphens, not starting or ending with a hyphen
|
||||
static bool valid_hostname(const char *s)
|
||||
{
|
||||
size_t n = strlen(s);
|
||||
if (n == 0 || n > 63 || s[0] == '-' || s[n - 1] == '-') {
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
char c = s[i];
|
||||
bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
|
||||
if (!ok) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool valid_ipv4(const char *s)
|
||||
{
|
||||
esp_ip4_addr_t a;
|
||||
return s && s[0] && esp_netif_str_to_ip4(s, &a) == ESP_OK;
|
||||
}
|
||||
|
||||
// GET /api/network : mDNS name and client address settings, with the current address
|
||||
static esp_err_t network_get(httpd_req_t *req)
|
||||
{
|
||||
net_cfg_t n;
|
||||
settings_load_net(&n);
|
||||
char ip[16];
|
||||
bool up = net_sta_status(ip, sizeof(ip));
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "hostname", n.hostname);
|
||||
cJSON_AddStringToObject(o, "mode", n.use_static ? "static" : "dhcp");
|
||||
cJSON_AddStringToObject(o, "ip", n.ip);
|
||||
cJSON_AddStringToObject(o, "netmask", n.netmask);
|
||||
cJSON_AddStringToObject(o, "gateway", n.gateway);
|
||||
cJSON_AddStringToObject(o, "dns", n.dns);
|
||||
cJSON_AddBoolToObject(o, "connected", up);
|
||||
cJSON_AddStringToObject(o, "current_ip", ip);
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// POST /api/network {"hostname","mode":"dhcp"|"static","ip","netmask","gateway","dns"}
|
||||
// Missing fields keep their current value. Saves, applies and reconnects the client.
|
||||
static esp_err_t network_post(httpd_req_t *req)
|
||||
{
|
||||
cJSON *in = read_json(req);
|
||||
if (!in) {
|
||||
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||
}
|
||||
net_cfg_t n;
|
||||
settings_load_net(&n);
|
||||
|
||||
cJSON *h = cJSON_GetObjectItem(in, "hostname");
|
||||
if (cJSON_IsString(h)) {
|
||||
char name[64];
|
||||
strncpy(name, h->valuestring, sizeof(name) - 1);
|
||||
name[sizeof(name) - 1] = '\0';
|
||||
for (char *p = name; *p; p++) {
|
||||
if (*p >= 'A' && *p <= 'Z') *p = *p - 'A' + 'a';
|
||||
}
|
||||
if (!valid_hostname(name)) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "hostname: 1-63 letters, digits or hyphens");
|
||||
}
|
||||
strncpy(n.hostname, name, sizeof(n.hostname) - 1);
|
||||
}
|
||||
|
||||
cJSON *mode = cJSON_GetObjectItem(in, "mode");
|
||||
if (cJSON_IsString(mode)) {
|
||||
if (strcmp(mode->valuestring, "static") == 0) {
|
||||
n.use_static = true;
|
||||
} else if (strcmp(mode->valuestring, "dhcp") == 0) {
|
||||
n.use_static = false;
|
||||
} else {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "mode must be dhcp or static");
|
||||
}
|
||||
}
|
||||
|
||||
struct { const char *key; char *dst; size_t len; } fields[] = {
|
||||
{ "ip", n.ip, sizeof(n.ip) },
|
||||
{ "netmask", n.netmask, sizeof(n.netmask) },
|
||||
{ "gateway", n.gateway, sizeof(n.gateway) },
|
||||
{ "dns", n.dns, sizeof(n.dns) },
|
||||
};
|
||||
for (auto &f : fields) {
|
||||
cJSON *v = cJSON_GetObjectItem(in, f.key);
|
||||
if (cJSON_IsString(v)) {
|
||||
strncpy(f.dst, v->valuestring, f.len - 1);
|
||||
f.dst[f.len - 1] = '\0';
|
||||
}
|
||||
}
|
||||
cJSON_Delete(in);
|
||||
|
||||
if (n.use_static) {
|
||||
if (!valid_ipv4(n.ip) || !valid_ipv4(n.netmask) || !valid_ipv4(n.gateway)) {
|
||||
return send_error(req, "400 Bad Request", "static mode needs ip, netmask and gateway as IPv4 addresses");
|
||||
}
|
||||
if (n.dns[0] && !valid_ipv4(n.dns)) {
|
||||
return send_error(req, "400 Bad Request", "dns must be an IPv4 address or empty");
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t err = net_save_network(&n);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "Network apply failed: %s", esp_err_to_name(err));
|
||||
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
||||
}
|
||||
// With a static address the page's current address changes, so say where to go next
|
||||
char addr[80];
|
||||
if (n.use_static) {
|
||||
snprintf(addr, sizeof(addr), "%s", n.ip);
|
||||
} else {
|
||||
snprintf(addr, sizeof(addr), "%s.local", n.hostname);
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "saved; reconnecting");
|
||||
cJSON_AddStringToObject(o, "address", addr);
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// ---- presets -----------------------------------------------------------------------------------
|
||||
|
||||
// ---- LED strip hardware ------------------------------------------------------------------------
|
||||
|
||||
static bool valid_order(const char *s)
|
||||
{
|
||||
if (strlen(s) != 3) return false;
|
||||
bool seen[3] = { false, false, false };
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int k = s[i] == 'r' ? 0 : (s[i] == 'g' ? 1 : (s[i] == 'b' ? 2 : -1));
|
||||
if (k < 0 || seen[k]) return false;
|
||||
seen[k] = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// GPIOs that can drive the strip on the ESP32-C3: not the flash (11-17) or the USB (18, 19)
|
||||
static bool valid_pin(int pin)
|
||||
{
|
||||
return (pin >= 0 && pin <= 10) || pin == 20 || pin == 21;
|
||||
}
|
||||
|
||||
// GET /api/hardware : LED strip settings
|
||||
static esp_err_t hardware_get(httpd_req_t *req)
|
||||
{
|
||||
hw_cfg_t hw;
|
||||
settings_load_hw(&hw);
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "rgb_order", hw.order);
|
||||
cJSON_AddNumberToObject(o, "max_brightness", hw.max_brightness);
|
||||
cJSON_AddNumberToObject(o, "num_leds", hw.num_leds);
|
||||
cJSON_AddNumberToObject(o, "pin", hw.pin);
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// POST /api/hardware {"rgb_order","max_brightness":0-255,"num_leds":1-512}. Missing fields keep their value.
|
||||
static esp_err_t hardware_post(httpd_req_t *req)
|
||||
{
|
||||
cJSON *in = read_json(req);
|
||||
if (!in) {
|
||||
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||
}
|
||||
hw_cfg_t hw;
|
||||
settings_load_hw(&hw);
|
||||
cJSON *v = cJSON_GetObjectItem(in, "rgb_order");
|
||||
if (cJSON_IsString(v)) {
|
||||
char order[4];
|
||||
for (int i = 0; i < 3; i++) order[i] = (char)(v->valuestring[i] >= 'A' && v->valuestring[i] <= 'Z' ? v->valuestring[i] + 32 : v->valuestring[i]);
|
||||
order[3] = '\0';
|
||||
if (!valid_order(order)) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "rgb_order must be rgb, rbg, grb, gbr, brg or bgr");
|
||||
}
|
||||
strncpy(hw.order, order, sizeof(hw.order));
|
||||
}
|
||||
v = cJSON_GetObjectItem(in, "max_brightness");
|
||||
if (cJSON_IsNumber(v)) {
|
||||
if (v->valueint < 0 || v->valueint > 255) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "max_brightness must be 0-255");
|
||||
}
|
||||
hw.max_brightness = (uint8_t)v->valueint;
|
||||
}
|
||||
v = cJSON_GetObjectItem(in, "num_leds");
|
||||
if (cJSON_IsNumber(v)) {
|
||||
if (v->valueint < 1 || v->valueint > FX_LEDS_MAX) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "num_leds must be 1-512");
|
||||
}
|
||||
hw.num_leds = v->valueint;
|
||||
}
|
||||
v = cJSON_GetObjectItem(in, "pin");
|
||||
if (cJSON_IsNumber(v)) {
|
||||
if (!valid_pin(v->valueint)) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "pin must be 0-10 or 20-21 (not 11-19, which the flash and USB use)");
|
||||
}
|
||||
hw.pin = v->valueint;
|
||||
}
|
||||
cJSON_Delete(in);
|
||||
|
||||
esp_err_t err = patterns_set_hardware(hw);
|
||||
if (err != ESP_OK) {
|
||||
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
||||
}
|
||||
err = settings_save_hw(&hw);
|
||||
if (err != ESP_OK) {
|
||||
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "saved");
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// GET /api/ddp[?led=N] : DDP receiver state, and the colour shown on LED N (for checks)
|
||||
static esp_err_t ddp_get(httpd_req_t *req)
|
||||
{
|
||||
bool active;
|
||||
uint32_t packets;
|
||||
patterns_ddp_status(&active, &packets);
|
||||
int led = 0;
|
||||
char q[32];
|
||||
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK) {
|
||||
char v[8];
|
||||
if (httpd_query_key_value(q, "led", v, sizeof(v)) == ESP_OK) {
|
||||
led = atoi(v);
|
||||
}
|
||||
}
|
||||
uint8_t px[3];
|
||||
patterns_shown_pixel(led, px);
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddBoolToObject(o, "active", active);
|
||||
cJSON_AddNumberToObject(o, "packets", packets);
|
||||
cJSON_AddNumberToObject(o, "port", DDP_PORT);
|
||||
cJSON_AddNumberToObject(o, "led", led);
|
||||
cJSON *px_arr = cJSON_AddArrayToObject(o, "rgb");
|
||||
for (int i = 0; i < 3; i++) {
|
||||
cJSON_AddItemToArray(px_arr, cJSON_CreateNumber(px[i]));
|
||||
}
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// POST /api/presets/order {"names":[...]} : the presets' order on the front page
|
||||
static esp_err_t presets_order_post(httpd_req_t *req)
|
||||
{
|
||||
cJSON *in = read_json(req);
|
||||
if (!in) {
|
||||
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||
}
|
||||
cJSON *arr = cJSON_GetObjectItem(in, "names");
|
||||
if (!cJSON_IsArray(arr)) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "names must be a list");
|
||||
}
|
||||
const char *names[PRESETS_MAX];
|
||||
size_t n = 0;
|
||||
cJSON *item;
|
||||
cJSON_ArrayForEach(item, arr) {
|
||||
if (n < PRESETS_MAX && cJSON_IsString(item)) {
|
||||
names[n++] = item->valuestring;
|
||||
}
|
||||
}
|
||||
presets_set_order(names, n);
|
||||
cJSON_Delete(in);
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "saved");
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// POST /api/presets/defaults : add the default presets that are missing
|
||||
static esp_err_t presets_defaults_post(httpd_req_t *req)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddNumberToObject(o, "added", presets_add_defaults());
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// GET /api/presets
|
||||
static esp_err_t presets_get(httpd_req_t *req)
|
||||
{
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON *arr = cJSON_AddArrayToObject(o, "presets");
|
||||
for (size_t i = 0; i < presets_count(); i++) {
|
||||
cJSON_AddItemToArray(arr, preset_to_json(presets_at(i)));
|
||||
}
|
||||
cJSON_AddStringToObject(o, "selected", presets_selected());
|
||||
cJSON_AddStringToObject(o, "startup", presets_startup());
|
||||
cJSON_AddNumberToObject(o, "max", PRESETS_MAX);
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// POST /api/brightness {"brightness":0-255} : live brightness for every pattern, saved
|
||||
static esp_err_t brightness_post(httpd_req_t *req)
|
||||
{
|
||||
cJSON *in = read_json(req);
|
||||
if (!in) {
|
||||
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||
}
|
||||
cJSON *v = cJSON_GetObjectItem(in, "brightness");
|
||||
if (!cJSON_IsNumber(v) || v->valueint < 0 || v->valueint > 255) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "brightness must be 0-255");
|
||||
}
|
||||
uint8_t level = (uint8_t)v->valueint;
|
||||
cJSON_Delete(in);
|
||||
patterns_set_global(level);
|
||||
hw_cfg_t hw;
|
||||
settings_load_hw(&hw);
|
||||
hw.global_brightness = level;
|
||||
settings_save_hw(&hw);
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "saved");
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// POST /api/presets : create or update by name. Missing fields take the running settings.
|
||||
static esp_err_t presets_post(httpd_req_t *req)
|
||||
{
|
||||
cJSON *in = read_json(req);
|
||||
if (!in) {
|
||||
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||
}
|
||||
cJSON *name = cJSON_GetObjectItem(in, "name");
|
||||
if (!cJSON_IsString(name) || !name->valuestring[0] || strlen(name->valuestring) >= 32) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "name must be 1-31 characters");
|
||||
}
|
||||
preset_t pr;
|
||||
patterns_get(&pr);
|
||||
bool ok = preset_from_json(in, &pr);
|
||||
cJSON_Delete(in);
|
||||
if (!ok) {
|
||||
return send_error(req, "400 Bad Request", "unknown pattern");
|
||||
}
|
||||
|
||||
esp_err_t err = presets_save(&pr);
|
||||
if (err == ESP_ERR_NO_MEM) {
|
||||
return send_error(req, "400 Bad Request", "preset list is full");
|
||||
}
|
||||
if (err != ESP_OK) {
|
||||
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", "saved");
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
// Shared body for select, delete and startup: {"name"}
|
||||
static esp_err_t preset_name_action(httpd_req_t *req, esp_err_t (*action)(const char *), const char *ok_msg)
|
||||
{
|
||||
cJSON *in = read_json(req);
|
||||
if (!in) {
|
||||
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||
}
|
||||
cJSON *name = cJSON_GetObjectItem(in, "name");
|
||||
if (!cJSON_IsString(name)) {
|
||||
cJSON_Delete(in);
|
||||
return send_error(req, "400 Bad Request", "name is required");
|
||||
}
|
||||
char buf[32];
|
||||
strncpy(buf, name->valuestring, sizeof(buf) - 1);
|
||||
buf[sizeof(buf) - 1] = '\0';
|
||||
cJSON_Delete(in);
|
||||
|
||||
esp_err_t err = action(buf);
|
||||
if (err == ESP_ERR_NOT_FOUND) {
|
||||
return send_error(req, "404 Not Found", "no such preset");
|
||||
}
|
||||
if (err != ESP_OK) {
|
||||
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
||||
}
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "message", ok_msg);
|
||||
return send_json(req, o);
|
||||
}
|
||||
|
||||
static esp_err_t select_post(httpd_req_t *req)
|
||||
{
|
||||
return preset_name_action(req, presets_select, "selected");
|
||||
}
|
||||
|
||||
static esp_err_t delete_post(httpd_req_t *req)
|
||||
{
|
||||
return preset_name_action(req, presets_delete, "deleted");
|
||||
}
|
||||
|
||||
static esp_err_t startup_post(httpd_req_t *req)
|
||||
{
|
||||
return preset_name_action(req, presets_set_startup, "startup set");
|
||||
}
|
||||
|
||||
static void add_uri(httpd_handle_t srv, const char *uri, httpd_method_t method, esp_err_t (*handler)(httpd_req_t *))
|
||||
{
|
||||
httpd_uri_t u = { .uri = uri, .method = method, .handler = handler, .user_ctx = NULL };
|
||||
httpd_register_uri_handler(srv, &u);
|
||||
}
|
||||
|
||||
// Host part of a relay target: letters, digits, dots, dashes and an optional :port.
|
||||
static bool relay_host_ok(const char *h)
|
||||
{
|
||||
size_t n = strlen(h);
|
||||
if (n == 0 || n > 80) {
|
||||
return false;
|
||||
}
|
||||
for (const char *p = h; *p; p++) {
|
||||
char c = *p;
|
||||
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == ':';
|
||||
if (!ok) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Only this driver's own API and its firmware info and reboot, so the relay cannot reach other services.
|
||||
static bool relay_path_ok(const char *p)
|
||||
{
|
||||
if (strcmp(p, "/ota") == 0 || strcmp(p, "/reboot") == 0) {
|
||||
return true;
|
||||
}
|
||||
if (strncmp(p, "/api/", 5) != 0 || strcmp(p, "/api/relay") == 0 || strlen(p) > 120) {
|
||||
return false;
|
||||
}
|
||||
return strstr(p, "..") == NULL && strchr(p, ' ') == NULL && strchr(p, '\r') == NULL && strchr(p, '\n') == NULL;
|
||||
}
|
||||
|
||||
// POST /api/relay {"host": "10.1.1.50", "method": "GET" or "POST", "path": "/api/status", "body": "..."}
|
||||
// Calls another driver from here and answers {"status": n, "body": "..."}. A page on this driver only
|
||||
// talks to this driver, so the browser never has to reach the other device itself.
|
||||
static esp_err_t relay_post(httpd_req_t *req)
|
||||
{
|
||||
// Heap buffers: the HTTP server task has an 8 KB stack
|
||||
char *in = (char *)malloc(2048);
|
||||
char *out = (char *)malloc(4096);
|
||||
if (!in || !out) {
|
||||
free(in);
|
||||
free(out);
|
||||
return send_error(req, "503 Service Unavailable", "out of memory");
|
||||
}
|
||||
esp_err_t result = ESP_FAIL;
|
||||
if (!read_body(req, in, 2048)) {
|
||||
result = send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||
goto done;
|
||||
} else {
|
||||
cJSON *top = cJSON_Parse(in);
|
||||
const cJSON *jh = top ? cJSON_GetObjectItem(top, "host") : NULL;
|
||||
const cJSON *jm = top ? cJSON_GetObjectItem(top, "method") : NULL;
|
||||
const cJSON *jp = top ? cJSON_GetObjectItem(top, "path") : NULL;
|
||||
const cJSON *jb = top ? cJSON_GetObjectItem(top, "body") : NULL;
|
||||
if (!cJSON_IsString(jh) || !cJSON_IsString(jm) || !cJSON_IsString(jp) || !relay_host_ok(jh->valuestring)
|
||||
|| !relay_path_ok(jp->valuestring) || (strcmp(jm->valuestring, "GET") != 0 && strcmp(jm->valuestring, "POST") != 0)) {
|
||||
cJSON_Delete(top);
|
||||
result = send_error(req, "400 Bad Request", "need host, method GET or POST, and a path under /api/");
|
||||
goto done;
|
||||
}
|
||||
const bool is_post = strcmp(jm->valuestring, "POST") == 0;
|
||||
const char *body = (is_post && cJSON_IsString(jb)) ? jb->valuestring : "";
|
||||
const int body_len = (int)strlen(body);
|
||||
char url[200];
|
||||
snprintf(url, sizeof(url), "http://%s%s", jh->valuestring, jp->valuestring);
|
||||
esp_http_client_config_t ccfg = {};
|
||||
ccfg.url = url;
|
||||
ccfg.method = is_post ? HTTP_METHOD_POST : HTTP_METHOD_GET;
|
||||
ccfg.timeout_ms = 4000;
|
||||
esp_http_client_handle_t cl = esp_http_client_init(&ccfg);
|
||||
if (!cl) {
|
||||
cJSON_Delete(top);
|
||||
result = send_error(req, "502 Bad Gateway", "could not start the request");
|
||||
goto done;
|
||||
}
|
||||
esp_http_client_set_header(cl, "Content-Type", "text/plain");
|
||||
esp_err_t err = esp_http_client_open(cl, is_post ? body_len : 0);
|
||||
if (err == ESP_OK && is_post && body_len > 0) {
|
||||
if (esp_http_client_write(cl, body, body_len) != body_len) {
|
||||
err = ESP_FAIL;
|
||||
}
|
||||
}
|
||||
int got = 0;
|
||||
int status = 0;
|
||||
if (err == ESP_OK && esp_http_client_fetch_headers(cl) >= 0) {
|
||||
status = esp_http_client_get_status_code(cl);
|
||||
int r;
|
||||
while (got < 4095 && (r = esp_http_client_read(cl, out + got, 4095 - got)) > 0) {
|
||||
got += r;
|
||||
}
|
||||
} else {
|
||||
err = ESP_FAIL;
|
||||
}
|
||||
esp_http_client_close(cl);
|
||||
esp_http_client_cleanup(cl);
|
||||
cJSON_Delete(top);
|
||||
if (err != ESP_OK) {
|
||||
result = send_error(req, "502 Bad Gateway", "could not reach that device");
|
||||
goto done;
|
||||
}
|
||||
out[got] = '\0';
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddNumberToObject(o, "status", status);
|
||||
cJSON_AddStringToObject(o, "body", out);
|
||||
result = send_json(req, o);
|
||||
}
|
||||
done:
|
||||
free(in);
|
||||
free(out);
|
||||
return result;
|
||||
}
|
||||
|
||||
// GET /api/devices: the LED drivers on this network, found by mDNS (they advertise app=led-strip).
|
||||
// Includes this driver; the page leaves it out, since "This device" is already in the list.
|
||||
static esp_err_t devices_get(httpd_req_t *req)
|
||||
{
|
||||
cJSON *arr = cJSON_CreateArray();
|
||||
mdns_result_t *res = NULL;
|
||||
if (mdns_query_ptr("_http", "_tcp", 1500, 30, &res) == ESP_OK && res) {
|
||||
for (mdns_result_t *r = res; r; r = r->next) {
|
||||
if (!r->hostname) {
|
||||
continue;
|
||||
}
|
||||
bool is_strip = false;
|
||||
for (size_t i = 0; i < r->txt_count && r->txt; i++) {
|
||||
if (r->txt[i].key && r->txt[i].value && strcmp(r->txt[i].key, "app") == 0
|
||||
&& strcmp(r->txt[i].value, "led-strip") == 0) {
|
||||
is_strip = true;
|
||||
}
|
||||
}
|
||||
if (!is_strip) {
|
||||
continue;
|
||||
}
|
||||
char ip[16] = "";
|
||||
for (mdns_ip_addr_t *a = r->addr; a; a = a->next) {
|
||||
if (a->addr.type == ESP_IPADDR_TYPE_V4) {
|
||||
snprintf(ip, sizeof(ip), IPSTR, IP2STR(&a->addr.u_addr.ip4));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ip[0] == '\0') {
|
||||
continue;
|
||||
}
|
||||
bool seen = false; // one entry per address (a service can be listed twice)
|
||||
for (int i = 0; i < cJSON_GetArraySize(arr); i++) {
|
||||
const cJSON *ip_item = cJSON_GetObjectItem(cJSON_GetArrayItem(arr, i), "ip");
|
||||
if (cJSON_IsString(ip_item) && strcmp(ip_item->valuestring, ip) == 0) {
|
||||
seen = true;
|
||||
}
|
||||
}
|
||||
if (seen) {
|
||||
continue;
|
||||
}
|
||||
char host[96];
|
||||
snprintf(host, sizeof(host), "%s.local", r->hostname);
|
||||
cJSON *o = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(o, "name", r->hostname);
|
||||
cJSON_AddStringToObject(o, "host", host);
|
||||
cJSON_AddStringToObject(o, "ip", ip);
|
||||
cJSON_AddItemToArray(arr, o);
|
||||
}
|
||||
}
|
||||
if (res) {
|
||||
mdns_query_results_free(res);
|
||||
}
|
||||
cJSON *top = cJSON_CreateObject();
|
||||
cJSON_AddItemToObject(top, "devices", arr);
|
||||
return send_json(req, top);
|
||||
}
|
||||
|
||||
esp_err_t web_start(void)
|
||||
{
|
||||
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
|
||||
cfg.max_uri_handlers = 30;
|
||||
cfg.stack_size = 8192;
|
||||
cfg.lru_purge_enable = true;
|
||||
cfg.max_open_sockets = 7;
|
||||
cfg.backlog_conn = 10;
|
||||
esp_err_t err = httpd_start(&s_server, &cfg);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "HTTP server start failed: %s", esp_err_to_name(err));
|
||||
return err;
|
||||
}
|
||||
add_uri(s_server, "/", HTTP_GET, index_get);
|
||||
add_uri(s_server, "/app.js", HTTP_GET, app_js_get);
|
||||
add_uri(s_server, "/style.css", HTTP_GET, style_css_get);
|
||||
add_uri(s_server, "/api/status", HTTP_GET, status_get);
|
||||
add_uri(s_server, "/api/pattern", HTTP_POST, pattern_post);
|
||||
add_uri(s_server, "/api/wifi", HTTP_GET, wifi_get);
|
||||
add_uri(s_server, "/api/wifi", HTTP_POST, wifi_post);
|
||||
add_uri(s_server, "/api/wifi/scan", HTTP_GET, wifi_scan_get);
|
||||
add_uri(s_server, "/api/network", HTTP_GET, network_get);
|
||||
add_uri(s_server, "/api/network", HTTP_POST, network_post);
|
||||
add_uri(s_server, "/api/ddp", HTTP_GET, ddp_get);
|
||||
add_uri(s_server, "/api/hardware", HTTP_GET, hardware_get);
|
||||
add_uri(s_server, "/api/hardware", HTTP_POST, hardware_post);
|
||||
add_uri(s_server, "/api/presets", HTTP_GET, presets_get);
|
||||
add_uri(s_server, "/api/presets", HTTP_POST, presets_post);
|
||||
add_uri(s_server, "/api/presets/select", HTTP_POST, select_post);
|
||||
add_uri(s_server, "/api/presets/delete", HTTP_POST, delete_post);
|
||||
add_uri(s_server, "/api/presets/startup", HTTP_POST, startup_post);
|
||||
add_uri(s_server, "/api/presets/defaults", HTTP_POST, presets_defaults_post);
|
||||
add_uri(s_server, "/api/presets/order", HTTP_POST, presets_order_post);
|
||||
add_uri(s_server, "/api/brightness", HTTP_POST, brightness_post);
|
||||
add_uri(s_server, "/api/relay", HTTP_POST, relay_post);
|
||||
add_uri(s_server, "/api/devices", HTTP_GET, devices_get);
|
||||
ota_register(s_server);
|
||||
ESP_LOGI(TAG, "Web UI on port 80");
|
||||
return ESP_OK;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_http_server.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @brief Start the HTTP server on port 80 (UI and JSON API). */
|
||||
esp_err_t web_start(void);
|
||||
|
||||
/**
|
||||
* @brief Add Access-Control-Allow-Origin for a LAN or localhost page that asked (the Origin header).
|
||||
* Call before the response is sent. Other origins get no header, so the browser blocks them.
|
||||
*/
|
||||
void web_allow_lan_origin(httpd_req_t *req);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include "ws2812.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "esp_check.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
static const char *TAG = "ws2812";
|
||||
|
||||
/* ---- RMT encoder: turns RGB bytes into WS2812 waveform symbols ---- */
|
||||
|
||||
typedef struct {
|
||||
rmt_encoder_t base;
|
||||
rmt_encoder_t *bytes_encoder;
|
||||
rmt_encoder_t *copy_encoder;
|
||||
int state;
|
||||
rmt_symbol_word_t reset_code;
|
||||
} rmt_ws2812_encoder_t;
|
||||
|
||||
RMT_ENCODER_FUNC_ATTR
|
||||
static size_t rmt_encode_ws2812(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state)
|
||||
{
|
||||
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
|
||||
rmt_encoder_handle_t bytes_encoder = led_encoder->bytes_encoder;
|
||||
rmt_encoder_handle_t copy_encoder = led_encoder->copy_encoder;
|
||||
rmt_encode_state_t session_state = RMT_ENCODING_RESET;
|
||||
rmt_encode_state_t state = RMT_ENCODING_RESET;
|
||||
size_t encoded_symbols = 0;
|
||||
switch (led_encoder->state) {
|
||||
case 0: // send RGB data
|
||||
encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, primary_data, data_size, &session_state);
|
||||
if (session_state & RMT_ENCODING_COMPLETE) {
|
||||
led_encoder->state = 1; // switch to next state when current encoding session finished
|
||||
}
|
||||
if (session_state & RMT_ENCODING_MEM_FULL) {
|
||||
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_MEM_FULL);
|
||||
goto out; // yield if there's no free space for encoding artifacts
|
||||
}
|
||||
// fall-through
|
||||
case 1: // send reset code
|
||||
encoded_symbols += copy_encoder->encode(copy_encoder, channel, &led_encoder->reset_code,
|
||||
sizeof(led_encoder->reset_code), &session_state);
|
||||
if (session_state & RMT_ENCODING_COMPLETE) {
|
||||
led_encoder->state = RMT_ENCODING_RESET; // back to the initial encoding session
|
||||
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_COMPLETE);
|
||||
}
|
||||
if (session_state & RMT_ENCODING_MEM_FULL) {
|
||||
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_MEM_FULL);
|
||||
goto out; // yield if there's no free space for encoding artifacts
|
||||
}
|
||||
}
|
||||
out:
|
||||
*ret_state = state;
|
||||
return encoded_symbols;
|
||||
}
|
||||
|
||||
static esp_err_t rmt_del_ws2812_encoder(rmt_encoder_t *encoder)
|
||||
{
|
||||
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
|
||||
rmt_del_encoder(led_encoder->bytes_encoder);
|
||||
rmt_del_encoder(led_encoder->copy_encoder);
|
||||
free(led_encoder);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
RMT_ENCODER_FUNC_ATTR
|
||||
static esp_err_t rmt_ws2812_encoder_reset(rmt_encoder_t *encoder)
|
||||
{
|
||||
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
|
||||
rmt_encoder_reset(led_encoder->bytes_encoder);
|
||||
rmt_encoder_reset(led_encoder->copy_encoder);
|
||||
led_encoder->state = RMT_ENCODING_RESET;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t new_ws2812_encoder(uint32_t resolution, rmt_encoder_handle_t *ret_encoder)
|
||||
{
|
||||
// Declared up front: the error path jumps forward to `err`, which C++ forbids
|
||||
// across initialised declarations.
|
||||
esp_err_t ret = ESP_OK;
|
||||
rmt_ws2812_encoder_t *led_encoder = NULL;
|
||||
rmt_bytes_encoder_config_t bytes_encoder_config = {};
|
||||
rmt_copy_encoder_config_t copy_encoder_config = {};
|
||||
uint32_t reset_ticks = 0;
|
||||
|
||||
ESP_GOTO_ON_FALSE(ret_encoder, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument");
|
||||
led_encoder = static_cast<rmt_ws2812_encoder_t *>(rmt_alloc_encoder_mem(sizeof(rmt_ws2812_encoder_t)));
|
||||
ESP_GOTO_ON_FALSE(led_encoder, ESP_ERR_NO_MEM, err, TAG, "no mem for ws2812 encoder");
|
||||
led_encoder->base.encode = rmt_encode_ws2812;
|
||||
led_encoder->base.del = rmt_del_ws2812_encoder;
|
||||
led_encoder->base.reset = rmt_ws2812_encoder_reset;
|
||||
|
||||
// WS2812 timing
|
||||
bytes_encoder_config.bit0.level0 = 1;
|
||||
bytes_encoder_config.bit0.duration0 = 0.3 * resolution / 1000000; // T0H=0.3us
|
||||
bytes_encoder_config.bit0.level1 = 0;
|
||||
bytes_encoder_config.bit0.duration1 = 0.9 * resolution / 1000000; // T0L=0.9us
|
||||
bytes_encoder_config.bit1.level0 = 1;
|
||||
bytes_encoder_config.bit1.duration0 = 0.9 * resolution / 1000000; // T1H=0.9us
|
||||
bytes_encoder_config.bit1.level1 = 0;
|
||||
bytes_encoder_config.bit1.duration1 = 0.3 * resolution / 1000000; // T1L=0.3us
|
||||
bytes_encoder_config.flags.msb_first = 1; // WS2812 transfer bit order: G7...G0R7...R0B7...B0
|
||||
ESP_GOTO_ON_ERROR(rmt_new_bytes_encoder(&bytes_encoder_config, &led_encoder->bytes_encoder), err, TAG, "create bytes encoder failed");
|
||||
ESP_GOTO_ON_ERROR(rmt_new_copy_encoder(©_encoder_config, &led_encoder->copy_encoder), err, TAG, "create copy encoder failed");
|
||||
|
||||
reset_ticks = resolution / 1000000 * 50 / 2; // reset code duration defaults to 50us
|
||||
led_encoder->reset_code.level0 = 0;
|
||||
led_encoder->reset_code.duration0 = reset_ticks;
|
||||
led_encoder->reset_code.level1 = 0;
|
||||
led_encoder->reset_code.duration1 = reset_ticks;
|
||||
|
||||
*ret_encoder = &led_encoder->base;
|
||||
return ESP_OK;
|
||||
err:
|
||||
if (led_encoder) {
|
||||
if (led_encoder->bytes_encoder) {
|
||||
rmt_del_encoder(led_encoder->bytes_encoder);
|
||||
}
|
||||
if (led_encoder->copy_encoder) {
|
||||
rmt_del_encoder(led_encoder->copy_encoder);
|
||||
}
|
||||
free(led_encoder);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* ---- WS2812 strip ---- */
|
||||
|
||||
WS2812::WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz)
|
||||
: num_leds_(num_leds), pixels_(num_leds * 3, 0), tx_pixels_(num_leds * 3, 0)
|
||||
{
|
||||
rmt_tx_channel_config_t tx_chan_config = {};
|
||||
tx_chan_config.clk_src = RMT_CLK_SRC_DEFAULT;
|
||||
tx_chan_config.gpio_num = gpio;
|
||||
tx_chan_config.mem_block_symbols = 64; // larger blocks reduce flicker
|
||||
tx_chan_config.resolution_hz = resolution_hz;
|
||||
tx_chan_config.trans_queue_depth = 4;
|
||||
ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &channel_));
|
||||
|
||||
ESP_ERROR_CHECK(new_ws2812_encoder(resolution_hz, &encoder_));
|
||||
|
||||
ESP_ERROR_CHECK(rmt_enable(channel_));
|
||||
tx_config_.loop_count = 0; // send once per write()
|
||||
|
||||
ESP_LOGI(TAG, "Strip ready: %zu LEDs on GPIO %d", num_leds_, (int)gpio);
|
||||
}
|
||||
|
||||
WS2812::~WS2812()
|
||||
{
|
||||
if (channel_) {
|
||||
rmt_tx_wait_all_done(channel_, portMAX_DELAY);
|
||||
rmt_disable(channel_);
|
||||
rmt_del_channel(channel_);
|
||||
}
|
||||
if (encoder_) {
|
||||
encoder_->del(encoder_);
|
||||
}
|
||||
}
|
||||
|
||||
void WS2812::set(size_t index, uint8_t r, uint8_t g, uint8_t b)
|
||||
{
|
||||
if (index >= num_leds_) {
|
||||
return;
|
||||
}
|
||||
uint8_t *p = &pixels_[index * 3];
|
||||
uint8_t c[3] = { r, g, b };
|
||||
p[0] = c[order_[0]];
|
||||
p[1] = c[order_[1]];
|
||||
p[2] = c[order_[2]];
|
||||
}
|
||||
|
||||
void WS2812::setOrder(const char *order)
|
||||
{
|
||||
if (!order || strlen(order) != 3) {
|
||||
return;
|
||||
}
|
||||
uint8_t idx[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
switch (order[i]) {
|
||||
case 'r': idx[i] = 0; break;
|
||||
case 'g': idx[i] = 1; break;
|
||||
case 'b': idx[i] = 2; break;
|
||||
default: return;
|
||||
}
|
||||
}
|
||||
if (idx[0] == idx[1] || idx[1] == idx[2] || idx[0] == idx[2]) {
|
||||
return;
|
||||
}
|
||||
memcpy(order_, idx, sizeof(order_));
|
||||
}
|
||||
|
||||
void WS2812::fill(uint8_t r, uint8_t g, uint8_t b)
|
||||
{
|
||||
for (size_t i = 0; i < num_leds_; i++) {
|
||||
set(i, r, g, b);
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t WS2812::write()
|
||||
{
|
||||
for (size_t i = 0; i < pixels_.size(); i++) {
|
||||
tx_pixels_[i] = static_cast<uint8_t>(pixels_[i] * brightness_ / 255);
|
||||
}
|
||||
esp_err_t ret = rmt_transmit(channel_, encoder_, tx_pixels_.data(), tx_pixels_.size(), &tx_config_);
|
||||
if (ret != ESP_OK) {
|
||||
return ret;
|
||||
}
|
||||
return rmt_tx_wait_all_done(channel_, portMAX_DELAY);
|
||||
}
|
||||
|
||||
void WS2812::hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b)
|
||||
{
|
||||
h %= 360; // h -> [0,360]
|
||||
uint32_t rgb_max = v * 2.55f;
|
||||
uint32_t rgb_min = rgb_max * (100 - s) / 100.0f;
|
||||
|
||||
uint32_t i = h / 60;
|
||||
uint32_t diff = h % 60;
|
||||
|
||||
// RGB adjustment amount by hue
|
||||
uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60;
|
||||
|
||||
switch (i) {
|
||||
case 0:
|
||||
*r = rgb_max;
|
||||
*g = rgb_min + rgb_adj;
|
||||
*b = rgb_min;
|
||||
break;
|
||||
case 1:
|
||||
*r = rgb_max - rgb_adj;
|
||||
*g = rgb_max;
|
||||
*b = rgb_min;
|
||||
break;
|
||||
case 2:
|
||||
*r = rgb_min;
|
||||
*g = rgb_max;
|
||||
*b = rgb_min + rgb_adj;
|
||||
break;
|
||||
case 3:
|
||||
*r = rgb_min;
|
||||
*g = rgb_max - rgb_adj;
|
||||
*b = rgb_max;
|
||||
break;
|
||||
case 4:
|
||||
*r = rgb_min + rgb_adj;
|
||||
*g = rgb_min;
|
||||
*b = rgb_max;
|
||||
break;
|
||||
default:
|
||||
*r = rgb_max;
|
||||
*g = rgb_min;
|
||||
*b = rgb_max - rgb_adj;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "driver/gpio.h"
|
||||
#include "driver/rmt_encoder.h"
|
||||
#include "driver/rmt_tx.h"
|
||||
#include "esp_err.h"
|
||||
|
||||
/**
|
||||
* @brief WS2812-style addressable LED strip driven through the RMT peripheral.
|
||||
*
|
||||
* Pixel data is kept in a local buffer. set() and fill() only update that buffer;
|
||||
* call write() to push the buffer out to the strip.
|
||||
*/
|
||||
class WS2812 {
|
||||
public:
|
||||
/**
|
||||
* @param gpio GPIO connected to the strip's data input (DI)
|
||||
* @param num_leds Number of LEDs in the strip
|
||||
* @param resolution_hz RMT tick resolution; 10 MHz gives 0.1 us ticks, which WS2812 needs
|
||||
*/
|
||||
WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz = 10000000);
|
||||
~WS2812();
|
||||
|
||||
WS2812(const WS2812 &) = delete;
|
||||
WS2812 &operator=(const WS2812 &) = delete;
|
||||
|
||||
/** @brief Set one pixel in the buffer. Out-of-range indices are ignored. */
|
||||
void set(size_t index, uint8_t r, uint8_t g, uint8_t b);
|
||||
|
||||
/** @brief Set every pixel in the buffer to the same colour. */
|
||||
void fill(uint8_t r, uint8_t g, uint8_t b);
|
||||
|
||||
/**
|
||||
* @brief Transmit the buffer to the strip and wait until the transfer finishes.
|
||||
* @return ESP_OK on success, or an error from the RMT driver.
|
||||
*/
|
||||
esp_err_t write();
|
||||
|
||||
/** @brief Number of LEDs in the strip. */
|
||||
size_t size() const { return num_leds_; }
|
||||
|
||||
/**
|
||||
* @brief Set the output brightness, 0 (off) to 255 (full). Applied in write();
|
||||
* the pixel buffer keeps its full-colour values. Defaults to 255.
|
||||
*/
|
||||
void setBrightness(uint8_t level) { brightness_ = level; }
|
||||
|
||||
/** @brief Current output brightness, 0-255. */
|
||||
uint8_t brightness() const { return brightness_; }
|
||||
|
||||
/**
|
||||
* @brief Convert HSV to RGB.
|
||||
*
|
||||
* h is the hue in degrees (wrapped to [0, 360)); s and v are 0-100 percent.
|
||||
* Wiki: https://en.wikipedia.org/wiki/HSL_and_HSV
|
||||
*/
|
||||
static void hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b);
|
||||
|
||||
/**
|
||||
* @brief Byte order of the strip, as the letters of the colours in the order they are sent.
|
||||
* "grb" (the default) is the WS2812 norm; "rgb", "rbg", "gbr", "brg" and "bgr" cover the rest.
|
||||
* Unknown names keep the current order.
|
||||
*/
|
||||
void setOrder(const char *order);
|
||||
|
||||
private:
|
||||
size_t num_leds_;
|
||||
uint8_t order_[3] = { 1, 0, 2 }; // indices into (r, g, b) for each byte sent: GRB
|
||||
std::vector<uint8_t> pixels_; // 3 bytes per LED, in the strip's byte order
|
||||
std::vector<uint8_t> tx_pixels_; // pixels_ scaled by brightness_, sent by write()
|
||||
uint8_t brightness_ = 255;
|
||||
rmt_channel_handle_t channel_ = nullptr;
|
||||
rmt_encoder_handle_t encoder_ = nullptr;
|
||||
rmt_transmit_config_t tx_config_ = {};
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
# Name, Type, SubType, Offset, Size
|
||||
nvs, data, nvs, 0x9000, 0x6000
|
||||
otadata, data, ota, 0xf000, 0x2000
|
||||
phy_init, data, phy, 0x11000, 0x1000
|
||||
ota_0, app, ota_0, 0x20000, 0x1E0000
|
||||
ota_1, app, ota_1, 0x200000, 0x1E0000
|
||||
|
@@ -0,0 +1,11 @@
|
||||
CONFIG_IDF_TARGET="esp32c3"
|
||||
# The mDNS console CLI needs the console component; the app does not use it.
|
||||
CONFIG_MDNS_ENABLE_CONSOLE_CLI=n
|
||||
# The chip has 4 MB: two app slots for over-the-air updates (see partitions.csv)
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||
# A new OTA image must confirm itself (ota_confirm_later) or the bootloader goes back to the old one
|
||||
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||
# mDNS opens sockets on both the AP and client interfaces, plus HTTP and DDP. The default 10 runs out and httpd stops accepting.
|
||||
CONFIG_LWIP_MAX_SOCKETS=16
|
||||
@@ -1,17 +0,0 @@
|
||||
import asyncio
|
||||
import utime
|
||||
|
||||
from mem_stats import print_mem
|
||||
|
||||
|
||||
async def presets_loop(presets, wdt):
|
||||
last_mem_log = utime.ticks_ms()
|
||||
while True:
|
||||
presets.tick()
|
||||
wdt.feed()
|
||||
if bool(getattr(presets, "debug", False)):
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_mem_log) >= 5000:
|
||||
print_mem("runtime")
|
||||
last_mem_log = now
|
||||
await asyncio.sleep(0)
|
||||
@@ -1,92 +0,0 @@
|
||||
import struct
|
||||
|
||||
WIRE_MAGIC = 0x4C
|
||||
MSG_BEAT = 0x25
|
||||
FRAME_LEN = 8 # [4C][25][flags][idx u16][period u16][fire_in]
|
||||
MIN_GUARD_MS = 30
|
||||
FREERUN_MISS_MAX = 4
|
||||
RESTART_BEATS = 3 # consecutive beats that all look old mean the controller restarted its counter
|
||||
|
||||
|
||||
def _diff(a, b):
|
||||
return (a - b) & 0xFFFF
|
||||
|
||||
|
||||
class BeatSync:
|
||||
"""Turns beat frames from the controller into step triggers.
|
||||
|
||||
The controller sends every beat twice with the same index; only the first
|
||||
copy that arrives is acted on. Between frames the driver free-runs on the
|
||||
last period so a lost beat is not noticed.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.last_idx = None
|
||||
self.period = 0
|
||||
self.last_fire = 0
|
||||
self.fire_at = None
|
||||
self.downbeat = False
|
||||
self.bar = 0
|
||||
self.missed = 0
|
||||
self.stale_idx = None # newest index seen while every frame looked old
|
||||
self.stale_n = 0
|
||||
self.freerun_fire = False # True when the last fire was invented, not triggered by a frame
|
||||
# fires: beats acted on; dups: second copies dropped; late: too-soon or old frames;
|
||||
# freerun: beats the driver made up because no frame arrived
|
||||
self.stats = {"fires": 0, "dups": 0, "late": 0, "freerun": 0}
|
||||
|
||||
def on_frame(self, data, now):
|
||||
"""Handle one received frame. Call from the ESP-NOW irq: no allocation beyond unpack."""
|
||||
if len(data) != FRAME_LEN or data[0] != WIRE_MAGIC or data[1] != MSG_BEAT:
|
||||
return False
|
||||
flags, idx, period, fire_in = struct.unpack_from("<BHHB", data, 2)
|
||||
if self.last_idx is not None:
|
||||
if idx == self.last_idx:
|
||||
self.stats["dups"] += 1
|
||||
return False # second copy of a beat we already took
|
||||
guard = max(MIN_GUARD_MS, self.period // 2)
|
||||
if _diff(idx, self.last_idx) >= 0x8000:
|
||||
# Behind us. A late copy is one or two frames; a controller that rebooted and
|
||||
# restarted its counter sends a run of consecutive indices, so follow it.
|
||||
if idx == self.stale_idx:
|
||||
self.stats["late"] += 1
|
||||
return False
|
||||
self.stale_n = self.stale_n + 1 if self.stale_idx is not None and _diff(idx, self.stale_idx) == 1 else 1
|
||||
self.stale_idx = idx
|
||||
if self.stale_n < RESTART_BEATS:
|
||||
self.stats["late"] += 1
|
||||
return False
|
||||
elif (
|
||||
self.fire_at is None and now - self.last_fire < guard and self.period
|
||||
):
|
||||
self.stats["late"] += 1
|
||||
return False # late copy of an older beat, or too soon after the last one
|
||||
self.stale_idx = None
|
||||
self.stale_n = 0
|
||||
self.last_idx = idx
|
||||
self.period = period
|
||||
self.downbeat = bool(flags & 1)
|
||||
self.bar = (flags >> 1) & 7
|
||||
self.fire_at = now + fire_in
|
||||
self.missed = 0
|
||||
return True
|
||||
|
||||
def poll(self, now):
|
||||
"""True when a beat should step the pattern now. Call every tick."""
|
||||
if self.fire_at is not None:
|
||||
if now - self.fire_at >= 0:
|
||||
self.fire_at = None
|
||||
self.last_fire = now
|
||||
self.freerun_fire = False
|
||||
self.stats["fires"] += 1
|
||||
return True
|
||||
return False
|
||||
if self.period and self.last_idx is not None and self.missed < FREERUN_MISS_MAX:
|
||||
if now - (self.last_fire + self.period + self.period // 4) >= 0:
|
||||
self.last_fire += self.period
|
||||
self.missed += 1
|
||||
self.freerun_fire = True
|
||||
self.stats["fires"] += 1
|
||||
self.stats["freerun"] += 1
|
||||
return True
|
||||
return False
|
||||
@@ -1,209 +0,0 @@
|
||||
"""Decode compact binary controller envelopes — v2 native binary, v1 legacy JSON blobs."""
|
||||
|
||||
import json
|
||||
import struct
|
||||
|
||||
BINARY_ENVELOPE_VERSION_1 = 1
|
||||
BINARY_ENVELOPE_VERSION_2 = 2
|
||||
HEADER_LEN = 5
|
||||
|
||||
|
||||
def _brightness_0_255_from_wire(wire):
|
||||
w = max(0, min(127, int(wire)))
|
||||
return min(255, (w * 255) // 127)
|
||||
|
||||
|
||||
def _decode_preset_record(buf, off):
|
||||
nl = buf[off]
|
||||
off += 1
|
||||
name = buf[off : off + nl].decode("utf-8")
|
||||
off += nl
|
||||
pl = buf[off]
|
||||
off += 1
|
||||
pattern = buf[off : off + pl].decode("utf-8")
|
||||
off += pl
|
||||
nc = buf[off]
|
||||
off += 1
|
||||
colors = []
|
||||
for _ in range(nc):
|
||||
r, g, b = buf[off], buf[off + 1], buf[off + 2]
|
||||
off += 3
|
||||
colors.append("#%02x%02x%02x" % (r, g, b))
|
||||
if off + 16 > len(buf):
|
||||
raise ValueError("truncated")
|
||||
delay, br, auto, n1, n2, n3, n4, n5, n6 = struct.unpack_from(
|
||||
"<HBBhhhhhh", buf, off
|
||||
)
|
||||
off += 16
|
||||
preset = {
|
||||
"p": pattern,
|
||||
"c": colors,
|
||||
"d": delay,
|
||||
"b": br,
|
||||
"a": bool(auto),
|
||||
"n1": n1,
|
||||
"n2": n2,
|
||||
"n3": n3,
|
||||
"n4": n4,
|
||||
"n5": n5,
|
||||
"n6": n6,
|
||||
}
|
||||
return name, preset, off
|
||||
|
||||
|
||||
def _decode_presets_blob(chunk):
|
||||
if not chunk:
|
||||
return {}
|
||||
off = 0
|
||||
count = chunk[off]
|
||||
off += 1
|
||||
out = {}
|
||||
for _ in range(count):
|
||||
name, preset, off = _decode_preset_record(chunk, off)
|
||||
out[name] = preset
|
||||
if off != len(chunk):
|
||||
raise ValueError("presets blob mismatch")
|
||||
return out
|
||||
|
||||
|
||||
def _decode_select_blob(chunk):
|
||||
if not chunk:
|
||||
return {}
|
||||
off = 0
|
||||
count = chunk[off]
|
||||
off += 1
|
||||
out = {}
|
||||
for _ in range(count):
|
||||
dl = chunk[off]
|
||||
off += 1
|
||||
device = chunk[off : off + dl].decode("utf-8")
|
||||
off += dl
|
||||
pl = chunk[off]
|
||||
off += 1
|
||||
pname = chunk[off : off + pl].decode("utf-8")
|
||||
off += pl
|
||||
has_step = chunk[off]
|
||||
off += 1
|
||||
if has_step:
|
||||
step = struct.unpack_from("<H", chunk, off)[0]
|
||||
off += 2
|
||||
out[device] = [pname, step]
|
||||
else:
|
||||
out[device] = [pname]
|
||||
if off != len(chunk):
|
||||
raise ValueError("select blob mismatch")
|
||||
return out
|
||||
|
||||
|
||||
def _decode_default_blob(chunk):
|
||||
if not chunk:
|
||||
return "", []
|
||||
off = 0
|
||||
nl = chunk[off]
|
||||
off += 1
|
||||
default_name = chunk[off : off + nl].decode("utf-8") if nl else ""
|
||||
off += nl
|
||||
nt = chunk[off]
|
||||
off += 1
|
||||
targets = []
|
||||
for _ in range(nt):
|
||||
tl = chunk[off]
|
||||
off += 1
|
||||
targets.append(chunk[off : off + tl].decode("utf-8"))
|
||||
off += tl
|
||||
if off != len(chunk):
|
||||
raise ValueError("default blob mismatch")
|
||||
return default_name, targets
|
||||
|
||||
|
||||
def parse_binary_envelope_v2(buf):
|
||||
if not isinstance(buf, (bytes, bytearray)) or len(buf) < HEADER_LEN:
|
||||
return None
|
||||
if buf[0] != BINARY_ENVELOPE_VERSION_2:
|
||||
return None
|
||||
lp = buf[2]
|
||||
ls = buf[3]
|
||||
ld = buf[4]
|
||||
need = HEADER_LEN + lp + ls + ld
|
||||
if len(buf) != need:
|
||||
return None
|
||||
|
||||
off = HEADER_LEN
|
||||
presets_chunk = buf[off : off + lp]
|
||||
off += lp
|
||||
select_chunk = buf[off : off + ls]
|
||||
off += ls
|
||||
default_chunk = buf[off : off + ld]
|
||||
|
||||
data = {"v": "1"}
|
||||
br = buf[1]
|
||||
if br < 128:
|
||||
data["b"] = _brightness_0_255_from_wire(br)
|
||||
|
||||
try:
|
||||
if lp:
|
||||
data["presets"] = _decode_presets_blob(presets_chunk)
|
||||
if ls:
|
||||
data["select"] = _decode_select_blob(select_chunk)
|
||||
if ld:
|
||||
dname, targets = _decode_default_blob(default_chunk)
|
||||
data["default"] = dname
|
||||
data["targets"] = targets
|
||||
except (ValueError, UnicodeError, TypeError, struct.error):
|
||||
return None
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def parse_binary_envelope_v1(buf):
|
||||
if not isinstance(buf, (bytes, bytearray)) or len(buf) < HEADER_LEN:
|
||||
return None
|
||||
if buf[0] != BINARY_ENVELOPE_VERSION_1:
|
||||
return None
|
||||
lp = buf[2]
|
||||
ls = buf[3]
|
||||
ld = buf[4]
|
||||
need = HEADER_LEN + lp + ls + ld
|
||||
if len(buf) != need:
|
||||
return None
|
||||
|
||||
off = HEADER_LEN
|
||||
presets_chunk = buf[off : off + lp]
|
||||
off += lp
|
||||
select_chunk = buf[off : off + ls]
|
||||
off += ls
|
||||
default_chunk = buf[off : off + ld]
|
||||
|
||||
data = {"v": "1"}
|
||||
|
||||
br = buf[1]
|
||||
if br < 128:
|
||||
data["b"] = _brightness_0_255_from_wire(br)
|
||||
|
||||
if lp:
|
||||
try:
|
||||
data["presets"] = json.loads(presets_chunk.decode("utf-8"))
|
||||
except (ValueError, UnicodeError):
|
||||
return None
|
||||
if ls:
|
||||
try:
|
||||
data["select"] = json.loads(select_chunk.decode("utf-8"))
|
||||
except (ValueError, UnicodeError):
|
||||
return None
|
||||
if ld:
|
||||
try:
|
||||
extra = json.loads(default_chunk.decode("utf-8"))
|
||||
except (ValueError, UnicodeError):
|
||||
return None
|
||||
if isinstance(extra, dict):
|
||||
for k, v in extra.items():
|
||||
data[k] = v
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def parse_binary_envelope(buf):
|
||||
d = parse_binary_envelope_v2(buf)
|
||||
if d is not None:
|
||||
return d
|
||||
return parse_binary_envelope_v1(buf)
|
||||
@@ -1,41 +0,0 @@
|
||||
"""ESP32-C3 and ESP32-S3 differences for the LED driver.
|
||||
|
||||
Seeed XIAO silk-screen D10 is GPIO 10 on the C3 and GPIO 9 on the S3.
|
||||
Fresh settings use that pad. A saved ``led_pin`` is left unchanged.
|
||||
"""
|
||||
|
||||
try:
|
||||
import uos as os
|
||||
except ImportError:
|
||||
import os
|
||||
|
||||
import machine
|
||||
|
||||
_LED_PIN_C3 = 10
|
||||
_LED_PIN_S3 = 9
|
||||
_CPU_HZ_C3 = 160000000
|
||||
_CPU_HZ_S3 = 240000000
|
||||
|
||||
|
||||
def mcu():
|
||||
"""Return ``s3``, ``c3``, or ``""`` when the chip is neither."""
|
||||
name = os.uname().machine.upper().replace("-", "")
|
||||
if "ESP32S3" in name:
|
||||
return "s3"
|
||||
if "ESP32C3" in name:
|
||||
return "c3"
|
||||
return ""
|
||||
|
||||
|
||||
def default_led_pin():
|
||||
if mcu() == "s3":
|
||||
return _LED_PIN_S3
|
||||
return _LED_PIN_C3
|
||||
|
||||
|
||||
def apply_cpu_freq():
|
||||
"""C3 maximum is 160 MHz. S3 (XIAO firmware) runs at 240 MHz."""
|
||||
if mcu() == "s3":
|
||||
machine.freq(_CPU_HZ_S3)
|
||||
else:
|
||||
machine.freq(_CPU_HZ_C3)
|
||||
@@ -1,512 +0,0 @@
|
||||
"""Parse controller JSON (v1) and apply brightness, presets, OTA patterns, etc."""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import network
|
||||
import ubinascii
|
||||
|
||||
import device_groups as dg
|
||||
from v1_wire import expand_v1
|
||||
from binary_envelope import parse_binary_envelope
|
||||
from utils import convert_and_reorder_colors
|
||||
|
||||
try:
|
||||
import uos as os
|
||||
except ImportError:
|
||||
import os
|
||||
|
||||
|
||||
def _log_rx(payload) -> None:
|
||||
"""Serial log when led-controller sends a message into ``process_data``."""
|
||||
try:
|
||||
if isinstance(payload, (bytes, bytearray)):
|
||||
n = len(payload)
|
||||
if n == 0:
|
||||
print("rx 0 B")
|
||||
return
|
||||
cap = 160
|
||||
chunk = payload if n <= cap else payload[:cap]
|
||||
try:
|
||||
txt = bytes(chunk).decode("utf-8")
|
||||
except Exception:
|
||||
txt = str(chunk)
|
||||
if n > cap:
|
||||
txt = txt + "..."
|
||||
print("rx", n, "B", txt)
|
||||
else:
|
||||
s = str(payload)
|
||||
cap = 200
|
||||
if len(s) <= cap:
|
||||
print("rx", len(s), "C", s)
|
||||
else:
|
||||
print("rx", len(s), "C", s[:cap] + "...")
|
||||
except Exception:
|
||||
print("rx (logging failed)")
|
||||
|
||||
|
||||
def process_data(payload, settings, presets, controller_ip=None, save=False):
|
||||
"""Read one controller message; binary v2 envelope or JSON v1, then apply fields."""
|
||||
_log_rx(payload)
|
||||
data = None
|
||||
if isinstance(payload, (bytes, bytearray)):
|
||||
data = parse_binary_envelope(payload)
|
||||
if data is None:
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except (ValueError, TypeError):
|
||||
return
|
||||
else:
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except (ValueError, TypeError):
|
||||
return
|
||||
if data.get("v", "") != "1":
|
||||
return
|
||||
data = expand_v1(data)
|
||||
if save:
|
||||
data["save"] = True
|
||||
set_groups = bool(data.get("set_groups"))
|
||||
groups = data.get("groups")
|
||||
if set_groups and isinstance(groups, list):
|
||||
dg.groups_replace(groups, settings)
|
||||
print("groups set", dg.list_groups())
|
||||
elif isinstance(groups, list) and groups:
|
||||
if not any(dg.in_group(str(g)) for g in groups):
|
||||
print("ignored: not in groups", groups)
|
||||
return
|
||||
if "device_config" in data:
|
||||
apply_device_config(data, settings, presets)
|
||||
if "b" in data:
|
||||
apply_brightness(data, settings, presets)
|
||||
if "presets" in data:
|
||||
apply_presets(data, settings, presets)
|
||||
if "clear_presets" in data:
|
||||
apply_clear_presets(data, presets)
|
||||
if ("select" in data or "s" in data) and "presets" not in data:
|
||||
apply_select(data, settings, presets)
|
||||
if "default" in data:
|
||||
apply_default(data, settings, presets)
|
||||
if "manifest" in data:
|
||||
apply_patterns_ota(data, presets, controller_ip=controller_ip)
|
||||
if "save" in data and ("presets" in data or "default" in data):
|
||||
presets.save()
|
||||
if "save" in data and "clear_presets" in data:
|
||||
presets.save()
|
||||
if "save" in data and "b" in data:
|
||||
settings.save()
|
||||
if "save" in data and "device_config" in data:
|
||||
settings.save()
|
||||
_flush_pending_select(settings, presets)
|
||||
|
||||
|
||||
_VALID_DEVICE_COLOR_ORDERS = frozenset({"rgb", "rbg", "grb", "gbr", "brg", "bgr"})
|
||||
_STARTUP_MODES = frozenset({"default", "last", "off"})
|
||||
_MAX_DEVICE_LEDS = 2048
|
||||
|
||||
|
||||
def apply_startup_pattern(settings, presets):
|
||||
"""Apply power-on behaviour from ``startup_mode`` (default / last / off)."""
|
||||
mode = str(settings.get("startup_mode", "default")).lower().strip()
|
||||
if mode not in _STARTUP_MODES:
|
||||
mode = "default"
|
||||
if mode == "off":
|
||||
if presets.select("off"):
|
||||
return
|
||||
presets.fill((0, 0, 0))
|
||||
return
|
||||
if mode == "last":
|
||||
lp = settings.get("last_preset") or ""
|
||||
if isinstance(lp, str) and lp.strip() and lp.strip() in presets.presets:
|
||||
if presets.select(lp.strip()):
|
||||
return
|
||||
dp = settings.get("default", "")
|
||||
if dp and dp in presets.presets:
|
||||
if not presets.select(dp):
|
||||
print("Startup preset failed (invalid pattern?):", dp)
|
||||
|
||||
|
||||
def _config_flag(value):
|
||||
"""Parse a device_config boolean. None if the value is not a flag."""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, int) and not isinstance(value, bool):
|
||||
return value != 0
|
||||
if isinstance(value, str):
|
||||
s = value.strip().lower()
|
||||
if s in ("1", "true", "yes", "on"):
|
||||
return True
|
||||
if s in ("0", "false", "no", "off"):
|
||||
return False
|
||||
return None
|
||||
|
||||
|
||||
def apply_device_config(data, settings, presets):
|
||||
"""Apply fields from v1 ``device_config``; reload presets when strip length or colour order changes."""
|
||||
dc = data.get("device_config")
|
||||
if not isinstance(dc, dict):
|
||||
return
|
||||
strip_changed = False
|
||||
meta_changed = False
|
||||
if "name" in dc:
|
||||
n = dc["name"]
|
||||
if isinstance(n, str) and n.strip():
|
||||
settings["name"] = n.strip()
|
||||
meta_changed = True
|
||||
if "num_leds" in dc:
|
||||
try:
|
||||
n = int(dc["num_leds"])
|
||||
if 1 <= n <= _MAX_DEVICE_LEDS:
|
||||
settings["num_leds"] = n
|
||||
presets.update_num_leds(settings["led_pin"], n)
|
||||
strip_changed = True
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if "color_order" in dc:
|
||||
co = str(dc["color_order"]).lower().strip()
|
||||
if co in _VALID_DEVICE_COLOR_ORDERS:
|
||||
settings["color_order"] = co
|
||||
settings.color_order = settings.get_color_order(co)
|
||||
strip_changed = True
|
||||
if "startup_mode" in dc:
|
||||
sm = str(dc["startup_mode"]).lower().strip()
|
||||
if sm in _STARTUP_MODES:
|
||||
settings["startup_mode"] = sm
|
||||
meta_changed = True
|
||||
if "reversed" in dc:
|
||||
flag = _config_flag(dc["reversed"])
|
||||
if flag is not None:
|
||||
settings["reversed"] = flag
|
||||
presets.reversed = flag
|
||||
meta_changed = True
|
||||
max_changed = False
|
||||
if "max_brightness" in dc:
|
||||
try:
|
||||
mb = max(0, min(255, int(dc["max_brightness"])))
|
||||
max_changed = presets.max_b != mb
|
||||
settings["max_brightness"] = mb
|
||||
presets.max_b = mb
|
||||
meta_changed = True
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if not strip_changed and not meta_changed:
|
||||
return
|
||||
if max_changed and not strip_changed and presets.selected in presets.presets:
|
||||
presets.select(presets.selected) # redraw static patterns under the new ceiling
|
||||
if strip_changed:
|
||||
prev = presets.selected
|
||||
try:
|
||||
presets.load(settings)
|
||||
except Exception as e:
|
||||
print("device_config: presets.load failed:", e)
|
||||
if prev and prev in presets.presets:
|
||||
presets.select(prev)
|
||||
elif settings.get("default") and settings["default"] in presets.presets:
|
||||
presets.select(settings["default"])
|
||||
|
||||
|
||||
def record_last_preset(settings, preset_name):
|
||||
"""Persist the last selected preset id (single entry in flash)."""
|
||||
if not isinstance(preset_name, str) or not preset_name:
|
||||
return
|
||||
settings["last_preset"] = preset_name.strip()
|
||||
settings.save()
|
||||
|
||||
|
||||
def apply_brightness(data, settings, presets):
|
||||
try:
|
||||
new_b = max(0, min(255, int(data["b"])))
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
changed = int(presets.b) != new_b
|
||||
presets.b = new_b
|
||||
settings["brightness"] = new_b
|
||||
# A finished manual chase frame keeps the colours scaled at the last beat.
|
||||
# Skip when this message also selects: that select redraws after ``b`` is set.
|
||||
if not changed or presets.generator is not None:
|
||||
return
|
||||
if "select" in data or "s" in data:
|
||||
return
|
||||
name = presets.selected
|
||||
preset = presets.presets.get(name) if name else None
|
||||
if preset is None or getattr(preset, "p", None) != "chase":
|
||||
return
|
||||
presets.redraw = True
|
||||
try:
|
||||
presets.select(name)
|
||||
finally:
|
||||
presets.redraw = False
|
||||
|
||||
|
||||
_pending_select = None
|
||||
|
||||
|
||||
def _run_select(presets, settings, preset_name, step=None):
|
||||
if presets.select(preset_name, step=step):
|
||||
record_last_preset(settings, preset_name)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _flush_pending_select(settings, presets):
|
||||
global _pending_select
|
||||
if _pending_select is None:
|
||||
return
|
||||
preset_name, step = _pending_select
|
||||
if preset_name not in presets.presets and preset_name not in ("on", "off"):
|
||||
return
|
||||
_pending_select = None
|
||||
if not _run_select(presets, settings, preset_name, step):
|
||||
print("select failed (pending):", preset_name)
|
||||
|
||||
|
||||
def apply_presets(data, settings, presets):
|
||||
global _pending_select
|
||||
presets_map = data["presets"]
|
||||
for id, preset_data in presets_map.items():
|
||||
if not preset_data:
|
||||
continue
|
||||
color_key = "c" if "c" in preset_data else ("colors" if "colors" in preset_data else None)
|
||||
if color_key is not None:
|
||||
try:
|
||||
preset_data[color_key] = convert_and_reorder_colors(
|
||||
preset_data[color_key], settings
|
||||
)
|
||||
except (TypeError, ValueError, KeyError) as err:
|
||||
print("preset color convert failed:", id, err)
|
||||
if "bg" in preset_data:
|
||||
try:
|
||||
bg_color = convert_and_reorder_colors([preset_data["bg"]], settings)
|
||||
if bg_color:
|
||||
preset_data["bg"] = bg_color[0]
|
||||
except (TypeError, ValueError, KeyError):
|
||||
pass
|
||||
presets.edit(id, preset_data)
|
||||
# Same message often carries select; apply now while presets are loaded.
|
||||
if "select" in data or "s" in data:
|
||||
apply_select(data, settings, presets)
|
||||
else:
|
||||
_flush_pending_select(settings, presets)
|
||||
|
||||
|
||||
def _select_list_for_this_device(select_val, settings):
|
||||
"""Resolve select to ``[preset_id, step?]`` (wire list or legacy name map)."""
|
||||
if isinstance(select_val, list) and select_val:
|
||||
return select_val
|
||||
if isinstance(select_val, str) and str(select_val).strip():
|
||||
return [str(select_val).strip()]
|
||||
if not isinstance(select_val, dict) or not select_val:
|
||||
return None
|
||||
if "preset" in select_val:
|
||||
preset_name = select_val.get("preset")
|
||||
if preset_name is None:
|
||||
return None
|
||||
out = [str(preset_name)]
|
||||
if "step" in select_val:
|
||||
out.append(select_val["step"])
|
||||
return out
|
||||
device_name = str(settings.get("name") or "").strip()
|
||||
select_list = select_val.get(device_name)
|
||||
if select_list:
|
||||
return select_list
|
||||
try:
|
||||
sta = network.WLAN(network.STA_IF)
|
||||
mac_hex = ubinascii.hexlify(sta.config("mac")).decode().lower()
|
||||
except Exception:
|
||||
mac_hex = ""
|
||||
if mac_hex:
|
||||
for key in select_val:
|
||||
k = str(key).lower().replace(":", "").replace("-", "")
|
||||
if mac_hex in k:
|
||||
return select_val[key]
|
||||
if len(select_val) == 1:
|
||||
return next(iter(select_val.values()))
|
||||
return None
|
||||
|
||||
|
||||
def apply_select(data, settings, presets):
|
||||
global _pending_select
|
||||
select_val = data.get("select")
|
||||
if select_val is None:
|
||||
select_val = data.get("s")
|
||||
select_list = _select_list_for_this_device(select_val, settings)
|
||||
if not select_list:
|
||||
print("select ignored:", repr(select_val))
|
||||
return
|
||||
preset_name = str(select_list[0]).strip()
|
||||
if not preset_name:
|
||||
return
|
||||
step = select_list[1] if len(select_list) > 1 else None
|
||||
if preset_name not in presets.presets and preset_name not in ("on", "off"):
|
||||
try:
|
||||
presets.load(settings)
|
||||
except Exception:
|
||||
pass
|
||||
if preset_name not in presets.presets and preset_name not in ("on", "off"):
|
||||
_pending_select = (preset_name, step)
|
||||
print("select deferred (preset not loaded yet):", preset_name)
|
||||
return
|
||||
if _run_select(presets, settings, preset_name, step):
|
||||
_pending_select = None
|
||||
else:
|
||||
print("select failed:", preset_name)
|
||||
|
||||
|
||||
def apply_clear_presets(data, presets):
|
||||
clear_value = data.get("clear_presets")
|
||||
if isinstance(clear_value, bool):
|
||||
should_clear = clear_value
|
||||
elif isinstance(clear_value, int):
|
||||
should_clear = bool(clear_value)
|
||||
elif isinstance(clear_value, str):
|
||||
should_clear = clear_value.lower() in ("true", "1", "yes", "on")
|
||||
else:
|
||||
should_clear = False
|
||||
if not should_clear:
|
||||
return
|
||||
presets.delete_all()
|
||||
|
||||
|
||||
def apply_default(data, settings, presets):
|
||||
targets = data.get("targets") or []
|
||||
default_name = data["default"]
|
||||
if (
|
||||
settings["name"] in targets
|
||||
and isinstance(default_name, str)
|
||||
and default_name in presets.presets
|
||||
):
|
||||
settings["default"] = default_name
|
||||
settings.save()
|
||||
|
||||
|
||||
def _parse_http_url(url):
|
||||
"""Parse http://host[:port]/path into (host, port, path)."""
|
||||
if not isinstance(url, str):
|
||||
raise ValueError("url must be a string")
|
||||
if not url.startswith("http://"):
|
||||
raise ValueError("only http:// URLs are supported")
|
||||
remainder = url[7:]
|
||||
slash_idx = remainder.find("/")
|
||||
if slash_idx == -1:
|
||||
host_port = remainder
|
||||
path = "/"
|
||||
else:
|
||||
host_port = remainder[:slash_idx]
|
||||
path = remainder[slash_idx:]
|
||||
if ":" in host_port:
|
||||
host, port_s = host_port.rsplit(":", 1)
|
||||
port = int(port_s)
|
||||
else:
|
||||
host = host_port
|
||||
port = 80
|
||||
if not host:
|
||||
raise ValueError("missing host")
|
||||
return host, port, path
|
||||
|
||||
|
||||
def _http_get_raw(url, timeout_s=10.0):
|
||||
host, port, path = _parse_http_url(url)
|
||||
req = (
|
||||
"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" % (path, host)
|
||||
).encode("utf-8")
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.settimeout(timeout_s)
|
||||
sock.connect((host, int(port)))
|
||||
sock.send(req)
|
||||
data = b""
|
||||
while True:
|
||||
chunk = sock.recv(1024)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
sep = b"\r\n\r\n"
|
||||
if sep not in data:
|
||||
raise OSError("invalid HTTP response")
|
||||
head, body = data.split(sep, 1)
|
||||
status_line = head.split(b"\r\n", 1)[0]
|
||||
if b" 200 " not in status_line:
|
||||
raise OSError("HTTP status not OK: %s" % status_line.decode("utf-8"))
|
||||
return body
|
||||
|
||||
|
||||
def _http_get_json(url, timeout_s=10.0):
|
||||
body = _http_get_raw(url, timeout_s=timeout_s)
|
||||
return json.loads(body.decode("utf-8"))
|
||||
|
||||
|
||||
def _http_get_text(url, timeout_s=10.0, controller_ip=None):
|
||||
# Support relative URLs from controller messages.
|
||||
if isinstance(url, str) and url.startswith("/"):
|
||||
if not controller_ip:
|
||||
raise OSError("controller IP unavailable for relative URL")
|
||||
url = "http://%s%s" % (controller_ip, url)
|
||||
try:
|
||||
body = _http_get_raw(url, timeout_s=timeout_s)
|
||||
return body.decode("utf-8")
|
||||
except Exception:
|
||||
# Fallback for mDNS/unresolvable host: retry against current controller IP.
|
||||
if not controller_ip or not isinstance(url, str) or not url.startswith("http://"):
|
||||
raise
|
||||
_host, _port, path = _parse_http_url(url)
|
||||
fallback = "http://%s:%d%s" % (controller_ip, _port, path)
|
||||
body = _http_get_raw(fallback, timeout_s=timeout_s)
|
||||
return body.decode("utf-8")
|
||||
|
||||
|
||||
def _safe_pattern_filename(name):
|
||||
if not isinstance(name, str):
|
||||
return False
|
||||
if not name.endswith(".py"):
|
||||
return False
|
||||
if "/" in name or "\\" in name or ".." in name:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def apply_patterns_ota(data, presets, controller_ip=None):
|
||||
manifest_payload = data.get("manifest")
|
||||
if not manifest_payload:
|
||||
return
|
||||
try:
|
||||
if isinstance(manifest_payload, dict):
|
||||
manifest = manifest_payload
|
||||
elif isinstance(manifest_payload, str):
|
||||
manifest = _http_get_json(manifest_payload, timeout_s=20.0)
|
||||
else:
|
||||
print("patterns_ota: invalid manifest payload type")
|
||||
return
|
||||
files = manifest.get("files", [])
|
||||
if not isinstance(files, list) or not files:
|
||||
print("patterns_ota: no files in manifest")
|
||||
return
|
||||
try:
|
||||
os.mkdir("patterns")
|
||||
except OSError:
|
||||
pass
|
||||
updated = 0
|
||||
for item in files:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
name = item.get("name")
|
||||
url = item.get("url")
|
||||
inline_code = item.get("code")
|
||||
if not _safe_pattern_filename(name):
|
||||
continue
|
||||
if isinstance(inline_code, str):
|
||||
code = inline_code
|
||||
elif isinstance(url, str):
|
||||
code = _http_get_text(url, timeout_s=20.0, controller_ip=controller_ip)
|
||||
else:
|
||||
continue
|
||||
with open("patterns/" + name, "w") as f:
|
||||
f.write(code)
|
||||
updated += 1
|
||||
if updated > 0:
|
||||
presets.reload_patterns()
|
||||
except Exception as e:
|
||||
print("patterns_ota failed:", e)
|
||||
@@ -1,28 +0,0 @@
|
||||
"""Group membership for GROUP_CMD filtering; persisted in settings.json."""
|
||||
|
||||
_groups = []
|
||||
|
||||
|
||||
def load_from_settings(settings):
|
||||
global _groups
|
||||
g = settings.get("groups") if settings is not None else None
|
||||
if isinstance(g, list):
|
||||
_groups = [str(x) for x in g if str(x).strip()]
|
||||
else:
|
||||
_groups = []
|
||||
|
||||
|
||||
def groups_replace(group_ids, settings=None, *, persist=True):
|
||||
global _groups
|
||||
_groups = [str(g) for g in group_ids]
|
||||
if persist and settings is not None:
|
||||
settings["groups"] = list(_groups)
|
||||
settings.save()
|
||||
|
||||
|
||||
def in_group(group_id):
|
||||
return str(group_id) in _groups
|
||||
|
||||
|
||||
def list_groups():
|
||||
return list(_groups)
|
||||
@@ -1,293 +0,0 @@
|
||||
"""App-file OTA over ESP-NOW (driver side). Imported on the first OTA packet only.
|
||||
|
||||
Inner packets, carried in reliable-link DATA frames (unicast acked, or broadcast):
|
||||
0x07 BEGIN [4C][07][sess u16][size u32][sha256 32B][plen][path]
|
||||
0x08 DATA [4C][08][sess u16][chunk u16] + up to CHUNK bytes at chunk * CHUNK
|
||||
0x09 END [4C][09][sess u16] hash the staged file
|
||||
0x0A COMMIT [4C][0A][sess u16] move every staged file into place, then reset
|
||||
0x0B ABORT [4C][0B][sess u16] delete the staged files
|
||||
0x0C MISSING [4C][0C][sess u16] report which chunks of the current file are missing
|
||||
Reply, sent straight back (not through the link):
|
||||
0x26 STATUS [4C][26][sess u16][op][code] + arg
|
||||
arg: [cnt u16] + missing bitmap for MISSING, else received bytes u32
|
||||
Files are written to <path>.new; a new session discards whatever an older one staged.
|
||||
The committed session is kept in ota_last: the reset can beat a lost reply, and the
|
||||
controller then asks again.
|
||||
"""
|
||||
import struct
|
||||
|
||||
import file_hashes
|
||||
|
||||
WIRE_MAGIC = 0x4C
|
||||
OP_BEGIN = 0x07
|
||||
OP_DATA = 0x08
|
||||
OP_END = 0x09
|
||||
OP_COMMIT = 0x0A
|
||||
OP_ABORT = 0x0B
|
||||
OP_MISSING = 0x0C
|
||||
MSG_STATUS = 0x26
|
||||
|
||||
OK = 0
|
||||
READY = 1
|
||||
SAME = 2
|
||||
BADHASH = 3
|
||||
INCOMPLETE = 4
|
||||
BADPATH = 5
|
||||
IOERR = 6
|
||||
NOSESS = 7
|
||||
TOOBIG = 8
|
||||
|
||||
CHUNK = 944 # 4 link fragments of 238 bytes minus this packet's 8-byte header
|
||||
MAX_SIZE = 65536
|
||||
STAGED_SUFFIX = ".new"
|
||||
LAST_FILE = "ota_last" # session last committed, so a repeated COMMIT after the reset still gets OK
|
||||
|
||||
try:
|
||||
import uos as os
|
||||
except ImportError:
|
||||
import os
|
||||
|
||||
|
||||
def safe_path(path):
|
||||
"""Relative path to a root file, patterns/... or lib/..., never the hash manifest."""
|
||||
if not path or path.startswith("/") or "\\" in path or path == file_hashes.MANIFEST_FILENAME:
|
||||
return False
|
||||
parts = path.split("/")
|
||||
if any(p in ("", ".", "..") for p in parts):
|
||||
return False
|
||||
return len(parts) == 1 or parts[0] in ("patterns", "lib")
|
||||
|
||||
|
||||
def _makedirs(path):
|
||||
parts = path.split("/")[:-1]
|
||||
for i in range(1, len(parts) + 1):
|
||||
try:
|
||||
os.mkdir("/".join(parts[:i]))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _remove(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
class Ota:
|
||||
def __init__(self, send, reset=None):
|
||||
self.send = send # send(mac, frame)
|
||||
self.reset = reset # called after a commit; defaults to machine.reset
|
||||
self.sess = 0
|
||||
self.staged = {} # path -> sha hex of a verified .new file
|
||||
self.cur = None # [path, size, sha hex, file, have bitmap (bytearray), received bytes]
|
||||
try:
|
||||
with open(LAST_FILE) as f:
|
||||
self.committed = int(f.read())
|
||||
except (OSError, ValueError):
|
||||
self.committed = 0
|
||||
|
||||
def handle(self, mac, pkt):
|
||||
if len(pkt) < 4:
|
||||
return
|
||||
op = pkt[1]
|
||||
sess = pkt[2] | (pkt[3] << 8)
|
||||
if sess == 0:
|
||||
return
|
||||
if op == OP_COMMIT and sess == self.committed:
|
||||
self._reply(mac, sess, op, OK, struct.pack("<I", 0))
|
||||
elif op == OP_BEGIN:
|
||||
self._begin(mac, sess, pkt)
|
||||
elif sess != self.sess:
|
||||
if op != OP_DATA: # data for a session we never started: stay quiet, it may be broadcast
|
||||
self._reply(mac, sess, op, NOSESS)
|
||||
elif op == OP_DATA:
|
||||
self._data(pkt)
|
||||
elif op == OP_END:
|
||||
self._end(mac)
|
||||
elif op == OP_COMMIT:
|
||||
self._commit(mac)
|
||||
elif op == OP_ABORT:
|
||||
self._abort()
|
||||
self._reply(mac, sess, op, OK)
|
||||
elif op == OP_MISSING:
|
||||
self._missing(mac)
|
||||
|
||||
def _reply(self, mac, sess, op, code, arg=None):
|
||||
if arg is None:
|
||||
arg = struct.pack("<I", self.cur[5] if self.cur else 0)
|
||||
self.send(mac, struct.pack("<BBHBB", WIRE_MAGIC, MSG_STATUS, sess, op, code) + arg)
|
||||
|
||||
def _close_cur(self, delete):
|
||||
if self.cur is None:
|
||||
return
|
||||
try:
|
||||
self.cur[3].close()
|
||||
except OSError:
|
||||
pass
|
||||
if delete:
|
||||
_remove(self.cur[0] + STAGED_SUFFIX)
|
||||
self.cur = None
|
||||
|
||||
def _abort(self):
|
||||
self._close_cur(True)
|
||||
for path in self.staged:
|
||||
_remove(path + STAGED_SUFFIX)
|
||||
self.staged = {}
|
||||
|
||||
def _begin(self, mac, sess, pkt):
|
||||
if len(pkt) < 43:
|
||||
return
|
||||
size = struct.unpack_from("<I", pkt, 4)[0]
|
||||
sha = "".join("%02x" % b for b in pkt[8:40])
|
||||
plen = pkt[40]
|
||||
path = bytes(pkt[41 : 41 + plen]).decode()
|
||||
if sess != self.sess:
|
||||
self._abort()
|
||||
self.sess = sess
|
||||
if not safe_path(path):
|
||||
self._reply(mac, sess, OP_BEGIN, BADPATH)
|
||||
return
|
||||
if size > MAX_SIZE:
|
||||
self._reply(mac, sess, OP_BEGIN, TOOBIG)
|
||||
return
|
||||
if self.cur is not None:
|
||||
if self.cur[0] == path and self.cur[2] == sha:
|
||||
self._reply(mac, sess, OP_BEGIN, READY) # our earlier reply was lost
|
||||
return
|
||||
self._close_cur(True)
|
||||
if self.staged.get(path) == sha:
|
||||
self._reply(mac, sess, OP_BEGIN, READY)
|
||||
return
|
||||
try:
|
||||
if file_hashes._hash_file(path) == sha:
|
||||
self._reply(mac, sess, OP_BEGIN, SAME)
|
||||
return
|
||||
except OSError:
|
||||
pass # no such file yet
|
||||
try:
|
||||
_makedirs(path)
|
||||
f = open(path + STAGED_SUFFIX, "w+b")
|
||||
except OSError:
|
||||
self._reply(mac, sess, OP_BEGIN, IOERR)
|
||||
return
|
||||
cnt = (size + CHUNK - 1) // CHUNK
|
||||
self.staged.pop(path, None)
|
||||
self.cur = [path, size, sha, f, bytearray((cnt + 7) // 8), 0]
|
||||
self._reply(mac, sess, OP_BEGIN, READY)
|
||||
|
||||
def _data(self, pkt):
|
||||
cur = self.cur
|
||||
if cur is None or len(pkt) < 6:
|
||||
return
|
||||
idx = pkt[4] | (pkt[5] << 8)
|
||||
body = pkt[6:]
|
||||
off = idx * CHUNK
|
||||
have = cur[4]
|
||||
if off >= cur[1] or have[idx >> 3] & (1 << (idx & 7)):
|
||||
return # past the end, or a copy we already wrote
|
||||
if len(body) != min(CHUNK, cur[1] - off):
|
||||
return
|
||||
f = cur[3]
|
||||
try:
|
||||
end = f.seek(0, 2)
|
||||
if end < off:
|
||||
f.write(bytes(off - end)) # a chunk before this one is still missing
|
||||
f.seek(off)
|
||||
f.write(body)
|
||||
except OSError:
|
||||
self._close_cur(True)
|
||||
return
|
||||
have[idx >> 3] |= 1 << (idx & 7)
|
||||
cur[5] += len(body)
|
||||
|
||||
def _missing_bitmap(self):
|
||||
cur = self.cur
|
||||
cnt = (cur[1] + CHUNK - 1) // CHUNK
|
||||
miss = bytearray(len(cur[4]))
|
||||
for i in range(cnt):
|
||||
if not cur[4][i >> 3] & (1 << (i & 7)):
|
||||
miss[i >> 3] |= 1 << (i & 7)
|
||||
return cnt, miss
|
||||
|
||||
def _missing(self, mac):
|
||||
if self.cur is None:
|
||||
self._reply(mac, self.sess, OP_MISSING, OK, struct.pack("<H", 0))
|
||||
return
|
||||
cnt, miss = self._missing_bitmap()
|
||||
self._reply(mac, self.sess, OP_MISSING, OK, struct.pack("<H", cnt) + miss)
|
||||
|
||||
def _end(self, mac):
|
||||
cur = self.cur
|
||||
if cur is None:
|
||||
# already verified: our OK was lost and the controller asks again
|
||||
self._reply(mac, self.sess, OP_END, OK if self.staged else NOSESS)
|
||||
return
|
||||
if cur[5] < cur[1]:
|
||||
self._reply(mac, self.sess, OP_END, INCOMPLETE)
|
||||
return
|
||||
path, sha = cur[0], cur[2]
|
||||
self._close_cur(False)
|
||||
try:
|
||||
ok = file_hashes._hash_file(path + STAGED_SUFFIX) == sha
|
||||
except OSError:
|
||||
ok = False
|
||||
if not ok:
|
||||
_remove(path + STAGED_SUFFIX)
|
||||
self._reply(mac, self.sess, OP_END, BADHASH)
|
||||
return
|
||||
self.staged[path] = sha
|
||||
self._reply(mac, self.sess, OP_END, OK)
|
||||
|
||||
def _commit(self, mac):
|
||||
self._close_cur(True)
|
||||
manifest = file_hashes.load()
|
||||
failed = False
|
||||
for path, sha in self.staged.items():
|
||||
try:
|
||||
try:
|
||||
os.rename(path + STAGED_SUFFIX, path)
|
||||
except OSError:
|
||||
_remove(path)
|
||||
os.rename(path + STAGED_SUFFIX, path)
|
||||
manifest[path] = sha
|
||||
except OSError:
|
||||
failed = True
|
||||
moved = len(self.staged)
|
||||
self.staged = {}
|
||||
try:
|
||||
file_hashes.save(manifest)
|
||||
with open(LAST_FILE, "w") as f:
|
||||
f.write(str(self.sess))
|
||||
except OSError:
|
||||
failed = True
|
||||
self.committed = self.sess
|
||||
self._reply(mac, self.sess, OP_COMMIT, IOERR if failed else OK, struct.pack("<I", moved))
|
||||
print("ota: committed", moved, "files" + (" with errors" if failed else ""))
|
||||
if moved:
|
||||
self._schedule_reset()
|
||||
|
||||
def _schedule_reset(self):
|
||||
if self.reset is not None:
|
||||
self.reset()
|
||||
return
|
||||
import machine
|
||||
|
||||
try:
|
||||
t = machine.Timer(0)
|
||||
t.init(mode=machine.Timer.ONE_SHOT, period=300, callback=lambda _: machine.reset())
|
||||
except Exception:
|
||||
import utime
|
||||
|
||||
utime.sleep_ms(300)
|
||||
machine.reset()
|
||||
|
||||
|
||||
_ota = None
|
||||
|
||||
|
||||
def handle(mac, pkt, send):
|
||||
global _ota
|
||||
if _ota is None:
|
||||
_ota = Ota(send)
|
||||
_ota.handle(bytes(mac), pkt)
|
||||
@@ -1,175 +0,0 @@
|
||||
"""Reliable-link extension of the 0x4C ESP-NOW protocol (driver side).
|
||||
|
||||
Extra message types, all inside the existing wire magic 0x4C:
|
||||
0x20 DATA [4C][20][flags][seq u16][ver u16][idx][cnt] + fragment of an inner packet
|
||||
flags: 1 = ack wanted, 2 = commit (record ver once complete)
|
||||
The inner packet is any normal packet (4C 03 CMD, 4C 04 GROUP_CMD, 4C 02 GROUPS, or JSON).
|
||||
0x21 ACK [4C][21][0][seq u16][cnt][mask u32] driver -> controller
|
||||
0x22 DIGEST [4C][22][ver u16] controller broadcast
|
||||
0x23 RESYNC [4C][23][ver u16] driver -> controller
|
||||
0x24 ECHO [4C][24][beat_idx u16] driver -> controller, bench only
|
||||
0x25 BEAT [4C][25][flags][idx u16][period u16][fire_in] handled by BeatSync
|
||||
0x26 OTA [4C][26][sess u16][op][code] + arg driver -> controller, see espnow_ota.py
|
||||
Everything else (announce, groups, cmd, group cmd, plain JSON) goes straight to the handler.
|
||||
"""
|
||||
import struct
|
||||
|
||||
WIRE_MAGIC = 0x4C
|
||||
MSG_DATA = 0x20
|
||||
MSG_ACK = 0x21
|
||||
MSG_DIGEST = 0x22
|
||||
MSG_RESYNC = 0x23
|
||||
MSG_ECHO = 0x24
|
||||
MSG_BEAT = 0x25
|
||||
LINK_TYPES = (MSG_DATA, MSG_DIGEST)
|
||||
F_ACK = 1
|
||||
F_COMMIT = 2
|
||||
HDR = 9
|
||||
|
||||
INBOX_MAX = 24
|
||||
DONE_MAX = 16
|
||||
ASM_TIMEOUT_MS = 3000
|
||||
RESYNC_MIN_GAP_MS = 3000
|
||||
|
||||
|
||||
def _due(now, t):
|
||||
return (now - t) & 0x7FFFFFFF < 0x40000000
|
||||
|
||||
|
||||
class LinkRx:
|
||||
def __init__(self, handler, beat, send=None, jitter_ms=0, rand=None):
|
||||
self.handler = handler # handler(mac, packet_bytes)
|
||||
self.beat = beat # BeatSync
|
||||
self.send = send # send(mac, frame)
|
||||
self.jitter_ms = jitter_ms # spreads resync requests across drivers
|
||||
self.ver = 0
|
||||
self.master = None
|
||||
self.inbox = []
|
||||
self.asm = {}
|
||||
self.done = []
|
||||
self.resync_at = None
|
||||
self.last_resync = None
|
||||
self.loss_pct = 0 # lossy-link test: drop this percentage of received frames
|
||||
self.loss_beats = True
|
||||
self.rand = rand # rand() -> 0..99; defaults to the random module
|
||||
self.stats = {"msgs": 0, "dups": 0, "acks": 0, "resyncs": 0, "dropped": 0, "sim_lost": 0}
|
||||
|
||||
def on_packet(self, mac, data, now):
|
||||
"""Call for every received frame (irq or main loop). Beats are handled here; the rest is queued."""
|
||||
if not data:
|
||||
return
|
||||
is_beat = len(data) > 1 and data[0] == WIRE_MAGIC and data[1] == MSG_BEAT
|
||||
if self.loss_pct and (self.loss_beats or not is_beat) and self._rand() < self.loss_pct:
|
||||
self.stats["sim_lost"] += 1
|
||||
return
|
||||
if is_beat:
|
||||
self.beat.on_frame(data, now)
|
||||
elif len(self.inbox) < INBOX_MAX:
|
||||
self.inbox.append((bytes(mac), bytes(data)))
|
||||
else:
|
||||
self.stats["dropped"] += 1
|
||||
|
||||
def _rand(self):
|
||||
if self.rand is None:
|
||||
import random
|
||||
|
||||
self.rand = lambda: random.getrandbits(16) % 100
|
||||
return self.rand()
|
||||
|
||||
def echo(self, idx):
|
||||
"""Tell the controller we just fired beat idx (bench measurement only)."""
|
||||
if self.send and self.master:
|
||||
self.send(self.master, struct.pack("<BBH", WIRE_MAGIC, MSG_ECHO, idx))
|
||||
|
||||
def poll(self, now):
|
||||
"""Process queued frames. Call from the main loop."""
|
||||
while self.inbox:
|
||||
mac, data = self.inbox.pop(0)
|
||||
if len(data) > 1 and data[0] == WIRE_MAGIC and data[1] == MSG_DATA:
|
||||
self._data(mac, data, now)
|
||||
elif len(data) > 1 and data[0] == WIRE_MAGIC and data[1] == MSG_DIGEST:
|
||||
self._digest(mac, data, now)
|
||||
else:
|
||||
self.handler(mac, data)
|
||||
if self.resync_at is not None and _due(now, self.resync_at):
|
||||
self.resync_at = None
|
||||
self._send_resync(now)
|
||||
if self.asm:
|
||||
for k in [k for k, e in self.asm.items() if now - e[3] > ASM_TIMEOUT_MS]:
|
||||
del self.asm[k]
|
||||
|
||||
def _ack(self, mac, seq, cnt, mask):
|
||||
if self.send:
|
||||
self.send(mac, struct.pack("<BBBHBI", WIRE_MAGIC, MSG_ACK, 0, seq, cnt, mask))
|
||||
self.stats["acks"] += 1
|
||||
|
||||
def _data(self, mac, data, now):
|
||||
if len(data) <= HDR:
|
||||
return
|
||||
_, _, flags, seq, ver, idx, cnt = struct.unpack("<BBBHHBB", data[:HDR])
|
||||
if cnt == 0 or cnt > 32 or idx >= cnt:
|
||||
return
|
||||
self.master = mac
|
||||
key = (mac, seq)
|
||||
full = (1 << cnt) - 1 if cnt < 32 else 0xFFFFFFFF
|
||||
if key in self.done:
|
||||
self.stats["dups"] += 1
|
||||
if flags & F_ACK:
|
||||
self._ack(mac, seq, cnt, full) # our earlier ack was lost
|
||||
return
|
||||
e = self.asm.get(key)
|
||||
if e is None:
|
||||
e = self.asm[key] = [cnt, 0, [None] * cnt, now, flags, ver]
|
||||
e[1] |= 1 << idx
|
||||
e[2][idx] = data[HDR:]
|
||||
e[3] = now
|
||||
if flags & F_ACK:
|
||||
self._ack(mac, seq, cnt, e[1])
|
||||
if e[1] != full:
|
||||
return
|
||||
del self.asm[key]
|
||||
self.done.append(key)
|
||||
if len(self.done) > DONE_MAX:
|
||||
self.done.pop(0)
|
||||
msg = e[2][0] if cnt == 1 else b"".join(e[2])
|
||||
self.stats["msgs"] += 1
|
||||
self.handler(mac, msg)
|
||||
if flags & F_COMMIT and ver:
|
||||
self.ver = ver
|
||||
self.resync_at = None
|
||||
|
||||
def _digest(self, mac, data, now):
|
||||
if len(data) < 4:
|
||||
return
|
||||
self.master = mac
|
||||
ver = struct.unpack("<H", data[2:4])[0]
|
||||
if ver == 0 or ver == self.ver or self.resync_at is not None:
|
||||
return
|
||||
if self.last_resync is not None and now - self.last_resync < RESYNC_MIN_GAP_MS:
|
||||
return
|
||||
self.resync_at = now + self.jitter_ms
|
||||
|
||||
def _send_resync(self, now):
|
||||
if self.send and self.master:
|
||||
self.last_resync = now
|
||||
self.stats["resyncs"] += 1
|
||||
self.send(self.master, struct.pack("<BBH", WIRE_MAGIC, MSG_RESYNC, self.ver))
|
||||
|
||||
|
||||
def make_sender(esp):
|
||||
"""send(mac, frame) for an espnow.ESPNow instance, adding the peer on first use."""
|
||||
peers = set()
|
||||
|
||||
def send(mac, frame):
|
||||
if mac not in peers:
|
||||
try:
|
||||
esp.add_peer(mac)
|
||||
except OSError:
|
||||
pass
|
||||
peers.add(mac)
|
||||
try:
|
||||
esp.send(mac, frame, False)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return send
|
||||
@@ -1,204 +0,0 @@
|
||||
"""ESP-NOW receive loop and boot announce."""
|
||||
|
||||
import asyncio
|
||||
import urandom
|
||||
import ubinascii
|
||||
|
||||
import espnow
|
||||
import network
|
||||
|
||||
import device_groups as dg
|
||||
from espnow_wire import (
|
||||
BROADCAST_MAC,
|
||||
MSG_ANNOUNCE,
|
||||
MSG_CMD,
|
||||
MSG_GROUP_CMD,
|
||||
MSG_GROUPS,
|
||||
MSG_OTA_FIRST,
|
||||
MSG_OTA_LAST,
|
||||
MSG_PING_REQ,
|
||||
cmd_envelope,
|
||||
pack_announce,
|
||||
pack_ping_rsp,
|
||||
parse_group_cmd,
|
||||
parse_groups,
|
||||
parse_ping_req,
|
||||
wire_msg_type,
|
||||
)
|
||||
|
||||
from controller_messages import process_data
|
||||
from settings import WIFI_CHANNEL_DEFAULT
|
||||
|
||||
_PING_DELAY_MS_MIN = 50
|
||||
_PING_DELAY_MS_MAX = 500
|
||||
|
||||
_esp = None
|
||||
_ota_send = None
|
||||
_groups_received = False
|
||||
_debug = False
|
||||
|
||||
|
||||
def _dlog(*parts):
|
||||
if _debug:
|
||||
print(*parts)
|
||||
|
||||
|
||||
def init_espnow(settings):
|
||||
global _esp, _debug
|
||||
_debug = bool(settings.get("debug", False))
|
||||
try:
|
||||
ch = int(settings.get("wifi_channel", WIFI_CHANNEL_DEFAULT))
|
||||
except (TypeError, ValueError):
|
||||
ch = WIFI_CHANNEL_DEFAULT
|
||||
ch = max(1, min(11, ch))
|
||||
sta = network.WLAN(network.STA_IF)
|
||||
sta.active(True)
|
||||
sta.config(pm=network.WLAN.PM_NONE)
|
||||
try:
|
||||
sta.config(channel=ch)
|
||||
except Exception as e:
|
||||
print("espnow sta channel set failed:", e)
|
||||
_esp = espnow.ESPNow()
|
||||
try:
|
||||
# The default 526 bytes holds two full frames; an OTA chunk is four
|
||||
_esp.config(rxbuf=int(settings.get("espnow_rxbuf", 2048)))
|
||||
except Exception as e:
|
||||
print("espnow rxbuf set failed:", e)
|
||||
_esp.active(True)
|
||||
try:
|
||||
_esp.add_peer(BROADCAST_MAC)
|
||||
_dlog("espnow add bcast ok")
|
||||
except Exception as e:
|
||||
print("espnow add bcast failed:", e)
|
||||
try:
|
||||
actual_ch = sta.config("channel")
|
||||
except Exception:
|
||||
actual_ch = "?"
|
||||
print("espnow init ch", ch, "sta_ch", actual_ch, "debug", _debug)
|
||||
return _esp
|
||||
|
||||
|
||||
def _send_ping_rsp(host, settings, ping_id, delay_ms):
|
||||
import utime
|
||||
|
||||
utime.sleep_ms(delay_ms)
|
||||
if _esp is None or not host or len(host) != 6:
|
||||
return
|
||||
pkt = pack_ping_rsp(ping_id, settings.get("name", "led"))
|
||||
try:
|
||||
try:
|
||||
_esp.add_peer(host)
|
||||
_dlog("espnow ping add_peer ok", ubinascii.hexlify(host).decode())
|
||||
except Exception as e:
|
||||
_dlog("espnow ping add_peer skip", repr(e))
|
||||
_esp.send(host, pkt)
|
||||
print("espnow ping rsp", ping_id, delay_ms, "ms", ubinascii.hexlify(host).decode())
|
||||
except Exception as e:
|
||||
print("espnow ping rsp failed:", e, "host", ubinascii.hexlify(host).decode(), "len", len(pkt))
|
||||
|
||||
|
||||
async def _send_ping_rsp_delayed(host, settings, ping_id):
|
||||
span = _PING_DELAY_MS_MAX - _PING_DELAY_MS_MIN
|
||||
delay_ms = _PING_DELAY_MS_MIN + (urandom.getrandbits(10) % (span + 1))
|
||||
await asyncio.sleep(delay_ms / 1000)
|
||||
_send_ping_rsp(host, settings, ping_id, delay_ms)
|
||||
|
||||
|
||||
def _schedule_ping_rsp(host, settings, ping_id):
|
||||
span = _PING_DELAY_MS_MAX - _PING_DELAY_MS_MIN
|
||||
delay_ms = _PING_DELAY_MS_MIN + (urandom.getrandbits(10) % (span + 1))
|
||||
try:
|
||||
import _thread
|
||||
|
||||
_thread.start_new_thread(_send_ping_rsp, (host, settings, ping_id, delay_ms))
|
||||
except ImportError:
|
||||
asyncio.create_task(_send_ping_rsp_delayed(host, settings, ping_id))
|
||||
|
||||
|
||||
def send_boot_announce(settings):
|
||||
if _esp is None:
|
||||
return
|
||||
pkt = pack_announce(
|
||||
settings.get("name", "led"),
|
||||
settings.get("num_leds", 1),
|
||||
color_order=settings.get("color_order", "rgb"),
|
||||
startup_mode=settings.get("startup_mode", "default"),
|
||||
brightness=settings.get("brightness", 32),
|
||||
)
|
||||
try:
|
||||
_esp.send(BROADCAST_MAC, pkt)
|
||||
print("espnow announce", len(pkt), "B")
|
||||
except Exception as e:
|
||||
print("espnow announce failed:", e)
|
||||
|
||||
|
||||
def _handle_packet(host, pkt, settings, presets):
|
||||
global _groups_received, _ota_send
|
||||
mt = wire_msg_type(pkt)
|
||||
if mt is not None and MSG_OTA_FIRST <= mt <= MSG_OTA_LAST:
|
||||
import espnow_ota
|
||||
|
||||
if _ota_send is None:
|
||||
from espnow_rx import make_sender
|
||||
|
||||
_ota_send = make_sender(_esp)
|
||||
espnow_ota.handle(host, pkt, _ota_send)
|
||||
return
|
||||
if mt == MSG_GROUPS:
|
||||
ids = parse_groups(pkt)
|
||||
if ids is not None:
|
||||
dg.groups_replace(ids, settings)
|
||||
_groups_received = True
|
||||
print("groups", ids)
|
||||
return
|
||||
if mt == MSG_GROUP_CMD:
|
||||
parsed = parse_group_cmd(pkt)
|
||||
if parsed is None:
|
||||
return
|
||||
gid, env = parsed
|
||||
if not dg.in_group(gid):
|
||||
return
|
||||
from espnow_wire import _envelope_size
|
||||
|
||||
need = _envelope_size(env)
|
||||
save = len(env) > need and env[need] == 1
|
||||
body = env[:need] if save else env
|
||||
if body:
|
||||
process_data(body, settings, presets, save=save)
|
||||
return
|
||||
if mt == MSG_CMD:
|
||||
env, save = cmd_envelope(pkt)
|
||||
if env:
|
||||
process_data(env, settings, presets, save=save)
|
||||
return
|
||||
if mt == MSG_PING_REQ:
|
||||
ping_id = parse_ping_req(pkt)
|
||||
if ping_id is not None and host and len(host) == 6:
|
||||
_schedule_ping_rsp(host, settings, ping_id)
|
||||
return
|
||||
if mt == MSG_ANNOUNCE:
|
||||
return
|
||||
|
||||
|
||||
async def espnow_receive_loop(settings, presets, wdt=None):
|
||||
global _groups_received
|
||||
while True:
|
||||
if _esp is None:
|
||||
await asyncio.sleep(0.1)
|
||||
continue
|
||||
host, msg = _esp.recv(0)
|
||||
if not host:
|
||||
if not _groups_received:
|
||||
await asyncio.sleep(5)
|
||||
send_boot_announce(settings)
|
||||
else:
|
||||
await asyncio.sleep(0.02)
|
||||
if wdt:
|
||||
wdt.feed()
|
||||
continue
|
||||
try:
|
||||
_handle_packet(host, msg, settings, presets)
|
||||
except Exception as e:
|
||||
print("espnow rx error:", e)
|
||||
if wdt:
|
||||
wdt.feed()
|
||||
@@ -1,137 +0,0 @@
|
||||
"""ESP-NOW wire format (MicroPython). See docs/espnow-binary-protocol.md in led-controller."""
|
||||
|
||||
import struct
|
||||
|
||||
WIRE_MAGIC = 0x4C
|
||||
MAX_ESPNOW_PAYLOAD = 250
|
||||
|
||||
MSG_ANNOUNCE = 0x01
|
||||
MSG_GROUPS = 0x02
|
||||
MSG_CMD = 0x03
|
||||
MSG_GROUP_CMD = 0x04
|
||||
MSG_PING_REQ = 0x05
|
||||
MSG_PING_RSP = 0x06
|
||||
MSG_OTA_FIRST = 0x07 # 0x07..0x0C app-file OTA, see espnow_ota.py
|
||||
MSG_OTA_LAST = 0x0C
|
||||
|
||||
BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
|
||||
|
||||
COLOR_ORDER_TO_ENUM = {
|
||||
"rgb": 0,
|
||||
"rbg": 1,
|
||||
"grb": 2,
|
||||
"gbr": 3,
|
||||
"brg": 4,
|
||||
"bgr": 5,
|
||||
}
|
||||
STARTUP_MODE_TO_ENUM = {"default": 0, "last": 1, "off": 2}
|
||||
|
||||
|
||||
def _pack_header(msg_type, body):
|
||||
pkt = bytes([WIRE_MAGIC, msg_type]) + body
|
||||
if len(pkt) > MAX_ESPNOW_PAYLOAD:
|
||||
raise ValueError("packet too large")
|
||||
return pkt
|
||||
|
||||
|
||||
def pack_announce(
|
||||
name,
|
||||
num_leds,
|
||||
color_order="rgb",
|
||||
startup_mode="default",
|
||||
brightness=32,
|
||||
device_type=0,
|
||||
):
|
||||
name_b = name.encode("utf-8")
|
||||
co = COLOR_ORDER_TO_ENUM.get(str(color_order).lower(), 0)
|
||||
sm = STARTUP_MODE_TO_ENUM.get(str(startup_mode).lower(), 0)
|
||||
body = (
|
||||
bytes([len(name_b)])
|
||||
+ name_b
|
||||
+ struct.pack("<H", int(num_leds))
|
||||
+ bytes([co & 7, sm & 3, max(0, min(255, int(brightness))), device_type & 255])
|
||||
)
|
||||
return _pack_header(MSG_ANNOUNCE, body)
|
||||
|
||||
|
||||
def parse_groups(payload):
|
||||
if len(payload) >= 2 and payload[0] == WIRE_MAGIC:
|
||||
if payload[1] != MSG_GROUPS:
|
||||
return None
|
||||
body = payload[2:]
|
||||
else:
|
||||
body = payload
|
||||
if not body:
|
||||
return []
|
||||
off = 0
|
||||
count = body[off]
|
||||
off += 1
|
||||
out = []
|
||||
for _ in range(count):
|
||||
gl = body[off]
|
||||
off += 1
|
||||
out.append(body[off : off + gl].decode("utf-8"))
|
||||
off += gl
|
||||
return out
|
||||
|
||||
|
||||
def parse_group_cmd(payload):
|
||||
if len(payload) < 2 or payload[0] != WIRE_MAGIC or payload[1] != MSG_GROUP_CMD:
|
||||
return None
|
||||
body = payload[2:]
|
||||
gl = body[0]
|
||||
gid = body[1 : 1 + gl].decode("utf-8")
|
||||
env = body[1 + gl :]
|
||||
return gid, env
|
||||
|
||||
|
||||
HEADER_LEN = 5
|
||||
|
||||
|
||||
def _envelope_size(env):
|
||||
if len(env) < HEADER_LEN:
|
||||
return len(env)
|
||||
lp, ls, ld = env[2], env[3], env[4]
|
||||
return HEADER_LEN + lp + ls + ld
|
||||
|
||||
|
||||
def cmd_envelope(payload):
|
||||
if len(payload) < 2 or payload[0] != WIRE_MAGIC or payload[1] != MSG_CMD:
|
||||
return None, False
|
||||
env = payload[2:]
|
||||
if not env:
|
||||
return None, False
|
||||
need = _envelope_size(env)
|
||||
if need > len(env):
|
||||
return None, False
|
||||
save = len(env) > need and env[need] == 1
|
||||
return env[:need], save
|
||||
|
||||
|
||||
def pack_ping_req(ping_id):
|
||||
body = struct.pack("<I", int(ping_id) & 0xFFFFFFFF)
|
||||
return _pack_header(MSG_PING_REQ, body)
|
||||
|
||||
|
||||
def parse_ping_req(payload):
|
||||
if len(payload) >= 2 and payload[0] == WIRE_MAGIC:
|
||||
if payload[1] != MSG_PING_REQ:
|
||||
return None
|
||||
body = payload[2:]
|
||||
else:
|
||||
body = payload
|
||||
if len(body) < 4:
|
||||
return None
|
||||
return struct.unpack("<I", body[:4])[0]
|
||||
|
||||
|
||||
def pack_ping_rsp(ping_id, name):
|
||||
name_b = name.encode("utf-8")
|
||||
body = struct.pack("<I", int(ping_id) & 0xFFFFFFFF) + bytes([len(name_b)]) + name_b
|
||||
return _pack_header(MSG_PING_RSP, body)
|
||||
|
||||
|
||||
def wire_msg_type(payload):
|
||||
if len(payload) >= 2 and payload[0] == WIRE_MAGIC:
|
||||
return payload[1]
|
||||
return None
|
||||
@@ -1,102 +0,0 @@
|
||||
"""
|
||||
Deploy hash manifest at flash root (file_hashes.json).
|
||||
|
||||
Updated by led-cli after directory uploads; used to skip unchanged files on
|
||||
the next deploy. Format: {"version": 1, "algorithm": "sha256", "files": {...}}
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
MANIFEST_FILENAME = "file_hashes.json"
|
||||
HASH_ALGO = "sha256"
|
||||
|
||||
_SKIP_NAMES = frozenset({MANIFEST_FILENAME, "__pycache__"})
|
||||
_SKIP_SUFFIXES = (".pyc", ".pyo")
|
||||
|
||||
|
||||
def _normalize_path(path):
|
||||
return path.replace("\\", "/").lstrip("/")
|
||||
|
||||
|
||||
def load():
|
||||
"""Return path -> sha256 hex map, or {} if missing or invalid."""
|
||||
try:
|
||||
with open(MANIFEST_FILENAME, "r") as f:
|
||||
doc = json.load(f)
|
||||
except OSError:
|
||||
return {}
|
||||
if not isinstance(doc, dict):
|
||||
return {}
|
||||
files = doc.get("files")
|
||||
return files if isinstance(files, dict) else {}
|
||||
|
||||
|
||||
def save(files):
|
||||
"""Write manifest (path keys use forward slashes, no leading slash)."""
|
||||
if not isinstance(files, dict):
|
||||
files = {}
|
||||
doc = {
|
||||
"version": MANIFEST_VERSION,
|
||||
"algorithm": HASH_ALGO,
|
||||
"files": files,
|
||||
}
|
||||
with open(MANIFEST_FILENAME, "w") as f:
|
||||
json.dump(doc, f)
|
||||
|
||||
|
||||
def _hash_file(path):
|
||||
import binascii
|
||||
import hashlib
|
||||
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
while True:
|
||||
chunk = f.read(1024)
|
||||
if not chunk:
|
||||
break
|
||||
h.update(chunk)
|
||||
return binascii.hexlify(h.digest()).decode() # MicroPython's sha256 has no hexdigest()
|
||||
|
||||
|
||||
def _walk_dir(base, prefix, out):
|
||||
try:
|
||||
names = os.listdir(base)
|
||||
except OSError:
|
||||
return
|
||||
for name in names:
|
||||
if name in _SKIP_NAMES or name.endswith(_SKIP_SUFFIXES):
|
||||
continue
|
||||
full = base + "/" + name if base else name
|
||||
key = _normalize_path((prefix + "/" + name) if prefix else name)
|
||||
try:
|
||||
mode = os.stat(full)[0]
|
||||
except OSError:
|
||||
continue
|
||||
if mode & 0x4000:
|
||||
_walk_dir(full, key, out)
|
||||
else:
|
||||
out[key] = _hash_file(full)
|
||||
|
||||
|
||||
def rebuild():
|
||||
"""Rebuild manifest from root .py files plus patterns/ and lib/ trees."""
|
||||
files = {}
|
||||
try:
|
||||
for name in os.listdir("."):
|
||||
if name in _SKIP_NAMES or name.endswith(_SKIP_SUFFIXES):
|
||||
continue
|
||||
try:
|
||||
mode = os.stat(name)[0]
|
||||
except OSError:
|
||||
continue
|
||||
if mode & 0x4000:
|
||||
if name in ("patterns", "lib"):
|
||||
_walk_dir(name, name, files)
|
||||
else:
|
||||
files[_normalize_path(name)] = _hash_file(name)
|
||||
except OSError:
|
||||
pass
|
||||
save(files)
|
||||
return files
|
||||
-174
@@ -1,174 +0,0 @@
|
||||
"""LED hello JSON line and UDP broadcast on port 8766.
|
||||
|
||||
Used so led-controller can register the device (name, MAC, IP) when ``wait_reply`` is
|
||||
false; the controller may then connect to the device's WebSocket. With
|
||||
``wait_reply`` true, blocks for an echo and returns the controller IP (legacy discovery).
|
||||
|
||||
Wi-Fi must already be connected; this module does not use Settings or call connect().
|
||||
"""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import ubinascii
|
||||
|
||||
import network
|
||||
|
||||
# Match led-controller/tests/udp_server.py
|
||||
DISCOVERY_UDP_PORT = 8766
|
||||
DEFAULT_RECV_TIMEOUT_S = 3
|
||||
|
||||
|
||||
def pack_hello_dict(sta, device_name=""):
|
||||
"""Same fields as main HTTP/ESP-NOW hello."""
|
||||
mac = sta.config("mac")
|
||||
return {
|
||||
"v": "1",
|
||||
"device_name": device_name,
|
||||
"mac": ubinascii.hexlify(mac).decode().lower(),
|
||||
"type": "led",
|
||||
}
|
||||
|
||||
|
||||
def pack_hello_bytes(sta, device_name=""):
|
||||
return json.dumps(pack_hello_dict(sta, device_name)).encode("utf-8")
|
||||
|
||||
|
||||
def pack_hello_line(sta, device_name=""):
|
||||
"""JSON hello + newline (HTTP/UDP discovery payloads)."""
|
||||
return pack_hello_bytes(sta, device_name) + b"\n"
|
||||
|
||||
|
||||
def ipv4_broadcast(ip, netmask):
|
||||
"""Directed broadcast (e.g. 192.168.1.0/24 -> 192.168.1.255)."""
|
||||
ia = [int(x) for x in ip.split(".")]
|
||||
im = [int(x) for x in netmask.split(".")]
|
||||
if len(ia) != 4 or len(im) != 4:
|
||||
return None
|
||||
# STA often reports 255.255.255.255; "broadcast" would equal the host IP — useless for LAN.
|
||||
if netmask == "255.255.255.255":
|
||||
return None
|
||||
bcast = ".".join(str(ia[i] | (255 - im[i])) for i in range(4))
|
||||
if bcast == ip:
|
||||
return None
|
||||
return bcast
|
||||
|
||||
|
||||
def udp_discovery_targets(ip, mask):
|
||||
"""(directed_broadcast, port) then limited broadcast."""
|
||||
out = [("255.255.255.255", DISCOVERY_UDP_PORT)]
|
||||
b = ipv4_broadcast(ip, mask)
|
||||
if b:
|
||||
out.insert(0, (b, DISCOVERY_UDP_PORT))
|
||||
return out
|
||||
|
||||
|
||||
def _udp_discovery_targets_single(ip, mask):
|
||||
"""One destination: subnet broadcast if known, else limited broadcast."""
|
||||
b = ipv4_broadcast(ip, mask)
|
||||
if b:
|
||||
return [(b, DISCOVERY_UDP_PORT)]
|
||||
return [("255.255.255.255", DISCOVERY_UDP_PORT)]
|
||||
|
||||
|
||||
def broadcast_hello_udp(
|
||||
sta,
|
||||
device_name="",
|
||||
*,
|
||||
wait_reply=True,
|
||||
recv_timeout_s=DEFAULT_RECV_TIMEOUT_S,
|
||||
wdt=None,
|
||||
dual_destinations=True,
|
||||
):
|
||||
"""
|
||||
Send pack_hello_line on DISCOVERY_UDP_PORT.
|
||||
STA must already be connected with a valid IPv4 (caller brings up Wi-Fi).
|
||||
|
||||
If dual_destinations (default), send subnet broadcast then 255.255.255.255 so
|
||||
discovery works on awkward APs — the controller may receive two packets.
|
||||
If dual_destinations is False, send only one (subnet broadcast or limited),
|
||||
e.g. after TCP connect so the Pi does not run duplicate resync handlers.
|
||||
|
||||
If wait_reply, wait for first UDP echo. Returns controller IP string or None.
|
||||
"""
|
||||
ip, mask, _gw, _dns = sta.ifconfig()
|
||||
msg = pack_hello_line(sta, device_name)
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
except (AttributeError, OSError) as e:
|
||||
print("SO_BROADCAST not set:", e)
|
||||
try:
|
||||
sock.bind((ip, 0))
|
||||
except (AttributeError, OSError, TypeError) as e:
|
||||
try:
|
||||
sock.bind(("0.0.0.0", 0))
|
||||
except (AttributeError, OSError) as e2:
|
||||
print("bind skipped:", e, e2)
|
||||
if wait_reply:
|
||||
try:
|
||||
sock.settimeout(recv_timeout_s)
|
||||
except (AttributeError, OSError):
|
||||
pass
|
||||
|
||||
discovered = None
|
||||
targets = (
|
||||
udp_discovery_targets(ip, mask)
|
||||
if dual_destinations
|
||||
else _udp_discovery_targets_single(ip, mask)
|
||||
)
|
||||
for dest_ip, dest_port in targets:
|
||||
if wdt is not None:
|
||||
wdt.feed()
|
||||
target = (dest_ip, dest_port)
|
||||
try:
|
||||
sock.sendto(msg, target)
|
||||
except OSError as e:
|
||||
print("sendto failed:", e)
|
||||
continue
|
||||
if not wait_reply:
|
||||
continue
|
||||
if wdt is not None:
|
||||
wdt.feed()
|
||||
try:
|
||||
_data, addr = sock.recvfrom(2048)
|
||||
remote_ip = addr[0]
|
||||
discovered = remote_ip
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
sock.close()
|
||||
return discovered
|
||||
|
||||
|
||||
def discover_controller_udp(device_name="", wdt=None):
|
||||
"""
|
||||
Broadcast hello; return controller IP from first UDP echo, or None.
|
||||
STA must already be connected.
|
||||
|
||||
device_name: logical name in the JSON (caller supplies, e.g. from Settings elsewhere).
|
||||
wdt: optional WDT to feed during waits.
|
||||
"""
|
||||
sta = network.WLAN(network.STA_IF)
|
||||
if not sta.isconnected():
|
||||
print("hello: STA not connected — connect Wi-Fi before discovery.")
|
||||
raise SystemExit(1)
|
||||
|
||||
ip, mask, _g, _d = sta.ifconfig()
|
||||
if ip == "0.0.0.0":
|
||||
print("hello: STA has no IP address.")
|
||||
raise SystemExit(1)
|
||||
|
||||
discovered = broadcast_hello_udp(
|
||||
sta,
|
||||
device_name,
|
||||
wait_reply=True,
|
||||
wdt=wdt,
|
||||
)
|
||||
return discovered
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not discover_controller_udp():
|
||||
raise SystemExit(1)
|
||||
@@ -1,107 +0,0 @@
|
||||
import json
|
||||
|
||||
from controller_messages import process_data
|
||||
from microdot.websocket import WebSocketError, with_websocket
|
||||
|
||||
try:
|
||||
import uos as os
|
||||
except ImportError:
|
||||
import os
|
||||
|
||||
|
||||
def _safe_pattern_filename(name):
|
||||
if not isinstance(name, str):
|
||||
return False
|
||||
if not name.endswith(".py"):
|
||||
return False
|
||||
if "/" in name or "\\" in name or ".." in name:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def register_routes(app, settings, presets, runtime_state):
|
||||
@app.route("/ws")
|
||||
@with_websocket
|
||||
async def ws_handler(request, ws):
|
||||
runtime_state.ws_connected()
|
||||
controller_ip = None
|
||||
try:
|
||||
client_addr = getattr(request, "client_addr", None)
|
||||
if isinstance(client_addr, (tuple, list)) and client_addr:
|
||||
controller_ip = client_addr[0]
|
||||
elif isinstance(client_addr, str):
|
||||
controller_ip = client_addr
|
||||
except Exception:
|
||||
controller_ip = None
|
||||
try:
|
||||
while True:
|
||||
data = await ws.receive()
|
||||
if not data:
|
||||
break
|
||||
process_data(data, settings, presets, controller_ip=controller_ip)
|
||||
except WebSocketError as e:
|
||||
print("WS client disconnected:", e)
|
||||
except OSError as e:
|
||||
print("WS client dropped (OSError):", e)
|
||||
finally:
|
||||
runtime_state.ws_disconnected()
|
||||
|
||||
@app.post("/patterns/upload")
|
||||
async def upload_pattern(request):
|
||||
"""Receive one pattern file body from led-controller and reload patterns."""
|
||||
raw_name = request.args.get("name")
|
||||
reload_raw = request.args.get("reload", "1")
|
||||
reload_patterns = str(reload_raw).strip().lower() not in ("0", "false", "no", "off")
|
||||
|
||||
if not isinstance(raw_name, str) or not raw_name.strip():
|
||||
return json.dumps({"error": "name is required"}), 400, {"Content-Type": "application/json"}
|
||||
body = request.body
|
||||
if not isinstance(body, (bytes, bytearray)) or not body:
|
||||
return json.dumps({"error": "code is required"}), 400, {"Content-Type": "application/json"}
|
||||
try:
|
||||
code = body.decode("utf-8")
|
||||
except UnicodeError:
|
||||
return json.dumps({"error": "body must be utf-8 text"}), 400, {"Content-Type": "application/json"}
|
||||
if not code.strip():
|
||||
return json.dumps({"error": "code is required"}), 400, {"Content-Type": "application/json"}
|
||||
|
||||
name = raw_name.strip()
|
||||
if not name.endswith(".py"):
|
||||
name += ".py"
|
||||
if not _safe_pattern_filename(name) or name in ("__init__.py", "main.py"):
|
||||
return json.dumps({"error": "invalid pattern filename"}), 400, {"Content-Type": "application/json"}
|
||||
|
||||
try:
|
||||
os.mkdir("patterns")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
path = "patterns/" + name
|
||||
try:
|
||||
with open(path, "w") as f:
|
||||
f.write(code)
|
||||
if reload_patterns:
|
||||
presets.reload_patterns()
|
||||
except OSError as e:
|
||||
print("patterns/upload failed:", e)
|
||||
return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"}
|
||||
|
||||
return json.dumps(
|
||||
{
|
||||
"message": "pattern uploaded",
|
||||
"name": name,
|
||||
"reloaded": reload_patterns,
|
||||
}
|
||||
), 201, {"Content-Type": "application/json"}
|
||||
|
||||
@app.post("/presets/upload")
|
||||
async def upload_presets(request):
|
||||
"""Receive v1 JSON with ``presets`` and apply/save on the driver."""
|
||||
body = request.body
|
||||
if not isinstance(body, (bytes, bytearray)) or not body:
|
||||
return json.dumps({"error": "body is required"}), 400, {"Content-Type": "application/json"}
|
||||
try:
|
||||
process_data(body, settings, presets)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"}
|
||||
return json.dumps({"message": "presets applied"}), 200, {"Content-Type": "application/json"}
|
||||
-128
@@ -1,128 +0,0 @@
|
||||
import print_timestamp # noqa: F401
|
||||
from settings import Settings
|
||||
import machine
|
||||
import asyncio
|
||||
import gc
|
||||
import json
|
||||
import network
|
||||
import espnow
|
||||
import device_groups as dg
|
||||
from board import apply_cpu_freq
|
||||
from presets import Presets
|
||||
from controller_messages import apply_startup_pattern, process_data
|
||||
from espnow_transport import _handle_packet, init_espnow
|
||||
from espnow_wire import BROADCAST_MAC, WIRE_MAGIC
|
||||
import utime
|
||||
from beat_sync import BeatSync
|
||||
from espnow_rx import LinkRx, make_sender
|
||||
|
||||
wdt = machine.WDT(timeout=10000)
|
||||
wdt.feed()
|
||||
|
||||
apply_cpu_freq()
|
||||
|
||||
settings = Settings()
|
||||
dg.load_from_settings(settings)
|
||||
print(settings)
|
||||
gc.collect()
|
||||
|
||||
# Bring Wi-Fi up before the pattern library and the LED driver claim memory: on the ESP32-C3 the radio
|
||||
# tasks otherwise fail to start on about every other cold boot (Wifi Unknown Error 0x0101)
|
||||
esp = init_espnow(settings)
|
||||
|
||||
presets = Presets(settings["led_pin"], settings["num_leds"])
|
||||
presets.load(settings)
|
||||
presets.b = settings.get("brightness", 255)
|
||||
presets.max_b = settings.get("max_brightness", 255)
|
||||
presets.debug = bool(settings.get("debug", False))
|
||||
gc.collect()
|
||||
|
||||
apply_startup_pattern(settings, presets)
|
||||
|
||||
print(network.WLAN(network.STA_IF).config("channel"))
|
||||
|
||||
hello = json.dumps({
|
||||
"v": "1",
|
||||
"name": settings.get("name", "led"),
|
||||
"type": "led",
|
||||
})
|
||||
print(hello)
|
||||
|
||||
esp.send(BROADCAST_MAC, hello)
|
||||
print("espnow hello", len(hello), "B")
|
||||
|
||||
|
||||
def _on_espnow_message(host, msg):
|
||||
if not msg:
|
||||
return
|
||||
if msg[0] == WIRE_MAGIC:
|
||||
_handle_packet(host, msg, settings, presets)
|
||||
return
|
||||
if msg[0:1] == b"{":
|
||||
process_data(msg, settings, presets)
|
||||
|
||||
|
||||
beat_sync = BeatSync()
|
||||
link = LinkRx(
|
||||
_on_espnow_message,
|
||||
beat_sync,
|
||||
make_sender(esp),
|
||||
jitter_ms=int.from_bytes(network.WLAN(network.STA_IF).config("mac")[-2:], "big") % 1000,
|
||||
)
|
||||
link.loss_pct = int(settings.get("espnow_loss", 0))
|
||||
bench = bool(settings.get("bench", False)) # echo each fired beat to the controller, print stats
|
||||
usb_log = bool(settings.get("usb_log", False)) # print "FIRE <idx> <ticks_us>" per real beat for tools/usb_latency.py
|
||||
fire_log = None
|
||||
last_stat = utime.ticks_ms()
|
||||
beat_pin = None
|
||||
if settings.get("beat_pin") is not None:
|
||||
beat_pin = machine.Pin(int(settings["beat_pin"]), machine.Pin.OUT)
|
||||
|
||||
def _drain(e):
|
||||
# Runs scheduled between bytecodes, so frames are taken while presets.tick() is still busy.
|
||||
# irecv reuses its buffers: on_packet handles beats in place and copies everything else.
|
||||
while True:
|
||||
try:
|
||||
host, msg = e.irecv(0)
|
||||
except OSError:
|
||||
return
|
||||
if not host:
|
||||
return
|
||||
if msg:
|
||||
try:
|
||||
link.on_packet(host, msg, utime.ticks_ms())
|
||||
except Exception as ex:
|
||||
print("espnow rx error:", ex)
|
||||
|
||||
|
||||
try:
|
||||
esp.irq(_drain)
|
||||
use_irq = True
|
||||
except AttributeError: # firmware built without ESP-NOW irq support: poll as before
|
||||
use_irq = False
|
||||
|
||||
while True:
|
||||
wdt.feed()
|
||||
if not use_irq:
|
||||
_drain(esp)
|
||||
now = utime.ticks_ms()
|
||||
try:
|
||||
link.poll(now)
|
||||
except Exception as e:
|
||||
print("espnow rx error:", e)
|
||||
if beat_sync.poll(now):
|
||||
fire_us = utime.ticks_us()
|
||||
presets.beat()
|
||||
if beat_pin is not None:
|
||||
beat_pin.value(not beat_pin.value()) # edge for the latency measurement
|
||||
if usb_log and not beat_sync.freerun_fire:
|
||||
fire_log = (beat_sync.last_idx, fire_us) # printed after the LED update so it never delays it
|
||||
if bench and not beat_sync.freerun_fire:
|
||||
link.echo(beat_sync.last_idx) # only real triggers: an invented beat has no send time to compare
|
||||
if bench and utime.ticks_diff(now, last_stat) >= 5000:
|
||||
last_stat = now
|
||||
print("beat", beat_sync.stats, "link", link.stats, "radio", esp.stats()) # radio: tx, tx_resp, tx_fail, rx, rx_dropped
|
||||
presets.tick()
|
||||
if fire_log is not None:
|
||||
print("FIRE", fire_log[0], fire_log[1])
|
||||
fire_log = None
|
||||
@@ -1,34 +0,0 @@
|
||||
"""GC / heap snapshot helpers for debug logging."""
|
||||
|
||||
import gc
|
||||
|
||||
|
||||
def snapshot():
|
||||
"""Return a dict of memory stats after ``gc.collect()``."""
|
||||
gc.collect()
|
||||
out = {
|
||||
"free": gc.mem_free(),
|
||||
"alloc": gc.mem_alloc(),
|
||||
}
|
||||
try:
|
||||
import esp32
|
||||
|
||||
blocks = esp32.idf_heap_info(esp32.HEAP_DATA)
|
||||
if blocks:
|
||||
block = blocks[0]
|
||||
if isinstance(block, dict):
|
||||
if "total_free_bytes" in block:
|
||||
out["idf_free"] = block["total_free_bytes"]
|
||||
largest = block.get("largest_free_block")
|
||||
if largest is None:
|
||||
largest = block.get("largest_free_block_in_bytes")
|
||||
if largest is not None:
|
||||
out["idf_largest"] = largest
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def print_mem(label):
|
||||
"""Print one timestamped memory line (via ``print_timestamp`` when installed)."""
|
||||
print("mem %s:" % label, snapshot())
|
||||
@@ -1,5 +0,0 @@
|
||||
"""Pattern modules are registered only via Presets._load_dynamic_patterns().
|
||||
|
||||
This file is ignored as a pattern (see presets.py). Keep it free of imports so
|
||||
adding a pattern does not require editing this package.
|
||||
"""
|
||||
@@ -1,95 +0,0 @@
|
||||
import math
|
||||
import utime
|
||||
|
||||
from patterns.pattern_modes import style_mode
|
||||
|
||||
_LEGACY = {"northern_wave": 1}
|
||||
|
||||
|
||||
class Aurora:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _run_bands(self, preset, colors):
|
||||
bands = max(1, int(preset.n1) if int(preset.n1) > 0 else 3)
|
||||
shimmer = max(0, min(255, int(preset.n2) if int(preset.n2) > 0 else 40))
|
||||
phase = self.driver.step % 256
|
||||
last = utime.ticks_ms()
|
||||
while True:
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d:
|
||||
for i in range(self.driver.num_leds):
|
||||
idx = (
|
||||
(i * bands) // max(1, self.driver.num_leds) + (phase // 32)
|
||||
) % len(colors)
|
||||
c = self.driver.apply_brightness(colors[idx], preset.b)
|
||||
w = 255 - abs(128 - ((i * 8 + phase) & 255)) * 2
|
||||
w = max(0, min(255, w + shimmer))
|
||||
self.driver.n[self.driver.led_i(preset, i)] = (
|
||||
(c[0] * w) // 255,
|
||||
(c[1] * w) // 255,
|
||||
(c[2] * w) // 255,
|
||||
)
|
||||
self.driver.n.write()
|
||||
phase = (phase + self.driver.signed(preset, 1)) & 255
|
||||
self.driver.step = phase
|
||||
last = utime.ticks_add(last, d)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
|
||||
def _run_northern(self, preset, colors):
|
||||
period = max(4, int(preset.n1) if int(preset.n1) > 0 else 20)
|
||||
contrast = max(1, min(255, int(preset.n2) if int(preset.n2) > 0 else 200))
|
||||
drift = max(1, int(preset.n3) if int(preset.n3) > 0 else 2)
|
||||
phase = 0
|
||||
last = utime.ticks_ms()
|
||||
ncols = len(colors)
|
||||
if ncols < 2:
|
||||
colors = list(colors) + [(120, 180, 255)]
|
||||
ncols = len(colors)
|
||||
twopi = 6.2831853
|
||||
|
||||
def lerp3(a, b, f):
|
||||
return (
|
||||
a[0] + ((b[0] - a[0]) * f) // 255,
|
||||
a[1] + ((b[1] - a[1]) * f) // 255,
|
||||
a[2] + ((b[2] - a[2]) * f) // 255,
|
||||
)
|
||||
|
||||
while True:
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d:
|
||||
bg = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
t = (i * twopi / period) + (phase * twopi / 256.0)
|
||||
w = (math.sin(t) + 1.0) * 0.5
|
||||
u = w * (ncols - 1) * 256.0
|
||||
fi = int(u) >> 8
|
||||
frac = int(u) & 255
|
||||
if fi >= ncols - 1:
|
||||
fi = ncols - 2
|
||||
frac = 255
|
||||
peak = lerp3(colors[fi], colors[fi + 1], frac)
|
||||
peak = self.driver.apply_brightness(peak, preset.b)
|
||||
mixf = min(255, int(w * contrast * 2) >> 1)
|
||||
self.driver.n[self.driver.led_i(preset, i)] = lerp3(bg, peak, mixf)
|
||||
self.driver.n.write()
|
||||
phase = (phase + self.driver.signed(preset, drift)) % 256
|
||||
last = utime.ticks_add(last, d)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
|
||||
def run(self, preset):
|
||||
"""Aurora bands (n6=0) or sine northern wave (n6=1, legacy northern_wave)."""
|
||||
colors = preset.c if preset.c else [(40, 200, 140), (80, 120, 255), (160, 80, 220)]
|
||||
if style_mode(preset, 0, _LEGACY) == 1:
|
||||
colors = preset.c if preset.c else [(20, 55, 120), (60, 140, 220), (180, 220, 255)]
|
||||
yield from self._run_northern(preset, colors)
|
||||
return
|
||||
yield from self._run_bands(preset, colors)
|
||||
@@ -1,29 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class BarGraph:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(0, 255, 0), (255, 80, 0)]
|
||||
last_update = utime.ticks_ms()
|
||||
while True:
|
||||
delay_ms = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_update) >= delay_ms:
|
||||
level = max(0, min(100, int(preset.n1) if int(preset.n1) >= 0 else 50))
|
||||
target = (self.driver.num_leds * level) // 100
|
||||
lit = self.driver.apply_brightness(colors[0], preset.b)
|
||||
unlit = self.driver.apply_brightness(
|
||||
preset.background_or(colors),
|
||||
preset.b,
|
||||
)
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = lit if i < target else unlit
|
||||
self.driver.n.write()
|
||||
last_update = utime.ticks_add(last_update, delay_ms)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,34 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class Blink:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
"""Blink pattern: toggles LEDs on/off using preset delay, cycling through colors."""
|
||||
# Use provided colors, or default to white if none
|
||||
colors = preset.c if preset.c else [(255, 255, 255)]
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
color_index = 0
|
||||
state = True # True = on, False = off
|
||||
last_update = utime.ticks_ms()
|
||||
|
||||
while True:
|
||||
current_time = utime.ticks_ms()
|
||||
# Re-read delay each loop so live updates to preset.d take effect
|
||||
delay_ms = max(1, int(preset.d))
|
||||
if utime.ticks_diff(current_time, last_update) >= delay_ms:
|
||||
if state:
|
||||
base_color = colors[color_index % len(colors)]
|
||||
color = self.driver.apply_brightness(base_color, preset.b)
|
||||
self.driver.fill(color)
|
||||
# Advance to next color for the next "on" phase
|
||||
color_index += 1
|
||||
else:
|
||||
# Inactive phase uses the preset background color.
|
||||
self.driver.fill(bg_color)
|
||||
state = not state
|
||||
last_update = utime.ticks_add(last_update, delay_ms)
|
||||
# Yield once per tick so other logic can run
|
||||
yield
|
||||
@@ -1,67 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
|
||||
class Blizzard:
|
||||
"""Dense falling flakes with sideways drift (compare `snowfall` for gentler flakes)."""
|
||||
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(255, 255, 255), (200, 230, 255), (180, 210, 255)]
|
||||
# Higher n1 → more spawns (0–255 threshold vs random)
|
||||
density = max(1, int(preset.n1) if int(preset.n1) > 0 else 90)
|
||||
speed = max(1, int(preset.n2) if int(preset.n2) > 0 else 2)
|
||||
# n3: 128 = no bias; <128 drift one way, >128 the other (scaled to small steps)
|
||||
wraw = int(preset.n3)
|
||||
if wraw <= 0:
|
||||
wind = 0
|
||||
else:
|
||||
wind = max(-4, min(4, (wraw - 128) // 20))
|
||||
|
||||
flakes = []
|
||||
last = utime.ticks_ms()
|
||||
|
||||
while True:
|
||||
d_ms = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d_ms:
|
||||
nled = self.driver.num_leds
|
||||
bg = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
|
||||
for i in range(nled):
|
||||
self.driver.n[i] = bg
|
||||
|
||||
if random.randint(0, 255) < density:
|
||||
flakes.append(
|
||||
[
|
||||
nled - 1,
|
||||
random.randint(0, len(colors) - 1),
|
||||
0 if wind == 0 else random.randint(-1, 1),
|
||||
]
|
||||
)
|
||||
|
||||
nf = []
|
||||
for pos, ci, wj in flakes:
|
||||
p = pos
|
||||
lateral = wind + (wj if wj else 0)
|
||||
p -= self.driver.signed(preset, speed)
|
||||
p += self.driver.signed(preset, lateral)
|
||||
if p < -2 or p >= nled + 2:
|
||||
continue
|
||||
pi = max(0, min(nled - 1, int(p)))
|
||||
self.driver.n[self.driver.led_i(preset, pi)] = self.driver.apply_brightness(
|
||||
colors[ci], preset.b
|
||||
)
|
||||
nf.append([p, ci, wj])
|
||||
flakes = nf
|
||||
|
||||
self.driver.n.write()
|
||||
last = utime.ticks_add(last, d_ms)
|
||||
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
|
||||
yield
|
||||
@@ -1,56 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
|
||||
class CandleGlow:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(255, 140, 40), (255, 200, 120), (255, 90, 20)]
|
||||
n_candles = max(1, min(self.driver.num_leds, int(preset.n1) if int(preset.n1) > 0 else 4))
|
||||
width = max(1, int(preset.n2) if int(preset.n2) > 0 else 3)
|
||||
flicker = max(1, min(255, int(preset.n3) if int(preset.n3) > 0 else 90))
|
||||
n_led = self.driver.num_leds
|
||||
centers = tuple(random.randint(0, max(0, n_led - 1)) for _ in range(n_candles))
|
||||
last = utime.ticks_ms()
|
||||
|
||||
while True:
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d:
|
||||
bg = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(n_led):
|
||||
self.driver.n[i] = bg
|
||||
base_lo = 180 - flicker // 2
|
||||
if base_lo < 40:
|
||||
base_lo = 40
|
||||
for ci, c in enumerate(centers):
|
||||
warmth = colors[ci % len(colors)]
|
||||
pulse = base_lo + random.randint(0, flicker)
|
||||
if pulse > 255:
|
||||
pulse = 255
|
||||
for off in range(-width, width + 1):
|
||||
idx = c + off
|
||||
if 0 <= idx < n_led:
|
||||
dist = abs(off)
|
||||
fall = ((width - dist + 1) * 256) // (width + 1)
|
||||
fac = (fall * pulse) // 256
|
||||
px = (
|
||||
(warmth[0] * fac) // 255,
|
||||
(warmth[1] * fac) // 255,
|
||||
(warmth[2] * fac) // 255,
|
||||
)
|
||||
lit = self.driver.apply_brightness(px, preset.b)
|
||||
o = self.driver.n[idx]
|
||||
self.driver.n[idx] = (
|
||||
max(o[0], lit[0]),
|
||||
max(o[1], lit[1]),
|
||||
max(o[2], lit[2]),
|
||||
)
|
||||
self.driver.n.write()
|
||||
last = utime.ticks_add(last, d)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,164 +0,0 @@
|
||||
import utime
|
||||
|
||||
from patterns.pattern_modes import style_mode
|
||||
|
||||
_LEGACY = {"marquee": 1}
|
||||
|
||||
|
||||
class Chase:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _run_marquee(self, preset, colors):
|
||||
on_len = max(1, int(preset.n1) if int(preset.n1) > 0 else 3)
|
||||
off_len = max(1, int(preset.n2) if int(preset.n2) > 0 else 2)
|
||||
step = max(1, abs(self.driver.signed(preset, int(preset.n3) if int(preset.n3) > 0 else 1)))
|
||||
phase = self.driver.step % (on_len + off_len)
|
||||
last = utime.ticks_ms()
|
||||
while True:
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d:
|
||||
c = self.driver.apply_brightness(colors[0], preset.b)
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
m = (i + phase) % (on_len + off_len)
|
||||
self.driver.n[self.driver.led_i(preset, i)] = c if m < on_len else bg_color
|
||||
self.driver.n.write()
|
||||
phase = (phase + self.driver.signed(preset, step)) % (on_len + off_len)
|
||||
self.driver.step = phase
|
||||
last = utime.ticks_add(last, d)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
|
||||
def run(self, preset):
|
||||
"""Chase (n6=0) or marquee dashes (n6=1, legacy marquee).
|
||||
|
||||
Chase: n1/n2 segment lengths, n3/n4 step on even/odd beats.
|
||||
Marquee: n1 on length, n2 off length, n3 scroll step.
|
||||
"""
|
||||
if style_mode(preset, 0, _LEGACY) == 1:
|
||||
colors = preset.c if preset.c else [(255, 255, 255)]
|
||||
yield from self._run_marquee(preset, colors)
|
||||
return
|
||||
|
||||
colors = preset.c
|
||||
if len(colors) < 1:
|
||||
# Need at least 1 color
|
||||
return
|
||||
|
||||
# Access colors, delay, and n values from preset
|
||||
if not colors:
|
||||
return
|
||||
# If only one color provided, use it for both colors
|
||||
if len(colors) < 2:
|
||||
color0 = colors[0]
|
||||
color1 = colors[0]
|
||||
else:
|
||||
color0 = colors[0]
|
||||
color1 = colors[1]
|
||||
|
||||
color0 = self.driver.apply_brightness(color0, preset.b)
|
||||
color1 = self.driver.apply_brightness(color1, preset.b)
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
|
||||
n1 = max(1, int(preset.n1)) # LEDs of color 0
|
||||
n2 = max(1, int(preset.n2)) # LEDs of color 1
|
||||
n3 = self.driver.signed(preset, int(preset.n3)) # Step movement on even steps
|
||||
n4 = self.driver.signed(preset, int(preset.n4)) # Step movement on odd steps
|
||||
|
||||
segment_length = n1 + n2
|
||||
|
||||
# Calculate position from step_count
|
||||
step_count = int(self.driver.step) % 2
|
||||
# Position alternates: step 0 adds n3, step 1 adds n4, step 2 adds n3, etc.
|
||||
if step_count % 2 == 0:
|
||||
# Even steps: (step_count//2) pairs of (n3+n4) plus one extra n3
|
||||
position = (step_count // 2) * (n3 + n4) + n3
|
||||
else:
|
||||
# Odd steps: ((step_count+1)//2) pairs of (n3+n4)
|
||||
position = ((step_count + 1) // 2) * (n3 + n4)
|
||||
|
||||
# Wrap position to keep it reasonable
|
||||
max_pos = self.driver.num_leds + segment_length
|
||||
position = position % max_pos
|
||||
if position < 0:
|
||||
position += max_pos
|
||||
|
||||
# If auto is False, run a single step and then stop
|
||||
if not preset.a:
|
||||
# Clear all LEDs
|
||||
self.driver.n.fill(bg_color)
|
||||
|
||||
# Draw repeating pattern starting at position
|
||||
for i in range(self.driver.num_leds):
|
||||
# Calculate position in the repeating segment
|
||||
relative_pos = (i - position) % segment_length
|
||||
if relative_pos < 0:
|
||||
relative_pos = (relative_pos + segment_length) % segment_length
|
||||
|
||||
# Determine which color based on position in segment
|
||||
if relative_pos < n1:
|
||||
self.driver.n[self.driver.led_i(preset, i)] = color0
|
||||
else:
|
||||
self.driver.n[self.driver.led_i(preset, i)] = color1
|
||||
|
||||
self.driver.n.write()
|
||||
print("[chase] step", step_count)
|
||||
|
||||
# Increment step for next beat
|
||||
self.driver.step = (step_count + 1) % 2
|
||||
|
||||
# Allow tick() to advance the generator once
|
||||
yield
|
||||
return
|
||||
|
||||
# Auto mode: continuous loop
|
||||
# Use transition_duration for timing and force the first update to happen immediately
|
||||
transition_duration = max(10, int(preset.d))
|
||||
last_update = utime.ticks_ms() - transition_duration
|
||||
|
||||
while True:
|
||||
current_time = utime.ticks_ms()
|
||||
if utime.ticks_diff(current_time, last_update) >= transition_duration:
|
||||
# Calculate current position from step_count
|
||||
if step_count % 2 == 0:
|
||||
position = (step_count // 2) * (n3 + n4) + n3
|
||||
else:
|
||||
position = ((step_count + 1) // 2) * (n3 + n4)
|
||||
|
||||
# Wrap position
|
||||
max_pos = self.driver.num_leds + segment_length
|
||||
position = position % max_pos
|
||||
if position < 0:
|
||||
position += max_pos
|
||||
|
||||
# Clear all LEDs
|
||||
self.driver.n.fill(bg_color)
|
||||
|
||||
# Draw repeating pattern starting at position
|
||||
for i in range(self.driver.num_leds):
|
||||
# Calculate position in the repeating segment
|
||||
relative_pos = (i - position) % segment_length
|
||||
if relative_pos < 0:
|
||||
relative_pos = (relative_pos + segment_length) % segment_length
|
||||
|
||||
# Determine which color based on position in segment
|
||||
if relative_pos < n1:
|
||||
self.driver.n[self.driver.led_i(preset, i)] = color0
|
||||
else:
|
||||
self.driver.n[self.driver.led_i(preset, i)] = color1
|
||||
|
||||
self.driver.n.write()
|
||||
print("[chase] step", step_count)
|
||||
|
||||
# Increment step
|
||||
step_count = (step_count + 1) % 2
|
||||
self.driver.step = step_count
|
||||
last_update = utime.ticks_add(last_update, transition_duration)
|
||||
transition_duration = max(10, int(preset.d))
|
||||
|
||||
# Yield once per tick so other logic can run
|
||||
yield
|
||||
@@ -1,100 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class Circle:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
"""Circle loading pattern - grows to n2, then tail moves forward at n3 until min length n4"""
|
||||
head = 0
|
||||
tail = 0
|
||||
|
||||
# Calculate timing from preset
|
||||
head_rate = max(1, int(preset.n1)) # n1 = head moves per second
|
||||
tail_rate = max(1, int(preset.n3)) # n3 = tail moves per second
|
||||
max_length = max(1, int(preset.n2)) # n2 = max length
|
||||
min_length = max(0, int(preset.n4)) # n4 = min length
|
||||
|
||||
head_delay = 1000 // head_rate # ms between head movements
|
||||
tail_delay = 1000 // tail_rate # ms between tail movements
|
||||
|
||||
last_head_move = utime.ticks_ms()
|
||||
last_tail_move = utime.ticks_ms()
|
||||
|
||||
phase = "growing" # "growing", "shrinking", or "off"
|
||||
|
||||
# Support up to two colors (like chase). If only one color is provided,
|
||||
# use black for the second; if none, default to white.
|
||||
colors = preset.c
|
||||
if not colors:
|
||||
base0 = base1 = (255, 255, 255)
|
||||
elif len(colors) == 1:
|
||||
base0 = colors[0]
|
||||
base1 = preset.background_or(colors)
|
||||
else:
|
||||
base0 = colors[0]
|
||||
base1 = preset.background_or(colors)
|
||||
|
||||
color0 = self.driver.apply_brightness(base0, preset.b)
|
||||
color1 = self.driver.apply_brightness(base1, preset.b)
|
||||
|
||||
while True:
|
||||
current_time = utime.ticks_ms()
|
||||
|
||||
# Background: use second color during the "off" phase, otherwise clear to black
|
||||
if phase == "off":
|
||||
self.driver.n.fill(color1)
|
||||
else:
|
||||
self.driver.n.fill(color1)
|
||||
|
||||
# Calculate segment length
|
||||
segment_length = (head - tail) % self.driver.num_leds
|
||||
if segment_length == 0 and head != tail:
|
||||
segment_length = self.driver.num_leds
|
||||
|
||||
# Draw segment from tail to head as a solid color (no per-LED alternation)
|
||||
current_color = color0
|
||||
for i in range(segment_length + 1):
|
||||
led_pos = (tail + i) % self.driver.num_leds
|
||||
self.driver.n[led_pos] = current_color
|
||||
|
||||
# Move head continuously at n1 LEDs per second
|
||||
if utime.ticks_diff(current_time, last_head_move) >= head_delay:
|
||||
head = (head + 1) % self.driver.num_leds
|
||||
last_head_move = utime.ticks_add(last_head_move, head_delay)
|
||||
head_rate = max(1, int(preset.n1))
|
||||
head_delay = 1000 // head_rate
|
||||
|
||||
# Tail behavior based on phase
|
||||
if phase == "growing":
|
||||
# Growing phase: tail stays at 0 until max length reached
|
||||
if segment_length >= max_length:
|
||||
phase = "shrinking"
|
||||
elif phase == "shrinking":
|
||||
# Shrinking phase: move tail forward at n3 LEDs per second
|
||||
if utime.ticks_diff(current_time, last_tail_move) >= tail_delay:
|
||||
tail = (tail + 1) % self.driver.num_leds
|
||||
last_tail_move = utime.ticks_add(last_tail_move, tail_delay)
|
||||
tail_rate = max(1, int(preset.n3))
|
||||
tail_delay = 1000 // tail_rate
|
||||
|
||||
# Check if we've reached min length
|
||||
current_length = (head - tail) % self.driver.num_leds
|
||||
if current_length == 0 and head != tail:
|
||||
current_length = self.driver.num_leds
|
||||
|
||||
# For min_length = 0, we need at least 1 LED (the head)
|
||||
if min_length == 0 and current_length <= 1:
|
||||
phase = "off" # All LEDs off for 1 step
|
||||
elif min_length > 0 and current_length <= min_length:
|
||||
phase = "growing" # Cycle repeats
|
||||
else: # phase == "off"
|
||||
# Off phase: second color fills the ring for 1 step, then restart
|
||||
tail = head # Reset tail to head position to start fresh
|
||||
phase = "growing"
|
||||
|
||||
self.driver.n.write()
|
||||
|
||||
# Yield once per tick so other logic can run
|
||||
yield
|
||||
@@ -1,33 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class ClockSweep:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(255, 255, 255), (60, 60, 60)]
|
||||
width = max(1, int(preset.n1) if int(preset.n1) > 0 else 1)
|
||||
marker = max(0, int(preset.n2) if int(preset.n2) > 0 else 0)
|
||||
pos = self.driver.step % max(1, self.driver.num_leds)
|
||||
last = utime.ticks_ms()
|
||||
while True:
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d:
|
||||
bg = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
fg = self.driver.apply_brightness(colors[0], preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = bg
|
||||
if marker > 0 and i % marker == 0:
|
||||
self.driver.n[i] = ((bg[0]*2)//3, (bg[1]*2)//3, (bg[2]*2)//3)
|
||||
for w in range(width):
|
||||
self.driver.n[(pos + w) % self.driver.num_leds] = fg
|
||||
self.driver.n.write()
|
||||
pos = (pos + 1) % max(1, self.driver.num_leds)
|
||||
self.driver.step = pos
|
||||
last = utime.ticks_add(last, d)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,100 +0,0 @@
|
||||
import utime
|
||||
|
||||
from patterns.pattern_modes import style_mode
|
||||
|
||||
_LEGACY = {"rainbow": 1, "gradient_scroll": 0}
|
||||
|
||||
|
||||
class ColourCycle:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _wheel(self, pos):
|
||||
if pos < 85:
|
||||
return (pos * 3, 255 - pos * 3, 0)
|
||||
if pos < 170:
|
||||
pos -= 85
|
||||
return (255 - pos * 3, 0, pos * 3)
|
||||
pos -= 170
|
||||
return (0, pos * 3, 255 - pos * 3)
|
||||
|
||||
def _render_gradient(self, preset, colors, phase, brightness):
|
||||
num_leds = self.driver.num_leds
|
||||
color_count = len(colors)
|
||||
if num_leds <= 0 or color_count <= 0:
|
||||
return
|
||||
if color_count == 1:
|
||||
self.driver.fill(self.driver.apply_brightness(colors[0], brightness))
|
||||
return
|
||||
|
||||
full_span = color_count * 256
|
||||
phase_shift = (phase * full_span) // 256
|
||||
for i in range(num_leds):
|
||||
pos = ((i * full_span) // num_leds + phase_shift) % full_span
|
||||
idx = pos // 256
|
||||
frac = pos & 255
|
||||
c1 = colors[idx]
|
||||
c2 = colors[(idx + 1) % color_count]
|
||||
blended = (
|
||||
c1[0] + ((c2[0] - c1[0]) * frac) // 256,
|
||||
c1[1] + ((c2[1] - c1[1]) * frac) // 256,
|
||||
c1[2] + ((c2[2] - c1[2]) * frac) // 256,
|
||||
)
|
||||
self.driver.n[self.driver.led_i(preset, i)] = self.driver.apply_brightness(
|
||||
blended, brightness
|
||||
)
|
||||
self.driver.n.write()
|
||||
|
||||
def _render_rainbow(self, preset, phase, brightness):
|
||||
num_leds = self.driver.num_leds
|
||||
for i in range(num_leds):
|
||||
rc_index = (i * 256 // max(1, num_leds)) + phase
|
||||
self.driver.n[self.driver.led_i(preset, i)] = self.driver.apply_brightness(
|
||||
self._wheel(rc_index & 255), brightness
|
||||
)
|
||||
self.driver.n.write()
|
||||
|
||||
def run(self, preset):
|
||||
"""Scroll gradient (n6=0) or fixed spectrum wheel (n6=1, legacy rainbow).
|
||||
|
||||
n1: step rate
|
||||
n6: 0 gradient scroll, 1 rainbow wheel
|
||||
"""
|
||||
mode = style_mode(preset, 0, _LEGACY)
|
||||
step_amount = max(1, int(preset.n1) if int(preset.n1) > 0 else 1)
|
||||
phase = self.driver.step % 256
|
||||
|
||||
if mode == 1:
|
||||
if not preset.a:
|
||||
self._render_rainbow(preset, phase, preset.b)
|
||||
self.driver.step = (phase + self.driver.signed(preset, step_amount)) % 256
|
||||
yield
|
||||
return
|
||||
last_update = utime.ticks_ms()
|
||||
while True:
|
||||
delay_ms = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_update) >= delay_ms:
|
||||
self._render_rainbow(preset, phase, preset.b)
|
||||
phase = (phase + self.driver.signed(preset, step_amount)) % 256
|
||||
self.driver.step = phase
|
||||
last_update = utime.ticks_add(last_update, delay_ms)
|
||||
yield
|
||||
|
||||
colors = preset.c if preset.c else [(255, 0, 0), (0, 0, 255)]
|
||||
if not preset.a:
|
||||
self._render_gradient(preset, colors, phase, preset.b)
|
||||
self.driver.step = (phase + self.driver.signed(preset, step_amount)) % 256
|
||||
yield
|
||||
return
|
||||
|
||||
last_update = utime.ticks_ms()
|
||||
while True:
|
||||
delay_ms = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_update) >= delay_ms:
|
||||
self._render_gradient(preset, colors, phase, preset.b)
|
||||
phase = (phase + self.driver.signed(preset, step_amount)) % 256
|
||||
self.driver.step = phase
|
||||
last_update = utime.ticks_add(last_update, delay_ms)
|
||||
yield
|
||||
@@ -1,210 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
# Default warm palette: ember → orange → yellow → pale hot (RGB)
|
||||
_DEFAULT_PALETTE = (
|
||||
(90, 8, 8),
|
||||
(200, 40, 12),
|
||||
(255, 120, 30),
|
||||
(255, 220, 140),
|
||||
)
|
||||
|
||||
|
||||
def _clamp(x, lo, hi):
|
||||
if x < lo:
|
||||
return lo
|
||||
if x > hi:
|
||||
return hi
|
||||
return x
|
||||
|
||||
|
||||
def _lerp_chan(a, b, t):
|
||||
return a + ((b - a) * t >> 8)
|
||||
|
||||
|
||||
def _lerp_rgb(c0, c1, t):
|
||||
return (
|
||||
_lerp_chan(c0[0], c1[0], t),
|
||||
_lerp_chan(c0[1], c1[1], t),
|
||||
_lerp_chan(c0[2], c1[2], t),
|
||||
)
|
||||
|
||||
|
||||
def _palette_sample(palette, pos256):
|
||||
n = len(palette)
|
||||
if n == 0:
|
||||
return (255, 160, 60)
|
||||
if n == 1:
|
||||
return palette[0]
|
||||
span = (n - 1) * pos256
|
||||
seg = span >> 8
|
||||
if seg >= n - 1:
|
||||
return palette[n - 1]
|
||||
frac = span & 0xFF
|
||||
return _lerp_rgb(palette[seg], palette[seg + 1], frac)
|
||||
|
||||
|
||||
def _triangle_255(elapsed_ms, period_ms):
|
||||
period_ms = max(period_ms, 400)
|
||||
p = elapsed_ms % period_ms
|
||||
half = period_ms >> 1
|
||||
if half <= 0:
|
||||
return 128
|
||||
if p < half:
|
||||
return (p * 255) // half
|
||||
return ((period_ms - p) * 255) // (period_ms - half)
|
||||
|
||||
|
||||
class Flame:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _build_palette(self, preset):
|
||||
colors = preset.c
|
||||
if not colors:
|
||||
return list(_DEFAULT_PALETTE)
|
||||
out = []
|
||||
for c in colors:
|
||||
if isinstance(c, (list, tuple)) and len(c) == 3:
|
||||
out.append(
|
||||
(
|
||||
_clamp(int(c[0]), 0, 255),
|
||||
_clamp(int(c[1]), 0, 255),
|
||||
_clamp(int(c[2]), 0, 255),
|
||||
)
|
||||
)
|
||||
return out if out else list(_DEFAULT_PALETTE)
|
||||
|
||||
def _draw_frame(self, preset, palette, ticks_now, breath_el_ms, rise, cluster_jit, breath_ms, lo, hi, spark_state):
|
||||
"""spark_state: (active: bool, start_ticks, duration_ms). ticks_now for sparks; breath_el_ms for slow wave."""
|
||||
num = self.driver.num_leds
|
||||
denom = num - 1 if num > 1 else 1
|
||||
|
||||
breathe = _triangle_255(breath_el_ms, breath_ms)
|
||||
base_level = lo + (((hi - lo) * breathe) >> 8)
|
||||
micro = 232 + random.randint(0, 35)
|
||||
level = (base_level * micro) >> 8
|
||||
level = _clamp(level, lo, hi)
|
||||
|
||||
spark_boost = 0
|
||||
spark_white = (0, 0, 0)
|
||||
active, s0, dur = spark_state
|
||||
if active and dur > 0:
|
||||
el = utime.ticks_diff(ticks_now, s0)
|
||||
if el < 0:
|
||||
el = 0
|
||||
if el >= dur:
|
||||
spark_boost = 0
|
||||
else:
|
||||
env = 255 - ((el * 255) // dur)
|
||||
spark_boost = (env * 90) >> 8
|
||||
spark_white = ((env * 55) >> 8, (env * 50) >> 8, (env * 40) >> 8)
|
||||
|
||||
for i in range(num):
|
||||
h = (i * 256) // denom
|
||||
flow = (h + rise + ((i // max(1, num >> 3)) * 17)) & 255
|
||||
pos = (flow + cluster_jit[(i >> 2) & 7]) & 255
|
||||
rgb = _palette_sample(palette, pos)
|
||||
if spark_boost:
|
||||
rgb = (
|
||||
_clamp(rgb[0] + spark_white[0] + (spark_boost * 3 >> 2), 0, 255),
|
||||
_clamp(rgb[1] + spark_white[1] + (spark_boost >> 1), 0, 255),
|
||||
_clamp(rgb[2] + spark_white[2] + (spark_boost >> 2), 0, 255),
|
||||
)
|
||||
self.driver.n[i] = self.driver.apply_brightness(rgb, level)
|
||||
|
||||
self.driver.n.write()
|
||||
|
||||
def run(self, preset):
|
||||
"""Salt-lamp / hearth-style flame: warm gradient, breathing, jitter, drift, rare sparks."""
|
||||
palette = self._build_palette(preset)
|
||||
lo = max(0, min(255, int(preset.n1)))
|
||||
hi = max(0, min(255, int(preset.b)))
|
||||
if lo > hi:
|
||||
lo, hi = hi, lo
|
||||
|
||||
bp = int(preset.n2)
|
||||
breath_ms = max(800, bp if bp > 0 else 2500)
|
||||
|
||||
gap_lo = int(preset.n3)
|
||||
gap_hi = int(preset.n4)
|
||||
# n3 < 0 disables sparks; n3=n4=0 uses ~10–30 s gaps (hearth pops).
|
||||
if gap_lo < 0:
|
||||
sparks_on = False
|
||||
else:
|
||||
sparks_on = True
|
||||
if gap_lo == 0 and gap_hi == 0:
|
||||
gap_lo, gap_hi = 10000, 30000
|
||||
else:
|
||||
gap_lo = max(gap_lo, 500)
|
||||
if gap_hi < gap_lo:
|
||||
gap_hi = gap_lo
|
||||
|
||||
delay_ms = max(16, int(preset.d))
|
||||
rise = random.randint(0, 255)
|
||||
cluster_jit = [random.randint(-18, 18) for _ in range(8)]
|
||||
last_draw = utime.ticks_ms()
|
||||
breath_origin = last_draw
|
||||
last_cluster = last_draw
|
||||
spark_active = False
|
||||
spark_start = 0
|
||||
spark_dur = 0
|
||||
next_spark = utime.ticks_add(last_draw, random.randint(gap_lo, gap_hi)) if sparks_on else 0
|
||||
|
||||
if not preset.a:
|
||||
now = utime.ticks_ms()
|
||||
self._draw_frame(
|
||||
preset,
|
||||
palette,
|
||||
now,
|
||||
utime.ticks_diff(now, breath_origin),
|
||||
rise,
|
||||
cluster_jit,
|
||||
breath_ms,
|
||||
lo,
|
||||
hi,
|
||||
(False, 0, 0),
|
||||
)
|
||||
yield
|
||||
return
|
||||
|
||||
while True:
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_draw) < delay_ms:
|
||||
yield
|
||||
continue
|
||||
last_draw = utime.ticks_add(last_draw, delay_ms)
|
||||
|
||||
rise = (rise + random.randint(-10, 12)) & 255
|
||||
|
||||
if utime.ticks_diff(now, last_cluster) >= (delay_ms * 4):
|
||||
last_cluster = now
|
||||
cluster_jit = [random.randint(-18, 18) for _ in range(8)]
|
||||
|
||||
spark_state = (spark_active, spark_start, spark_dur)
|
||||
if sparks_on:
|
||||
if spark_active:
|
||||
if utime.ticks_diff(now, spark_start) >= spark_dur:
|
||||
spark_active = False
|
||||
next_spark = utime.ticks_add(
|
||||
now,
|
||||
random.randint(gap_lo, gap_hi),
|
||||
)
|
||||
elif utime.ticks_diff(now, next_spark) >= 0:
|
||||
spark_active = True
|
||||
spark_start = now
|
||||
spark_dur = random.randint(180, 360)
|
||||
|
||||
self._draw_frame(
|
||||
preset,
|
||||
palette,
|
||||
now,
|
||||
utime.ticks_diff(now, breath_origin),
|
||||
rise,
|
||||
cluster_jit,
|
||||
breath_ms,
|
||||
lo,
|
||||
hi,
|
||||
(spark_active, spark_start, spark_dur),
|
||||
)
|
||||
yield
|
||||
@@ -1,40 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
|
||||
class Flicker:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
"""Random brightness between n1 (min) and b (max); delay d ms between updates."""
|
||||
colors = preset.c if preset.c else [(255, 255, 255)]
|
||||
color_index = 0
|
||||
last_update = utime.ticks_ms()
|
||||
|
||||
def brightness_bounds():
|
||||
lo = max(0, min(255, int(preset.n1)))
|
||||
hi = max(0, min(255, int(preset.b)))
|
||||
if lo > hi:
|
||||
lo, hi = hi, lo
|
||||
return lo, hi
|
||||
|
||||
if not preset.a:
|
||||
lo, hi = brightness_bounds()
|
||||
level = random.randint(lo, hi)
|
||||
base = colors[color_index % len(colors)]
|
||||
self.driver.fill(self.driver.apply_brightness(base, level))
|
||||
yield
|
||||
return
|
||||
|
||||
while True:
|
||||
current_time = utime.ticks_ms()
|
||||
delay_ms = max(1, int(preset.d))
|
||||
lo, hi = brightness_bounds()
|
||||
if utime.ticks_diff(current_time, last_update) >= delay_ms:
|
||||
level = random.randint(lo, hi)
|
||||
base = colors[color_index % len(colors)]
|
||||
self.driver.fill(self.driver.apply_brightness(base, level))
|
||||
color_index += 1
|
||||
last_update = utime.ticks_add(last_update, delay_ms)
|
||||
yield
|
||||
@@ -1,62 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class Icicles:
|
||||
"""Icicles hanging from anchor points; tips brighten toward max length then shrink."""
|
||||
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(240, 248, 255), (160, 210, 255), (255, 255, 255)]
|
||||
spacing = max(1, int(preset.n1) if int(preset.n1) > 0 else 12)
|
||||
nled = self.driver.num_leds
|
||||
max_len = max(
|
||||
2,
|
||||
min(
|
||||
int(preset.n2) if int(preset.n2) > 0 else min(14, max(3, nled // 4)),
|
||||
max(2, nled),
|
||||
),
|
||||
)
|
||||
span = max_len * 2
|
||||
phase_step = max(1, int(preset.n3) if int(preset.n3) > 0 else 1)
|
||||
phase = 0
|
||||
last = utime.ticks_ms()
|
||||
|
||||
while True:
|
||||
d_ms = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d_ms:
|
||||
bg_rgb = preset.background_or(colors)
|
||||
bg = self.driver.apply_brightness(bg_rgb, preset.b)
|
||||
|
||||
for i in range(nled):
|
||||
self.driver.n[i] = bg
|
||||
|
||||
aidx = 0
|
||||
for anchor in range(0, nled, spacing):
|
||||
tri_i = (phase + aidx * 5) % span
|
||||
ic_len = tri_i if tri_i <= max_len else span - tri_i
|
||||
tip_c = colors[aidx % len(colors)]
|
||||
tip = self.driver.apply_brightness(tip_c, preset.b)
|
||||
for k in range(ic_len):
|
||||
idx = anchor + k
|
||||
if idx >= nled:
|
||||
break
|
||||
br = ((k + 1) * 255) // max(1, ic_len)
|
||||
self.driver.n[self.driver.led_i(preset, idx)] = (
|
||||
(tip[0] * br + bg[0] * (255 - br)) // 255,
|
||||
(tip[1] * br + bg[1] * (255 - br)) // 255,
|
||||
(tip[2] * br + bg[2] * (255 - br)) // 255,
|
||||
)
|
||||
aidx += 1
|
||||
|
||||
self.driver.n.write()
|
||||
phase = (phase + self.driver.signed(preset, phase_step)) % span
|
||||
last = utime.ticks_add(last, d_ms)
|
||||
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
|
||||
yield
|
||||
@@ -1,176 +0,0 @@
|
||||
import utime
|
||||
|
||||
from patterns.pattern_modes import style_mode
|
||||
|
||||
_LEGACY = {"comet_dual": 1, "scanner": 2}
|
||||
|
||||
|
||||
class Meteor:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _fade(self, color, fade_amount):
|
||||
return (
|
||||
(color[0] * fade_amount) // 255,
|
||||
(color[1] * fade_amount) // 255,
|
||||
(color[2] * fade_amount) // 255,
|
||||
)
|
||||
|
||||
def _run_meteor(self, preset, colors, color_index, head, direction, last_update):
|
||||
tail_len = max(1, int(preset.n1) if int(preset.n1) > 0 else 8)
|
||||
speed = max(1, int(preset.n2) if int(preset.n2) > 0 else 1)
|
||||
fade_amount = int(preset.n3) if int(preset.n3) > 0 else 192
|
||||
fade_amount = max(1, min(255, fade_amount))
|
||||
delay_ms = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_update) < delay_ms:
|
||||
return color_index, head, direction, last_update, False
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = self._fade(self.driver.n[i], fade_amount)
|
||||
base = colors[color_index % len(colors)]
|
||||
lit = self.driver.apply_brightness(base, preset.b)
|
||||
if 0 <= head < self.driver.num_leds:
|
||||
self.driver.n[self.driver.led_i(preset, head)] = lit
|
||||
self.driver.n.write()
|
||||
head += self.driver.signed(preset, direction * speed)
|
||||
if head >= self.driver.num_leds + tail_len:
|
||||
head = self.driver.num_leds - 1
|
||||
direction = -1
|
||||
color_index += 1
|
||||
elif head < -tail_len:
|
||||
head = 0
|
||||
direction = 1
|
||||
color_index += 1
|
||||
return color_index, head, direction, utime.ticks_add(last_update, delay_ms), True
|
||||
|
||||
def _run_comet_dual(self, preset, colors, p1, p2, last):
|
||||
tail = max(1, int(preset.n1) if int(preset.n1) > 0 else 6)
|
||||
speed = max(1, int(preset.n2) if int(preset.n2) > 0 else 1)
|
||||
gap = max(0, int(preset.n3))
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) < d:
|
||||
return p1, p2, last, False
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = bg_color
|
||||
c1 = self.driver.apply_brightness(colors[0 % len(colors)], preset.b)
|
||||
c2 = self.driver.apply_brightness(
|
||||
colors[1 % len(colors)] if len(colors) > 1 else colors[0], preset.b
|
||||
)
|
||||
for t in range(tail):
|
||||
i1 = p1 - t
|
||||
if 0 <= i1 < self.driver.num_leds:
|
||||
s = (255 * (tail - t)) // max(1, tail)
|
||||
self.driver.n[self.driver.led_i(preset, i1)] = (
|
||||
(c1[0] * s) // 255,
|
||||
(c1[1] * s) // 255,
|
||||
(c1[2] * s) // 255,
|
||||
)
|
||||
i2 = p2 + t
|
||||
if 0 <= i2 < self.driver.num_leds:
|
||||
s = (255 * (tail - t)) // max(1, tail)
|
||||
self.driver.n[self.driver.led_i(preset, i2)] = (
|
||||
(c2[0] * s) // 255,
|
||||
(c2[1] * s) // 255,
|
||||
(c2[2] * s) // 255,
|
||||
)
|
||||
self.driver.n.write()
|
||||
p1 += self.driver.signed(preset, speed)
|
||||
p2 -= self.driver.signed(preset, speed)
|
||||
if p1 - tail > self.driver.num_leds and p2 + tail < 0:
|
||||
p1 = 0
|
||||
p2 = self.driver.num_leds - 1 - gap
|
||||
return p1, p2, utime.ticks_add(last, d), True
|
||||
|
||||
def _run_scanner(self, preset, colors, color_index, center, direction, pause_frames, last_update):
|
||||
width = max(1, int(preset.n1) if int(preset.n1) > 0 else 4)
|
||||
end_pause = max(0, int(preset.n2))
|
||||
delay_ms = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_update) < delay_ms:
|
||||
return color_index, center, direction, pause_frames, last_update, False
|
||||
base = self.driver.apply_brightness(colors[color_index % len(colors)], preset.b)
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
dist = i - center
|
||||
if dist < 0:
|
||||
dist = -dist
|
||||
if dist > width:
|
||||
self.driver.n[self.driver.led_i(preset, i)] = bg_color
|
||||
else:
|
||||
scale = ((width - dist) * 255) // max(1, width)
|
||||
self.driver.n[self.driver.led_i(preset, i)] = (
|
||||
(base[0] * scale) // 255,
|
||||
(base[1] * scale) // 255,
|
||||
(base[2] * scale) // 255,
|
||||
)
|
||||
self.driver.n.write()
|
||||
if pause_frames > 0:
|
||||
pause_frames -= 1
|
||||
else:
|
||||
center += self.driver.signed(preset, direction)
|
||||
if center >= self.driver.num_leds - 1:
|
||||
center = self.driver.num_leds - 1
|
||||
direction = -1
|
||||
pause_frames = end_pause
|
||||
color_index += 1
|
||||
elif center <= 0:
|
||||
center = 0
|
||||
direction = 1
|
||||
pause_frames = end_pause
|
||||
color_index += 1
|
||||
return color_index, center, direction, pause_frames, utime.ticks_add(last_update, delay_ms), True
|
||||
|
||||
def run(self, preset):
|
||||
"""Moving lights: n6 style 0 meteor, 1 dual comet, 2 scanner (legacy ids still work)."""
|
||||
mode = style_mode(preset, 0, _LEGACY)
|
||||
colors = preset.c if preset.c else [(255, 255, 255)]
|
||||
|
||||
if mode == 1:
|
||||
gap = max(0, int(preset.n3))
|
||||
nled = self.driver.num_leds
|
||||
if self.driver.is_reversed(preset):
|
||||
p1, p2 = nled - 1, gap
|
||||
else:
|
||||
p1, p2 = 0, nled - 1 - gap
|
||||
last = utime.ticks_ms()
|
||||
while True:
|
||||
p1, p2, last, stepped = self._run_comet_dual(preset, colors, p1, p2, last)
|
||||
if stepped and not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
|
||||
if mode == 2:
|
||||
nled = self.driver.num_leds
|
||||
if self.driver.is_reversed(preset):
|
||||
color_index, center, direction, pause_frames = 0, max(0, nled - 1), -1, 0
|
||||
else:
|
||||
color_index, center, direction, pause_frames = 0, 0, 1, 0
|
||||
last_update = utime.ticks_ms()
|
||||
while True:
|
||||
color_index, center, direction, pause_frames, last_update, stepped = (
|
||||
self._run_scanner(
|
||||
preset, colors, color_index, center, direction, pause_frames, last_update
|
||||
)
|
||||
)
|
||||
if stepped and not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
|
||||
nled = self.driver.num_leds
|
||||
if self.driver.is_reversed(preset):
|
||||
color_index, head, direction = 0, max(0, nled - 1), -1
|
||||
else:
|
||||
color_index, head, direction = 0, 0, 1
|
||||
last_update = utime.ticks_ms()
|
||||
while True:
|
||||
color_index, head, direction, last_update, stepped = self._run_meteor(
|
||||
preset, colors, color_index, head, direction, last_update
|
||||
)
|
||||
if stepped and not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,31 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class Orbit:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(255, 255, 255), (0, 180, 255), (255, 0, 120)]
|
||||
orbits = max(1, int(preset.n1) if int(preset.n1) > 0 else 3)
|
||||
speed = max(1, int(preset.n2) if int(preset.n2) > 0 else 1)
|
||||
phase = self.driver.step % 256
|
||||
last = utime.ticks_ms()
|
||||
while True:
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d:
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = bg_color
|
||||
for k in range(orbits):
|
||||
idx = ((phase * (k + 1)) // 8 + (k * self.driver.num_leds // max(1, orbits))) % max(1, self.driver.num_leds)
|
||||
self.driver.n[idx] = self.driver.apply_brightness(colors[k % len(colors)], preset.b)
|
||||
self.driver.n.write()
|
||||
phase = (phase + speed) & 255
|
||||
self.driver.step = phase
|
||||
last = utime.ticks_add(last, d)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,81 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class PaletteMorph:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _blend(self, c1, c2, t):
|
||||
return (
|
||||
c1[0] + ((c2[0] - c1[0]) * t) // 255,
|
||||
c1[1] + ((c2[1] - c1[1]) * t) // 255,
|
||||
c1[2] + ((c2[2] - c1[2]) * t) // 255,
|
||||
)
|
||||
|
||||
def run(self, preset):
|
||||
"""Living color field (non-scrolling palette warp).
|
||||
|
||||
Different from `colour_cycle`: this does not scroll a fixed gradient.
|
||||
Instead, each LED breathes/warps through the palette with local phase
|
||||
offsets so the strip looks alive.
|
||||
|
||||
n1: morph duration (ms)
|
||||
n2: warp rate
|
||||
n3: spatial turbulence amount
|
||||
"""
|
||||
colors = preset.c if preset.c else [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
|
||||
if len(colors) < 2:
|
||||
while True:
|
||||
self.driver.fill(self.driver.apply_brightness(colors[0], preset.b))
|
||||
yield
|
||||
morph = max(50, int(preset.n1) if int(preset.n1) > 0 else 1200)
|
||||
warp_rate = max(1, int(preset.n2) if int(preset.n2) > 0 else 3)
|
||||
turbulence = max(1, int(preset.n3) if int(preset.n3) > 0 else 24)
|
||||
base_idx = 0
|
||||
start = utime.ticks_ms()
|
||||
phase = self.driver.step % 256
|
||||
last_update = start
|
||||
|
||||
while True:
|
||||
now = utime.ticks_ms()
|
||||
delay_ms = max(1, int(preset.d))
|
||||
if utime.ticks_diff(now, last_update) < delay_ms:
|
||||
yield
|
||||
continue
|
||||
last_update = utime.ticks_add(last_update, delay_ms)
|
||||
age = utime.ticks_diff(now, start)
|
||||
if age < morph:
|
||||
t = (age * 255) // morph
|
||||
else:
|
||||
t = 255
|
||||
|
||||
# Global morph anchor between neighboring palette colors.
|
||||
a = colors[base_idx % len(colors)]
|
||||
b = colors[(base_idx + 1) % len(colors)]
|
||||
anchor = self._blend(a, b, t)
|
||||
|
||||
for i in range(self.driver.num_leds):
|
||||
# Non-linear local warp per LED to create "living" motion.
|
||||
pos = (i * 256) // max(1, self.driver.num_leds)
|
||||
wobble = ((pos * turbulence) // 32 + phase + (t // 2)) & 255
|
||||
breath = 255 - abs(128 - wobble) * 2
|
||||
local = (pos + (breath // 3) + (t // 4)) % 256
|
||||
idx = (base_idx + ((local * len(colors)) // 256)) % len(colors)
|
||||
frac = (local * len(colors)) & 255
|
||||
c1 = colors[idx]
|
||||
c2 = colors[(idx + 1) % len(colors)]
|
||||
grad = self._blend(c1, c2, frac)
|
||||
# Blend with anchor to keep coherent palette morphing.
|
||||
out = self._blend(grad, anchor, 80)
|
||||
self.driver.n[i] = self.driver.apply_brightness(out, preset.b)
|
||||
self.driver.n.write()
|
||||
|
||||
if age >= morph:
|
||||
base_idx = (base_idx + 1) % len(colors)
|
||||
start = now
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
phase = (phase + warp_rate) & 255
|
||||
self.driver.step = phase
|
||||
yield
|
||||
@@ -1,111 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
from patterns.pattern_modes import style_mode
|
||||
|
||||
_LEGACY = {"starfall": 1}
|
||||
|
||||
|
||||
class Particles:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _run_snowfall(self, preset, colors, flakes, last):
|
||||
density = max(1, int(preset.n1) if int(preset.n1) > 0 else 20)
|
||||
speed = max(1, abs(self.driver.signed(preset, int(preset.n2) if int(preset.n2) > 0 else 1)))
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) < d:
|
||||
return flakes, last, False
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
if random.randint(0, 255) < density:
|
||||
flakes.append([self.driver.num_leds - 1, random.randint(0, len(colors) - 1)])
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = bg_color
|
||||
nf = []
|
||||
for pos, ci in flakes:
|
||||
if 0 <= pos < self.driver.num_leds:
|
||||
self.driver.n[self.driver.led_i(preset, pos)] = self.driver.apply_brightness(
|
||||
colors[ci], preset.b
|
||||
)
|
||||
pos -= self.driver.signed(preset, speed)
|
||||
if pos >= -1:
|
||||
nf.append([pos, ci])
|
||||
self.driver.n.write()
|
||||
return nf, utime.ticks_add(last, d), True
|
||||
|
||||
def _run_starfall(self, preset, colors, stars, last):
|
||||
rate = max(1, min(255, int(preset.n1) if int(preset.n1) > 0 else 14))
|
||||
speed = max(1, abs(self.driver.signed(preset, int(preset.n2) if int(preset.n2) > 0 else 2)))
|
||||
tail = max(2, int(preset.n3) if int(preset.n3) > 0 else 10)
|
||||
max_stars = 4
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) < d:
|
||||
return stars, last, False
|
||||
bg = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = bg
|
||||
if len(stars) < max_stars and random.randint(0, 255) < rate:
|
||||
top = self.driver.num_leds - 1 + random.randint(
|
||||
0, min(8, self.driver.num_leds // 2)
|
||||
)
|
||||
stars.append({"h": float(top), "ci": random.randint(0, len(colors) - 1)})
|
||||
ns = []
|
||||
for s in stars:
|
||||
h = s["h"]
|
||||
ci = s["ci"]
|
||||
ih = int(h)
|
||||
for t in range(tail):
|
||||
idx = ih + t
|
||||
if 0 <= idx < self.driver.num_leds:
|
||||
fade = 255 - (t * 255 // max(1, tail - 1))
|
||||
base = colors[ci]
|
||||
lit = (
|
||||
(base[0] * fade) // 255,
|
||||
(base[1] * fade) // 255,
|
||||
(base[2] * fade) // 255,
|
||||
)
|
||||
lit = self.driver.apply_brightness(lit, preset.b)
|
||||
pix = self.driver.led_i(preset, idx)
|
||||
o = self.driver.n[pix]
|
||||
self.driver.n[pix] = (
|
||||
max(o[0], lit[0]),
|
||||
max(o[1], lit[1]),
|
||||
max(o[2], lit[2]),
|
||||
)
|
||||
h -= self.driver.signed(preset, speed)
|
||||
if h >= -tail:
|
||||
s["h"] = h
|
||||
ns.append(s)
|
||||
stars = ns
|
||||
self.driver.n.write()
|
||||
return stars, utime.ticks_add(last, d), True
|
||||
|
||||
def run(self, preset):
|
||||
"""Falling particles: n6 0 snowfall flakes, 1 starfall streaks."""
|
||||
mode = style_mode(preset, 0, _LEGACY)
|
||||
colors = preset.c if preset.c else [(255, 255, 255), (180, 220, 255)]
|
||||
last = utime.ticks_ms()
|
||||
|
||||
if mode == 1:
|
||||
colors = preset.c if preset.c else [
|
||||
(255, 255, 255),
|
||||
(200, 230, 255),
|
||||
(255, 248, 220),
|
||||
]
|
||||
stars = []
|
||||
while True:
|
||||
stars, last, stepped = self._run_starfall(preset, colors, stars, last)
|
||||
if stepped and not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
|
||||
flakes = []
|
||||
while True:
|
||||
flakes, last, stepped = self._run_snowfall(preset, colors, flakes, last)
|
||||
if stepped and not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,19 +0,0 @@
|
||||
"""Strip install direction: n5 bit 0 reverses along-strip motion (upside-down wiring)."""
|
||||
|
||||
|
||||
def is_reversed(preset):
|
||||
return bool(int(getattr(preset, "n5", 0) or 0) & 1)
|
||||
|
||||
|
||||
def led_i(driver, preset, logical_index):
|
||||
"""Map a logical strip index (0 = pattern start) to a physical pixel index."""
|
||||
n = int(driver.num_leds)
|
||||
i = int(logical_index)
|
||||
if 0 <= i < n and is_reversed(preset):
|
||||
return n - 1 - i
|
||||
return i
|
||||
|
||||
|
||||
def signed(preset, value):
|
||||
v = int(value)
|
||||
return -v if is_reversed(preset) else v
|
||||
@@ -1,18 +0,0 @@
|
||||
"""Resolve pattern style from n6 or legacy preset pattern id (p)."""
|
||||
|
||||
|
||||
def style_mode(preset, default=0, legacy=None):
|
||||
legacy = legacy or {}
|
||||
p = getattr(preset, "p", "") or ""
|
||||
if p in legacy:
|
||||
return legacy[p]
|
||||
mode = getattr(preset, "mode", None)
|
||||
if mode is None and isinstance(preset, dict):
|
||||
mode = preset.get("mode")
|
||||
if mode is not None:
|
||||
try:
|
||||
return int(mode)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
n6 = int(getattr(preset, "n6", 0) or 0)
|
||||
return n6 if n6 > 0 else default
|
||||
@@ -1,39 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class Plasma:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _wheel(self, pos):
|
||||
if pos < 85:
|
||||
return (pos * 3, 255 - pos * 3, 0)
|
||||
if pos < 170:
|
||||
pos -= 85
|
||||
return (255 - pos * 3, 0, pos * 3)
|
||||
pos -= 170
|
||||
return (0, pos * 3, 255 - pos * 3)
|
||||
|
||||
def run(self, preset):
|
||||
scale = max(1, int(preset.n1) if int(preset.n1) > 0 else 6)
|
||||
speed = max(1, int(preset.n2) if int(preset.n2) > 0 else 2)
|
||||
contrast = max(1, int(preset.n3) if int(preset.n3) > 0 else 2)
|
||||
t = self.driver.step % 256
|
||||
last = utime.ticks_ms()
|
||||
while True:
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d:
|
||||
for i in range(self.driver.num_leds):
|
||||
v = ((i * scale + t) & 255)
|
||||
v2 = (((i * scale // max(1, contrast)) - (t * 2)) & 255)
|
||||
c = self._wheel((v + v2) & 255)
|
||||
self.driver.n[i] = self.driver.apply_brightness(c, preset.b)
|
||||
self.driver.n.write()
|
||||
t = (t + speed) % 256
|
||||
self.driver.step = t
|
||||
last = utime.ticks_add(last, d)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,68 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class Pulse:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
# Get colors from preset
|
||||
colors = preset.c
|
||||
if not colors:
|
||||
colors = [(255, 255, 255)]
|
||||
bg_base = preset.background_or(colors)
|
||||
self.driver.fill(self.driver.apply_brightness(bg_base, preset.b))
|
||||
|
||||
manual = not preset.a
|
||||
color_index = self.driver.step % max(1, len(colors))
|
||||
cycle_start = utime.ticks_ms()
|
||||
|
||||
# State machine based pulse using a single generator loop
|
||||
while True:
|
||||
bg_color = self.driver.apply_brightness(bg_base, preset.b)
|
||||
# Read current timing parameters from preset
|
||||
attack_ms = max(0, int(preset.n1)) # Attack time in ms
|
||||
hold_ms = max(0, int(preset.n2)) # Hold time in ms
|
||||
decay_ms = max(0, int(preset.n3)) # Decay time in ms
|
||||
delay_ms = 0 if manual else max(0, int(preset.d))
|
||||
|
||||
total_ms = attack_ms + hold_ms + decay_ms + delay_ms
|
||||
if total_ms <= 0:
|
||||
total_ms = 1
|
||||
|
||||
now = utime.ticks_ms()
|
||||
elapsed = utime.ticks_diff(now, cycle_start)
|
||||
|
||||
base_color = colors[color_index % len(colors)]
|
||||
|
||||
if elapsed < attack_ms and attack_ms > 0:
|
||||
# Attack: fade 0 -> 1
|
||||
factor = elapsed / attack_ms
|
||||
color = tuple(int(c * factor) for c in base_color)
|
||||
self.driver.fill(self.driver.apply_brightness(color, preset.b))
|
||||
elif elapsed < attack_ms + hold_ms:
|
||||
# Hold: full brightness
|
||||
self.driver.fill(self.driver.apply_brightness(base_color, preset.b))
|
||||
elif elapsed < attack_ms + hold_ms + decay_ms and decay_ms > 0:
|
||||
# Decay: fade 1 -> 0
|
||||
dec_elapsed = elapsed - attack_ms - hold_ms
|
||||
factor = max(0.0, 1.0 - (dec_elapsed / decay_ms))
|
||||
color = tuple(int(c * factor) for c in base_color)
|
||||
self.driver.fill(self.driver.apply_brightness(color, preset.b))
|
||||
elif elapsed < total_ms:
|
||||
# Delay phase: LEDs off between pulses
|
||||
self.driver.fill(bg_color)
|
||||
else:
|
||||
# End of cycle: advance colour for the next run, then loop or stop.
|
||||
nclr = max(1, len(colors))
|
||||
color_index = (color_index + 1) % nclr
|
||||
self.driver.step = color_index
|
||||
if manual:
|
||||
self.driver.fill(bg_color)
|
||||
break
|
||||
cycle_start = now
|
||||
yield
|
||||
continue
|
||||
|
||||
# Yield once per tick
|
||||
yield
|
||||
@@ -1,172 +0,0 @@
|
||||
import utime
|
||||
|
||||
# When ``driver.debug`` is True (``settings["debug"]``), log at most this often (ms).
|
||||
_RADIATE_DBG_INTERVAL_MS = 2500
|
||||
|
||||
|
||||
class Radiate:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
self._color_step = 0
|
||||
|
||||
def run(self, preset):
|
||||
"""Radiate from nodes every n1 LEDs, retriggering every delay (d).
|
||||
|
||||
- n1: node spacing in LEDs
|
||||
- n2: outbound travel time in ms
|
||||
- n3: return travel time in ms
|
||||
- d: retrigger interval in ms
|
||||
"""
|
||||
colors = preset.c if preset.c else [(255, 255, 255)]
|
||||
base_off = preset.background_or(colors)
|
||||
|
||||
spacing = max(1, int(preset.n1))
|
||||
outward_ms = max(1, int(preset.n2))
|
||||
return_ms = max(1, int(preset.n3))
|
||||
max_dist = spacing // 2
|
||||
|
||||
lit_color = self.driver.apply_brightness(colors[self._color_step % max(1, len(colors))], preset.b)
|
||||
off_color = self.driver.apply_brightness(base_off, preset.b)
|
||||
|
||||
now = utime.ticks_ms()
|
||||
last_trigger = now
|
||||
active_pulses = [now]
|
||||
last_dbg = now
|
||||
dbg_banner = False
|
||||
|
||||
if not preset.a:
|
||||
# Manual mode: one-shot pulse using the same ms-based timing as auto.
|
||||
cycle_start = utime.ticks_ms()
|
||||
last_dbg = cycle_start
|
||||
while True:
|
||||
dbg = bool(getattr(self.driver, "debug", False))
|
||||
spacing = max(1, int(preset.n1))
|
||||
outward_ms = max(1, int(preset.n2))
|
||||
return_ms = max(1, int(preset.n3))
|
||||
max_dist = spacing // 2
|
||||
on_color = colors[self._color_step % max(1, len(colors))]
|
||||
lit_color = self.driver.apply_brightness(on_color, preset.b)
|
||||
off_color = self.driver.apply_brightness(base_off, preset.b)
|
||||
|
||||
pulse_lifetime = outward_ms + return_ms
|
||||
now = utime.ticks_ms()
|
||||
age = utime.ticks_diff(now, cycle_start)
|
||||
if age < 1:
|
||||
age = 1
|
||||
if age <= outward_ms:
|
||||
front = (age * max_dist + outward_ms - 1) // outward_ms
|
||||
elif age <= outward_ms + return_ms:
|
||||
back_age = age - outward_ms
|
||||
remaining = return_ms - back_age
|
||||
front = (remaining * max_dist + return_ms - 1) // return_ms
|
||||
else:
|
||||
front = 0
|
||||
|
||||
lit_count = 0
|
||||
for i in range(self.driver.num_leds):
|
||||
offset = (i + (spacing // 2)) % spacing
|
||||
dist = min(offset, spacing - offset)
|
||||
lit = dist <= front
|
||||
self.driver.n[i] = lit_color if lit else off_color
|
||||
if lit:
|
||||
lit_count += 1
|
||||
self.driver.n.write()
|
||||
|
||||
if dbg:
|
||||
if not dbg_banner:
|
||||
dbg_banner = True
|
||||
print(
|
||||
"[radiate] debug on n1=%s n2=%s n3=%s d=%s auto=%s num_leds=%d"
|
||||
% (preset.n1, preset.n2, preset.n3, preset.d, preset.a, self.driver.num_leds)
|
||||
)
|
||||
if utime.ticks_diff(now, last_dbg) >= _RADIATE_DBG_INTERVAL_MS:
|
||||
print(
|
||||
"[radiate] manual frame age=%d/%d front=%d lit=%d"
|
||||
% (age, pulse_lifetime, front, lit_count)
|
||||
)
|
||||
last_dbg = now
|
||||
|
||||
yield
|
||||
if age >= pulse_lifetime:
|
||||
self._color_step += 1
|
||||
return
|
||||
|
||||
while True:
|
||||
now = utime.ticks_ms()
|
||||
dbg = bool(getattr(self.driver, "debug", False))
|
||||
delay_ms = max(1, int(preset.d))
|
||||
spacing = max(1, int(preset.n1))
|
||||
outward_ms = max(1, int(preset.n2))
|
||||
return_ms = max(1, int(preset.n3))
|
||||
pulse_lifetime = outward_ms + return_ms
|
||||
max_dist = spacing // 2
|
||||
on_color = colors[self._color_step % max(1, len(colors))]
|
||||
lit_color = self.driver.apply_brightness(on_color, preset.b)
|
||||
off_color = self.driver.apply_brightness(base_off, preset.b)
|
||||
|
||||
if preset.a and utime.ticks_diff(now, last_trigger) >= delay_ms:
|
||||
# Keep one pulse train at a time; replacing instead of appending
|
||||
# prevents overlap from keeping color[0] continuously visible.
|
||||
active_pulses = [now]
|
||||
last_trigger = utime.ticks_add(last_trigger, delay_ms)
|
||||
self._color_step += 1
|
||||
|
||||
# Drop pulses once their out-and-back lifetime ends.
|
||||
kept = []
|
||||
for start in active_pulses:
|
||||
age = utime.ticks_diff(now, start)
|
||||
if age < pulse_lifetime:
|
||||
kept.append(start)
|
||||
active_pulses = kept
|
||||
|
||||
lit_count = 0
|
||||
for i in range(self.driver.num_leds):
|
||||
# Nearest node distance for a repeating node grid every `spacing` LEDs.
|
||||
offset = (i + (spacing // 2)) % spacing
|
||||
dist = min(offset, spacing - offset)
|
||||
|
||||
lit = False
|
||||
for start in active_pulses:
|
||||
age = utime.ticks_diff(now, start)
|
||||
# Auto: skip the exact trigger tick (age==0) so nodes are not stuck on.
|
||||
if age <= 0:
|
||||
continue
|
||||
if age <= outward_ms:
|
||||
# Integer-ceiling progression so peak can be reached even
|
||||
# when tick timing skips the exact outward_ms boundary.
|
||||
front = (age * max_dist + outward_ms - 1) // outward_ms
|
||||
elif age <= outward_ms + return_ms:
|
||||
back_age = age - outward_ms
|
||||
remaining = return_ms - back_age
|
||||
front = (remaining * max_dist + return_ms - 1) // return_ms
|
||||
else:
|
||||
continue
|
||||
|
||||
if dist <= front:
|
||||
lit = True
|
||||
break
|
||||
|
||||
self.driver.n[i] = lit_color if lit else off_color
|
||||
if lit:
|
||||
lit_count += 1
|
||||
|
||||
self.driver.n.write()
|
||||
|
||||
if dbg:
|
||||
if not dbg_banner:
|
||||
dbg_banner = True
|
||||
print(
|
||||
"[radiate] debug on n1=%s n2=%s n3=%s d=%s auto=%s num_leds=%d"
|
||||
% (preset.n1, preset.n2, preset.n3, preset.d, preset.a, self.driver.num_leds)
|
||||
)
|
||||
pulse_age = -1
|
||||
if active_pulses:
|
||||
pulse_age = utime.ticks_diff(now, active_pulses[0])
|
||||
if utime.ticks_diff(now, last_dbg) >= _RADIATE_DBG_INTERVAL_MS:
|
||||
print(
|
||||
"[radiate] pulses=%d first_age=%d lit=%d lifetime=%d"
|
||||
% (len(active_pulses), pulse_age, lit_count, pulse_lifetime)
|
||||
)
|
||||
last_dbg = now
|
||||
|
||||
yield
|
||||
@@ -1,41 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
|
||||
class RainDrops:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(120, 180, 255)]
|
||||
rate = max(1, int(preset.n1) if int(preset.n1) > 0 else 32)
|
||||
width = max(1, int(preset.n2) if int(preset.n2) > 0 else 3)
|
||||
drops = []
|
||||
last = utime.ticks_ms()
|
||||
while True:
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d:
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = bg_color
|
||||
if random.randint(0, 255) < rate:
|
||||
drops.append([random.randint(0, max(0, self.driver.num_leds - 1)), 0])
|
||||
nd = []
|
||||
for pos, age in drops:
|
||||
for off in range(-width, width + 1):
|
||||
idx = pos + off
|
||||
if 0 <= idx < self.driver.num_leds:
|
||||
s = 255 - min(255, abs(off) * 255 // max(1, width + 1) + age * 40)
|
||||
base = self.driver.apply_brightness(colors[age % len(colors)], preset.b)
|
||||
self.driver.n[idx] = ((base[0]*s)//255, (base[1]*s)//255, (base[2]*s)//255)
|
||||
age += 1
|
||||
if age < 8:
|
||||
nd.append([pos, age])
|
||||
drops = nd
|
||||
self.driver.n.write()
|
||||
last = utime.ticks_add(last, d)
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,72 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
|
||||
class Rime:
|
||||
"""Slow frost build-up on a chilly background — gentle random brightening then decay."""
|
||||
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(220, 235, 255), (255, 255, 255), (185, 220, 255)]
|
||||
num = self.driver.num_leds
|
||||
if num <= 0:
|
||||
while True:
|
||||
yield
|
||||
return
|
||||
|
||||
# n1: spawn tendency (like twinkle upper range)
|
||||
chill = max(1, min(255, int(preset.n1) if int(preset.n1) > 0 else 36))
|
||||
# n2: decay per refresh (subtract from glow buffer)
|
||||
melt = max(1, min(255, int(preset.n2) if int(preset.n2) > 0 else 12))
|
||||
# n3: how many LEDs can flash brighter per refresh (cap)
|
||||
spark_cap = max(1, min(num, int(preset.n3) if int(preset.n3) > 0 else 3))
|
||||
|
||||
glow = [0] * num
|
||||
last = utime.ticks_ms()
|
||||
|
||||
while True:
|
||||
d_ms = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) >= d_ms:
|
||||
base_bg = preset.background_or(colors)
|
||||
bg = self.driver.apply_brightness(base_bg, preset.b)
|
||||
|
||||
for i in range(num):
|
||||
if glow[i] > melt:
|
||||
glow[i] -= melt
|
||||
else:
|
||||
glow[i] = 0
|
||||
|
||||
spawned = 0
|
||||
tries = spark_cap + num // 8
|
||||
for _ in range(tries):
|
||||
if spawned >= spark_cap:
|
||||
break
|
||||
if random.randint(0, 255) >= chill:
|
||||
continue
|
||||
j = random.randint(0, num - 1)
|
||||
glow[j] = min(255, glow[j] + random.randint(80, 200))
|
||||
spawned += 1
|
||||
|
||||
palette = colors
|
||||
for i in range(num):
|
||||
g = glow[i]
|
||||
fg = palette[i % len(palette)]
|
||||
hi = self.driver.apply_brightness(fg, preset.b)
|
||||
mix = max(0, min(255, g))
|
||||
self.driver.n[i] = (
|
||||
(hi[0] * mix + bg[0] * (255 - mix)) // 255,
|
||||
(hi[1] * mix + bg[1] * (255 - mix)) // 255,
|
||||
(hi[2] * mix + bg[2] * (255 - mix)) // 255,
|
||||
)
|
||||
|
||||
self.driver.n.write()
|
||||
last = utime.ticks_add(last, d_ms)
|
||||
|
||||
if not preset.a:
|
||||
yield
|
||||
return
|
||||
|
||||
yield
|
||||
@@ -1,147 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
from patterns.pattern_modes import style_mode
|
||||
|
||||
_LEGACY = {"sparkle_trail": 0, "ice_sparkle": 1, "fireflies": 2}
|
||||
|
||||
|
||||
class Sparkle:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _run_trail(self, preset, colors, last):
|
||||
density = max(1, int(preset.n1) if int(preset.n1) > 0 else 24)
|
||||
decay = max(1, min(255, int(preset.n2) if int(preset.n2) > 0 else 210))
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) < d:
|
||||
return last, False
|
||||
for i in range(self.driver.num_leds):
|
||||
r, g, b = self.driver.n[i]
|
||||
self.driver.n[i] = ((r * decay) // 255, (g * decay) // 255, (b * decay) // 255)
|
||||
sparks = max(1, self.driver.num_leds * density // 255)
|
||||
for _ in range(sparks):
|
||||
idx = random.randint(0, max(0, self.driver.num_leds - 1))
|
||||
c = self.driver.apply_brightness(
|
||||
colors[random.randint(0, len(colors) - 1)], preset.b
|
||||
)
|
||||
self.driver.n[idx] = c
|
||||
self.driver.n.write()
|
||||
return utime.ticks_add(last, d), True
|
||||
|
||||
def _run_ice(self, preset, colors, sparks, last):
|
||||
rate = max(1, min(255, int(preset.n1) if int(preset.n1) > 0 else 55))
|
||||
decay = max(1, min(255, int(preset.n2) if int(preset.n2) > 0 else 140))
|
||||
halo = max(0, min(3, int(preset.n3)))
|
||||
cap = 28
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) < d:
|
||||
return sparks, last, False
|
||||
bg = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = bg
|
||||
ns = []
|
||||
for s in sparks:
|
||||
lv = s["lv"] - decay
|
||||
if lv > 0:
|
||||
s["lv"] = lv
|
||||
ns.append(s)
|
||||
sparks = ns
|
||||
if len(sparks) < cap and random.randint(0, 255) < rate:
|
||||
sparks.append(
|
||||
{
|
||||
"p": random.randint(0, max(0, self.driver.num_leds - 1)),
|
||||
"lv": 255,
|
||||
"ci": random.randint(0, len(colors) - 1),
|
||||
}
|
||||
)
|
||||
for s in sparks:
|
||||
p = s["p"]
|
||||
lv = s["lv"]
|
||||
ci = s["ci"]
|
||||
base = colors[ci]
|
||||
for off in range(-halo, halo + 1):
|
||||
idx = p + off
|
||||
if 0 <= idx < self.driver.num_leds:
|
||||
dist = abs(off)
|
||||
fac = lv if dist == 0 else (lv * (halo - dist + 1)) // (halo + 1)
|
||||
lit = self.driver.apply_brightness(
|
||||
(
|
||||
(base[0] * fac) // 255,
|
||||
(base[1] * fac) // 255,
|
||||
(base[2] * fac) // 255,
|
||||
),
|
||||
preset.b,
|
||||
)
|
||||
o = self.driver.n[idx]
|
||||
self.driver.n[idx] = (
|
||||
min(255, o[0] + lit[0]),
|
||||
min(255, o[1] + lit[1]),
|
||||
min(255, o[2] + lit[2]),
|
||||
)
|
||||
self.driver.n.write()
|
||||
return sparks, utime.ticks_add(last, d), True
|
||||
|
||||
def _run_fireflies(self, preset, colors, bugs, last):
|
||||
count = max(1, int(preset.n1) if int(preset.n1) > 0 else 6)
|
||||
speed = max(1, int(preset.n2) if int(preset.n2) > 0 else 8)
|
||||
d = max(1, int(preset.d))
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last) < d:
|
||||
return bugs, last, False
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
for i in range(self.driver.num_leds):
|
||||
self.driver.n[i] = bg_color
|
||||
for b in bugs:
|
||||
idx, ph = b
|
||||
tri = 255 - abs(128 - ph) * 2
|
||||
c = self.driver.apply_brightness(colors[idx % len(colors)], preset.b)
|
||||
self.driver.n[idx] = ((c[0] * tri) // 255, (c[1] * tri) // 255, (c[2] * tri) // 255)
|
||||
b[1] = (ph + speed) & 255
|
||||
if random.randint(0, 31) == 0:
|
||||
b[0] = random.randint(0, max(0, self.driver.num_leds - 1))
|
||||
self.driver.n.write()
|
||||
return bugs, utime.ticks_add(last, d), True
|
||||
|
||||
def run(self, preset):
|
||||
"""Sparkles: n6 0 trail decay, 1 ice burst+halo, 2 fireflies."""
|
||||
mode = style_mode(preset, 0, _LEGACY)
|
||||
colors = preset.c if preset.c else [(120, 120, 255)]
|
||||
last = utime.ticks_ms()
|
||||
|
||||
if mode == 2:
|
||||
colors = preset.c if preset.c else [(255, 210, 80), (120, 255, 120)]
|
||||
count = max(1, int(preset.n1) if int(preset.n1) > 0 else 6)
|
||||
bugs = [
|
||||
[random.randint(0, max(0, self.driver.num_leds - 1)), random.randint(0, 255)]
|
||||
for _ in range(count)
|
||||
]
|
||||
while True:
|
||||
bugs, last, stepped = self._run_fireflies(preset, colors, bugs, last)
|
||||
if stepped and not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
|
||||
if mode == 1:
|
||||
colors = preset.c if preset.c else [
|
||||
(240, 248, 255),
|
||||
(200, 235, 255),
|
||||
(255, 255, 255),
|
||||
]
|
||||
sparks = []
|
||||
while True:
|
||||
sparks, last, stepped = self._run_ice(preset, colors, sparks, last)
|
||||
if stepped and not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
|
||||
while True:
|
||||
last, stepped = self._run_trail(preset, colors, last)
|
||||
if stepped and not preset.a:
|
||||
yield
|
||||
return
|
||||
yield
|
||||
@@ -1,45 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class StrobeBurst:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
colors = preset.c if preset.c else [(255, 255, 255)]
|
||||
state = "flash_on"
|
||||
flash_idx = 0
|
||||
state_start = utime.ticks_ms()
|
||||
while True:
|
||||
count = max(1, int(preset.n1) if int(preset.n1) > 0 else 3)
|
||||
gap = max(1, int(preset.n2) if int(preset.n2) > 0 else 60)
|
||||
cooldown = max(1, int(preset.n3) if int(preset.n3) > 0 else 400)
|
||||
on_ms = max(1, int(preset.d) // 2)
|
||||
c = self.driver.apply_brightness(colors[0], preset.b)
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(colors), preset.b)
|
||||
now = utime.ticks_ms()
|
||||
|
||||
if state == "flash_on":
|
||||
self.driver.fill(c)
|
||||
if utime.ticks_diff(now, state_start) >= on_ms:
|
||||
state = "flash_off"
|
||||
state_start = utime.ticks_add(state_start, on_ms)
|
||||
elif state == "flash_off":
|
||||
self.driver.fill(bg_color)
|
||||
if utime.ticks_diff(now, state_start) >= gap:
|
||||
flash_idx += 1
|
||||
if flash_idx >= count:
|
||||
if not preset.a:
|
||||
return
|
||||
state = "cooldown"
|
||||
flash_idx = 0
|
||||
state_start = utime.ticks_add(state_start, gap)
|
||||
else:
|
||||
state = "flash_on"
|
||||
state_start = utime.ticks_add(state_start, gap)
|
||||
else:
|
||||
self.driver.fill(bg_color)
|
||||
if utime.ticks_diff(now, state_start) >= cooldown:
|
||||
state = "flash_on"
|
||||
state_start = utime.ticks_add(state_start, cooldown)
|
||||
yield
|
||||
@@ -1,57 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class Transition:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
"""Transition between colors, blending over `delay` ms."""
|
||||
colors = preset.c
|
||||
if not colors:
|
||||
self.driver.off()
|
||||
yield
|
||||
return
|
||||
|
||||
# Only one color: just keep it on
|
||||
if len(colors) == 1:
|
||||
while True:
|
||||
self.driver.fill(self.driver.apply_brightness(colors[0], preset.b))
|
||||
yield
|
||||
return
|
||||
|
||||
color_index = 0
|
||||
start_time = utime.ticks_ms()
|
||||
|
||||
while True:
|
||||
if not colors:
|
||||
break
|
||||
|
||||
# Get current and next color based on live list
|
||||
c1 = colors[color_index % len(colors)]
|
||||
c2 = colors[(color_index + 1) % len(colors)]
|
||||
|
||||
duration = max(10, int(preset.d)) # At least 10ms
|
||||
now = utime.ticks_ms()
|
||||
elapsed = utime.ticks_diff(now, start_time)
|
||||
|
||||
if elapsed >= duration:
|
||||
# End of this transition step
|
||||
if not preset.a:
|
||||
# One-shot: transition from first to second color only
|
||||
self.driver.fill(self.driver.apply_brightness(c2, preset.b))
|
||||
break
|
||||
# Auto: move to next pair
|
||||
color_index = (color_index + 1) % len(colors)
|
||||
start_time = now
|
||||
yield
|
||||
continue
|
||||
|
||||
# Interpolate between c1 and c2
|
||||
factor = elapsed / duration
|
||||
interpolated = tuple(
|
||||
int(c1[i] + (c2[i] - c1[i]) * factor) for i in range(3)
|
||||
)
|
||||
self.driver.fill(self.driver.apply_brightness(interpolated, preset.b))
|
||||
|
||||
yield
|
||||
@@ -1,160 +0,0 @@
|
||||
import random
|
||||
import utime
|
||||
|
||||
# Default cool palette (icy blues, violet, mint) when preset has no colours.
|
||||
_DEFAULT_COOL = (
|
||||
(120, 200, 255),
|
||||
(80, 140, 255),
|
||||
(180, 120, 255),
|
||||
(100, 220, 240),
|
||||
(160, 200, 255),
|
||||
(90, 180, 220),
|
||||
)
|
||||
|
||||
|
||||
class Twinkle:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def _palette(self, preset):
|
||||
colors = preset.c
|
||||
if not colors:
|
||||
return list(_DEFAULT_COOL)
|
||||
out = []
|
||||
for c in colors:
|
||||
if isinstance(c, (list, tuple)) and len(c) == 3:
|
||||
out.append(
|
||||
(
|
||||
max(0, min(255, int(c[0]))),
|
||||
max(0, min(255, int(c[1]))),
|
||||
max(0, min(255, int(c[2]))),
|
||||
)
|
||||
)
|
||||
return out if out else list(_DEFAULT_COOL)
|
||||
|
||||
def run(self, preset):
|
||||
"""Twinkle: n1 activity, n2 density; n3/n4 min/max length of adjacent on/off runs."""
|
||||
palette = self._palette(preset)
|
||||
num = self.driver.num_leds
|
||||
bg_color = self.driver.apply_brightness(preset.background_or(palette), preset.b)
|
||||
if num <= 0:
|
||||
while True:
|
||||
yield
|
||||
return
|
||||
|
||||
def activity_rate():
|
||||
r = int(preset.n1)
|
||||
if r <= 0:
|
||||
r = 48
|
||||
return max(1, min(255, r))
|
||||
|
||||
def density255():
|
||||
"""Higher → more LEDs lit on average when a twinkle step fires (0 = default mid)."""
|
||||
d = int(preset.n2)
|
||||
if d <= 0:
|
||||
d = 128
|
||||
return max(0, min(255, d))
|
||||
|
||||
def cluster_len_bounds():
|
||||
"""n3 = min adjacent LEDs per twinkle, n4 = max (both 0 → 1..4)."""
|
||||
lo = int(preset.n3)
|
||||
hi = int(preset.n4)
|
||||
if lo <= 0 and hi <= 0:
|
||||
lo, hi = 1, min(4, num)
|
||||
else:
|
||||
if lo <= 0:
|
||||
lo = 1
|
||||
if hi <= 0:
|
||||
hi = lo
|
||||
if hi < lo:
|
||||
lo, hi = hi, lo
|
||||
lo = max(1, min(lo, num))
|
||||
hi = max(lo, min(hi, num))
|
||||
return lo, hi
|
||||
|
||||
def random_cluster_len():
|
||||
lo, hi = cluster_len_bounds()
|
||||
# When min and max match, every lit/dim run is exactly that many LEDs (still capped by strip length).
|
||||
if lo == hi:
|
||||
return lo
|
||||
return random.randint(lo, hi)
|
||||
|
||||
def cluster_base_index(start, k):
|
||||
"""Shift run left so a length-k segment fits; keeps full k when num >= k."""
|
||||
k = min(max(0, int(k)), num)
|
||||
if k <= 0:
|
||||
return 0
|
||||
return max(0, min(int(start), num - k))
|
||||
|
||||
dens = density255()
|
||||
on = [random.randint(0, 255) < dens for _ in range(num)]
|
||||
colour_i = [random.randint(0, len(palette) - 1) for _ in range(num)]
|
||||
last_update = utime.ticks_ms()
|
||||
|
||||
if not preset.a:
|
||||
for i in range(num):
|
||||
if on[i]:
|
||||
base = palette[colour_i[i] % len(palette)]
|
||||
self.driver.n[i] = self.driver.apply_brightness(base, preset.b)
|
||||
else:
|
||||
self.driver.n[i] = bg_color
|
||||
self.driver.n.write()
|
||||
yield
|
||||
return
|
||||
|
||||
while True:
|
||||
now = utime.ticks_ms()
|
||||
delay_ms = max(1, int(preset.d))
|
||||
if utime.ticks_diff(now, last_update) >= delay_ms:
|
||||
rate = activity_rate()
|
||||
dens = density255()
|
||||
# Snapshot for decisions; apply all darks then all lights so
|
||||
# overlaps in the same tick favour lit runs (lights win).
|
||||
prev_on = on[:]
|
||||
prev_ci = colour_i[:]
|
||||
next_on = list(prev_on)
|
||||
next_ci = list(prev_ci)
|
||||
|
||||
light_i = []
|
||||
dark_i = []
|
||||
for i in range(num):
|
||||
if random.randint(0, 255) < rate:
|
||||
r = random.randint(0, 255)
|
||||
if not prev_on[i]:
|
||||
if r < dens:
|
||||
light_i.append(i)
|
||||
else:
|
||||
if r < (255 - dens):
|
||||
dark_i.append(i)
|
||||
|
||||
def light_adjacent(start):
|
||||
k = random_cluster_len()
|
||||
b = cluster_base_index(start, k)
|
||||
for dj in range(k):
|
||||
idx = b + dj
|
||||
next_on[idx] = True
|
||||
next_ci[idx] = random.randint(0, len(palette) - 1)
|
||||
|
||||
def dark_adjacent(start):
|
||||
k = random_cluster_len()
|
||||
b = cluster_base_index(start, k)
|
||||
for dj in range(k):
|
||||
idx = b + dj
|
||||
next_on[idx] = False
|
||||
|
||||
for i in dark_i:
|
||||
dark_adjacent(i)
|
||||
for i in light_i:
|
||||
light_adjacent(i)
|
||||
|
||||
for i in range(num):
|
||||
if next_on[i]:
|
||||
base = palette[next_ci[i] % len(palette)]
|
||||
self.driver.n[i] = self.driver.apply_brightness(base, preset.b)
|
||||
else:
|
||||
self.driver.n[i] = bg_color
|
||||
self.driver.n.write()
|
||||
on = next_on
|
||||
colour_i = next_ci
|
||||
last_update = utime.ticks_add(last_update, delay_ms)
|
||||
yield
|
||||
-156
@@ -1,156 +0,0 @@
|
||||
class Preset:
|
||||
def __init__(self, data):
|
||||
# Set default values for all preset attributes
|
||||
self.p = "off"
|
||||
self.d = 100
|
||||
self.b = 127
|
||||
self.c = [(255, 255, 255)]
|
||||
self.a = True
|
||||
self.n1 = 0
|
||||
self.n2 = 0
|
||||
self.n3 = 0
|
||||
self.n4 = 0
|
||||
self.n5 = 0
|
||||
self.n6 = 0
|
||||
self.bg = (0, 0, 0)
|
||||
|
||||
# Override defaults with provided data
|
||||
self.edit(data)
|
||||
|
||||
def edit(self, data=None):
|
||||
if not data:
|
||||
return False
|
||||
aliases = {
|
||||
"pattern": "p",
|
||||
"colors": "c",
|
||||
"delay": "d",
|
||||
"brightness": "b",
|
||||
"auto": "a",
|
||||
"background": "bg",
|
||||
"mode": "n6",
|
||||
}
|
||||
int_fields = {"d", "b", "n1", "n2", "n3", "n4", "n5", "n6"}
|
||||
allowed_fields = {"p", "c", "d", "b", "a", "bg", "n1", "n2", "n3", "n4", "n5", "n6"}
|
||||
for key, value in data.items():
|
||||
if key == "reverse":
|
||||
try:
|
||||
if isinstance(value, bool):
|
||||
self.n5 = 1 if value else 0
|
||||
elif isinstance(value, (int, float)):
|
||||
self.n5 = 1 if int(value) else 0
|
||||
elif isinstance(value, str):
|
||||
lowered = value.lower()
|
||||
self.n5 = 1 if lowered in ("true", "1", "yes", "on") else 0
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
continue
|
||||
key = aliases.get(key, key)
|
||||
if key not in allowed_fields:
|
||||
continue
|
||||
if key in int_fields:
|
||||
try:
|
||||
parsed = int(value)
|
||||
if key == "b":
|
||||
parsed = max(0, min(255, parsed))
|
||||
elif key in ("d", "n1", "n2", "n3", "n4", "n5", "n6"):
|
||||
parsed = max(0, parsed)
|
||||
setattr(self, key, parsed)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
elif key == "a":
|
||||
if isinstance(value, bool):
|
||||
self.a = value
|
||||
elif isinstance(value, int):
|
||||
self.a = bool(value)
|
||||
elif isinstance(value, str):
|
||||
lowered = value.lower()
|
||||
if lowered in ("true", "1", "yes", "on"):
|
||||
self.a = True
|
||||
elif lowered in ("false", "0", "no", "off"):
|
||||
self.a = False
|
||||
elif key == "c":
|
||||
if isinstance(value, (list, tuple)):
|
||||
self.c = value
|
||||
elif key == "bg":
|
||||
if isinstance(value, str) and value.startswith("#") and len(value) == 7:
|
||||
try:
|
||||
self.bg = (
|
||||
int(value[1:3], 16),
|
||||
int(value[3:5], 16),
|
||||
int(value[5:7], 16),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
elif isinstance(value, (list, tuple)) and len(value) == 3:
|
||||
try:
|
||||
self.bg = tuple(max(0, min(255, int(x))) for x in value)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
else:
|
||||
setattr(self, key, value)
|
||||
return True
|
||||
|
||||
@property
|
||||
def pattern(self):
|
||||
return self.p
|
||||
|
||||
@pattern.setter
|
||||
def pattern(self, value):
|
||||
self.p = value
|
||||
|
||||
@property
|
||||
def delay(self):
|
||||
return self.d
|
||||
|
||||
@delay.setter
|
||||
def delay(self, value):
|
||||
self.d = value
|
||||
|
||||
@property
|
||||
def brightness(self):
|
||||
return self.b
|
||||
|
||||
@brightness.setter
|
||||
def brightness(self, value):
|
||||
self.b = value
|
||||
|
||||
@property
|
||||
def colors(self):
|
||||
return self.c
|
||||
|
||||
@colors.setter
|
||||
def colors(self, value):
|
||||
self.c = value
|
||||
|
||||
@property
|
||||
def auto(self):
|
||||
return self.a
|
||||
|
||||
@auto.setter
|
||||
def auto(self, value):
|
||||
self.a = value
|
||||
|
||||
def background_or(self, colors=None, default=(0, 0, 0)):
|
||||
bg = getattr(self, "bg", None)
|
||||
if isinstance(bg, (list, tuple)) and len(bg) == 3:
|
||||
try:
|
||||
return tuple(max(0, min(255, int(x))) for x in bg)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return default
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"p": self.p,
|
||||
"d": self.d,
|
||||
"b": self.b,
|
||||
"c": self.c,
|
||||
"a": self.a,
|
||||
"bg": self.bg,
|
||||
"n1": self.n1,
|
||||
"n2": self.n2,
|
||||
"n3": self.n3,
|
||||
"n4": self.n4,
|
||||
"n5": self.n5,
|
||||
"n6": self.n6,
|
||||
}
|
||||
-324
@@ -1,324 +0,0 @@
|
||||
from machine import Pin
|
||||
from neopixel import NeoPixel
|
||||
from preset import Preset
|
||||
from utils import convert_and_reorder_colors
|
||||
import json
|
||||
import sys
|
||||
import utime
|
||||
try:
|
||||
import uos as os
|
||||
except ImportError:
|
||||
import os
|
||||
|
||||
MAX_PRESETS = 32
|
||||
|
||||
# Tests set this so pattern import can feed the 10s watchdog.
|
||||
load_wdt = None
|
||||
|
||||
|
||||
class Presets:
|
||||
def __init__(self, pin, num_leds):
|
||||
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
|
||||
self.num_leds = num_leds
|
||||
self.step = 0
|
||||
# Global brightness (0–255), controlled via ESPNow {"b": <value>}
|
||||
self.b = 255
|
||||
# Ceiling for the effective brightness (0–255): neither the global nor a preset's brightness goes above it
|
||||
self.max_b = 255
|
||||
self.reversed = False
|
||||
|
||||
self.generator = None
|
||||
self.presets = {}
|
||||
self.selected = None
|
||||
|
||||
self.reload_patterns()
|
||||
|
||||
def reload_patterns(self):
|
||||
# Register built-in methods first, then discovered pattern classes
|
||||
self.patterns = {
|
||||
"off": self.off,
|
||||
"on": self.on,
|
||||
"blink": self.blink,
|
||||
}
|
||||
self.patterns.update(self._load_dynamic_patterns())
|
||||
|
||||
def _load_dynamic_patterns(self):
|
||||
loaded = {}
|
||||
try:
|
||||
files = os.listdir("patterns")
|
||||
except OSError:
|
||||
return loaded
|
||||
|
||||
for filename in files:
|
||||
if load_wdt is not None:
|
||||
load_wdt.feed()
|
||||
if not filename.endswith(".py") or filename in ("__init__.py", "main.py"):
|
||||
continue
|
||||
module_basename = filename[:-3]
|
||||
module_name = "patterns." + module_basename
|
||||
try:
|
||||
if module_name in sys.modules:
|
||||
del sys.modules[module_name]
|
||||
module = __import__(module_name, None, None, ["*"])
|
||||
except Exception as e:
|
||||
print("Pattern import failed:", module_name, e)
|
||||
continue
|
||||
|
||||
pattern_class = None
|
||||
for attr_name in dir(module):
|
||||
attr = getattr(module, attr_name)
|
||||
# Pick the first class in the module that exposes run()
|
||||
if isinstance(attr, type) and hasattr(attr, "run"):
|
||||
pattern_class = attr
|
||||
break
|
||||
|
||||
if pattern_class is None:
|
||||
continue
|
||||
|
||||
try:
|
||||
loaded[module_basename] = pattern_class(self).run
|
||||
except Exception as e:
|
||||
print("Pattern init failed:", module_name, e)
|
||||
|
||||
self._apply_pattern_aliases(loaded)
|
||||
return loaded
|
||||
|
||||
def _apply_pattern_aliases(self, loaded):
|
||||
"""Legacy pattern ids -> merged implementations (same generator)."""
|
||||
aliases = (
|
||||
("rainbow", "colour_cycle"),
|
||||
("gradient_scroll", "colour_cycle"),
|
||||
("meteor_rain", "meteor"),
|
||||
("comet_dual", "meteor"),
|
||||
("scanner", "meteor"),
|
||||
("snowfall", "particles"),
|
||||
("starfall", "particles"),
|
||||
("sparkle_trail", "sparkle"),
|
||||
("ice_sparkle", "sparkle"),
|
||||
("fireflies", "sparkle"),
|
||||
("marquee", "chase"),
|
||||
("northern_wave", "aurora"),
|
||||
)
|
||||
for old, new in aliases:
|
||||
if new in loaded and old not in loaded:
|
||||
loaded[old] = loaded[new]
|
||||
|
||||
def save(self):
|
||||
"""Save the presets to a file."""
|
||||
with open("presets.json", "w") as f:
|
||||
json.dump({name: preset.to_dict() for name, preset in self.presets.items()}, f)
|
||||
return True
|
||||
|
||||
def load(self, settings=None):
|
||||
"""Load presets from a file.
|
||||
|
||||
`settings` is used to convert hex strings in `c` to RGB tuples and apply
|
||||
the device's colour order (same as ESPNow receive). If omitted, RGB order
|
||||
is assumed.
|
||||
"""
|
||||
try:
|
||||
with open("presets.json", "r") as f:
|
||||
data = json.load(f)
|
||||
except OSError:
|
||||
# Create an empty presets file if missing
|
||||
self.presets = {}
|
||||
self.save()
|
||||
return True
|
||||
|
||||
order = settings if settings is not None else "rgb"
|
||||
self.presets = {}
|
||||
for name, preset_data in data.items():
|
||||
if len(self.presets) >= MAX_PRESETS:
|
||||
print("Preset limit reached on load:", MAX_PRESETS)
|
||||
break
|
||||
color_key = "c" if "c" in preset_data else ("colors" if "colors" in preset_data else None)
|
||||
if color_key is not None:
|
||||
preset_data[color_key] = convert_and_reorder_colors(
|
||||
preset_data[color_key], order
|
||||
)
|
||||
self.presets[name] = Preset(preset_data)
|
||||
return True
|
||||
|
||||
def edit(self, name, data):
|
||||
"""Create or update a preset with the given name."""
|
||||
if name in self.presets:
|
||||
# Update existing preset
|
||||
was_auto = self.presets[name].a
|
||||
self.presets[name].edit(data)
|
||||
# Editing the live preset: auto still re-selects (one tick) so the strip
|
||||
# restarts without a separate select message (controller often sends both).
|
||||
# Manual must NOT call select() here — presets-only pushes (e.g. zone sequence
|
||||
# arming the first step) would otherwise run select's first tick and consume a
|
||||
# beat/step. Manual advances only on explicit select from the controller.
|
||||
if self.selected == name:
|
||||
preset = self.presets[name]
|
||||
if preset.a:
|
||||
self.step = 0
|
||||
self.generator = None
|
||||
self.fill((0, 0, 0))
|
||||
self.select(name)
|
||||
elif was_auto:
|
||||
self.step = 0
|
||||
self.generator = None
|
||||
self.fill((0, 0, 0))
|
||||
else:
|
||||
if len(self.presets) >= MAX_PRESETS and name not in ("on", "off"):
|
||||
print("Preset limit reached:", MAX_PRESETS)
|
||||
return False
|
||||
# Create new preset
|
||||
self.presets[name] = Preset(data)
|
||||
return True
|
||||
|
||||
def delete(self, name):
|
||||
if name in self.presets:
|
||||
del self.presets[name]
|
||||
return True
|
||||
return False
|
||||
|
||||
def delete_all(self):
|
||||
self.presets = {}
|
||||
self.generator = None
|
||||
self.selected = None
|
||||
return True
|
||||
|
||||
def tick(self):
|
||||
if self.generator is None:
|
||||
return
|
||||
try:
|
||||
next(self.generator)
|
||||
except StopIteration:
|
||||
self.generator = None
|
||||
except Exception as e:
|
||||
print(f"Error in tick: {e}")
|
||||
self.generator = None
|
||||
|
||||
def beat(self):
|
||||
"""Step the selected pattern once; same effect as re-selecting it, without the message."""
|
||||
name = self.selected
|
||||
if name in self.presets:
|
||||
preset = self.presets[name]
|
||||
if preset.p in self.patterns:
|
||||
self.generator = self.patterns[preset.p](preset)
|
||||
|
||||
def select(self, preset_name, step=None):
|
||||
# Auto-create simple built-in presets for common names on first use
|
||||
if preset_name not in self.presets and preset_name in ("on", "off"):
|
||||
if preset_name == "on":
|
||||
self.presets[preset_name] = Preset({"p": "on"})
|
||||
else:
|
||||
self.presets[preset_name] = Preset({"p": "off"})
|
||||
|
||||
if preset_name in self.presets:
|
||||
preset = self.presets[preset_name]
|
||||
if preset.p in self.patterns:
|
||||
if preset.p == "off":
|
||||
self.generator = None
|
||||
self.step = 0
|
||||
self.fill((0, 0, 0))
|
||||
self.selected = preset_name
|
||||
return True
|
||||
# If re-selecting the same preset before the main loop has tick()'d the
|
||||
# previous frame, run one pending tick so step stays in sync.
|
||||
if (
|
||||
preset_name == self.selected
|
||||
and self.generator is not None
|
||||
):
|
||||
self.tick()
|
||||
# Set step value if explicitly provided
|
||||
if step is not None:
|
||||
self.step = step
|
||||
elif self.selected != preset_name:
|
||||
self.step = 0
|
||||
self.generator = self.patterns[preset.p](preset)
|
||||
self.selected = preset_name # Store the preset name, not the object
|
||||
self.tick()
|
||||
return True
|
||||
print("select failed: pattern not found for preset", preset_name, "pattern=", preset.p)
|
||||
return False
|
||||
print("select failed: preset not found", preset_name)
|
||||
# If preset doesn't exist or pattern not found, indicate failure
|
||||
return False
|
||||
|
||||
def update_num_leds(self, pin, num_leds):
|
||||
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
|
||||
self.num_leds = num_leds
|
||||
|
||||
def is_reversed(self, preset):
|
||||
from patterns.pattern_direction import is_reversed as _is_reversed
|
||||
|
||||
return _is_reversed(preset, self)
|
||||
|
||||
def led_i(self, preset, logical_index):
|
||||
from patterns.pattern_direction import led_i as _led_i
|
||||
|
||||
return _led_i(self, preset, logical_index)
|
||||
|
||||
def set(self, preset, logical_index, color):
|
||||
from patterns.pattern_direction import set_led
|
||||
|
||||
set_led(self, preset, logical_index, color)
|
||||
|
||||
def signed(self, preset, value):
|
||||
from patterns.pattern_direction import signed as _signed
|
||||
|
||||
return _signed(preset, value, self)
|
||||
|
||||
def apply_brightness(self, color, brightness_override=None):
|
||||
# Combine per-preset brightness (override) with global brightness self.b
|
||||
local = brightness_override if brightness_override is not None else 255
|
||||
# Scale preset brightness by global brightness
|
||||
effective_brightness = min(int(local * self.b / 255), self.max_b)
|
||||
return tuple(int(c * effective_brightness / 255) for c in color)
|
||||
|
||||
def fill(self, color=None):
|
||||
fill_color = color if color is not None else (0, 0, 0)
|
||||
for i in range(self.num_leds):
|
||||
self.n[i] = fill_color
|
||||
self.n.write()
|
||||
|
||||
def off(self, preset=None):
|
||||
self.fill((0, 0, 0))
|
||||
|
||||
def on(self, preset):
|
||||
colors = preset.c
|
||||
color = colors[0] if colors else (255, 255, 255)
|
||||
while True:
|
||||
self.fill(self.apply_brightness(color, preset.b))
|
||||
yield
|
||||
|
||||
def blink(self, preset):
|
||||
"""Built-in blink (used by controller identify); no patterns/ deploy required."""
|
||||
colors = preset.c if preset.c else [(255, 255, 255)]
|
||||
bg_color = self.apply_brightness(preset.background_or(colors), preset.b)
|
||||
color_index = 0
|
||||
delay_ms = max(1, int(preset.d))
|
||||
period = delay_ms * 2
|
||||
now = utime.ticks_ms()
|
||||
# Phase-lock to wall time so group identify (broadcast select) stays in sync even
|
||||
# when devices process the packet on different main-loop iterations.
|
||||
phase = now % period if period else 0
|
||||
state = phase < delay_ms
|
||||
last_update = utime.ticks_add(now, -phase)
|
||||
if state:
|
||||
base = colors[color_index % len(colors)]
|
||||
self.fill(self.apply_brightness(base, preset.b))
|
||||
color_index += 1
|
||||
else:
|
||||
self.fill(bg_color)
|
||||
while True:
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_update) >= delay_ms:
|
||||
if state:
|
||||
base = colors[color_index % len(colors)]
|
||||
self.fill(self.apply_brightness(base, preset.b))
|
||||
color_index += 1
|
||||
else:
|
||||
self.fill(bg_color)
|
||||
state = not state
|
||||
last_update = utime.ticks_add(last_update, delay_ms)
|
||||
yield
|
||||
|
||||
|
||||
def run_tick(presets):
|
||||
"""Advance one animation frame (standalone tests / mpremote demos)."""
|
||||
presets.tick()
|
||||
@@ -1,17 +0,0 @@
|
||||
"""Install a builtins.print wrapper that prefixes each line with uptime (ms).
|
||||
|
||||
Import this module before other led-driver imports that print (e.g. first in main).
|
||||
"""
|
||||
|
||||
import builtins
|
||||
import utime
|
||||
|
||||
_original_print = builtins.print
|
||||
|
||||
|
||||
def _timestamped_print(*args, **kwargs):
|
||||
ts = utime.ticks_ms()
|
||||
return _original_print("[%d]" % ts, *args, **kwargs)
|
||||
|
||||
|
||||
builtins.print = _timestamped_print
|
||||
@@ -1,12 +0,0 @@
|
||||
class RuntimeState:
|
||||
def __init__(self):
|
||||
self.hello = True
|
||||
self.ws_client_count = 0
|
||||
|
||||
def ws_connected(self):
|
||||
self.ws_client_count += 1
|
||||
self.hello = False
|
||||
|
||||
def ws_disconnected(self):
|
||||
self.ws_client_count = max(0, self.ws_client_count - 1)
|
||||
self.hello = self.ws_client_count == 0
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
import json
|
||||
import ubinascii
|
||||
import machine
|
||||
import network
|
||||
|
||||
WIFI_CHANNEL_DEFAULT = 5
|
||||
|
||||
class Settings(dict):
|
||||
SETTINGS_FILE = "/settings.json"
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.load() # Load settings from file during initialization
|
||||
self.color_order = self.get_color_order(self["color_order"])
|
||||
|
||||
def set_defaults(self):
|
||||
|
||||
self["led_pin"] = 10
|
||||
self["num_leds"] = 200
|
||||
|
||||
self["color_order"] = "grb"
|
||||
|
||||
sta = network.WLAN(network.STA_IF)
|
||||
sta.active(True)
|
||||
#use led-mac for name
|
||||
mac = sta.config("mac")
|
||||
mac = ubinascii.hexlify(mac).decode().lower()
|
||||
self["name"] = "led-" + mac
|
||||
|
||||
self["debug"] = False
|
||||
self["default"] = "on"
|
||||
self["last_preset"] = ""
|
||||
# Power-on: "default" | "last" | "off"
|
||||
self["startup_mode"] = "default"
|
||||
self["brightness"] = 32
|
||||
|
||||
self["wifi_channel"] = WIFI_CHANNEL_DEFAULT
|
||||
self["groups"] = []
|
||||
|
||||
|
||||
def save(self):
|
||||
try:
|
||||
j = json.dumps(self)
|
||||
with open(self.SETTINGS_FILE, 'w') as file:
|
||||
file.write(j)
|
||||
except Exception as e:
|
||||
print(f"Error saving settings: {e}")
|
||||
|
||||
def load(self):
|
||||
try:
|
||||
with open(self.SETTINGS_FILE, 'r') as file:
|
||||
loaded_settings = json.load(file)
|
||||
self.update(loaded_settings)
|
||||
old_recent = self.pop("recent_presets", None)
|
||||
if isinstance(old_recent, list) and old_recent and not self.get("last_preset"):
|
||||
for x in reversed(old_recent):
|
||||
if isinstance(x, str) and x.strip():
|
||||
self["last_preset"] = x.strip()
|
||||
break
|
||||
if x is not None:
|
||||
s = str(x).strip()
|
||||
if s:
|
||||
self["last_preset"] = s
|
||||
break
|
||||
except Exception as e:
|
||||
print(f"Error loading settings")
|
||||
self.set_defaults()
|
||||
self.save()
|
||||
|
||||
def get_color_order(self, color_order):
|
||||
"""Convert color order string to tuple of hex string indices."""
|
||||
color_orders = {
|
||||
"rgb": (1, 3, 5),
|
||||
"rbg": (1, 5, 3),
|
||||
"grb": (3, 1, 5),
|
||||
"gbr": (3, 5, 1),
|
||||
"brg": (5, 1, 3),
|
||||
"bgr": (5, 3, 1)
|
||||
}
|
||||
return color_orders.get(color_order.lower(), (1, 3, 5)) # Default to RGB
|
||||
|
||||
def get_rgb_channel_order(self, color_order=None):
|
||||
"""Convert color order string to RGB channel indices for reordering tuples.
|
||||
Returns tuple of channel indices: (r_channel, g_channel, b_channel)
|
||||
Example: 'grb' -> (1, 0, 2) means (G, R, B)"""
|
||||
if color_order is None:
|
||||
color_order = self.get("color_order", "rgb")
|
||||
color_order = color_order.lower()
|
||||
# Map hex string positions to RGB channel indices
|
||||
# Position 1 (R in hex) -> channel 0, Position 3 (G) -> channel 1, Position 5 (B) -> channel 2
|
||||
hex_to_channel = {1: 0, 3: 1, 5: 2}
|
||||
hex_indices = self.get_color_order(color_order)
|
||||
return tuple(hex_to_channel[pos] for pos in hex_indices)
|
||||
|
||||
# Example usage
|
||||
def main():
|
||||
settings = Settings()
|
||||
print(f"Number of LEDs: {settings['num_leds']}")
|
||||
settings['num_leds'] = 100
|
||||
print(f"Updated number of LEDs: {settings['num_leds']}")
|
||||
settings.save()
|
||||
|
||||
# Create a new Settings object to test loading
|
||||
new_settings = Settings()
|
||||
print(f"Loaded number of LEDs: {new_settings['num_leds']}")
|
||||
print(settings)
|
||||
|
||||
|
||||
|
||||
# Run the example
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,52 +0,0 @@
|
||||
import gc
|
||||
import machine
|
||||
import network
|
||||
import utime
|
||||
|
||||
from presets import Presets
|
||||
from settings import Settings
|
||||
from controller_messages import apply_startup_pattern
|
||||
|
||||
|
||||
def initialize_runtime():
|
||||
machine.freq(160000000)
|
||||
|
||||
settings = Settings()
|
||||
|
||||
wdt = machine.WDT(timeout=10000)
|
||||
wdt.feed()
|
||||
|
||||
gc.collect()
|
||||
|
||||
presets = Presets(settings["led_pin"], settings["num_leds"])
|
||||
presets.load(settings)
|
||||
presets.b = settings.get("brightness", 255)
|
||||
presets.max_b = settings.get("max_brightness", 255)
|
||||
presets.debug = bool(settings.get("debug", False))
|
||||
gc.collect()
|
||||
|
||||
apply_startup_pattern(settings, presets)
|
||||
|
||||
# On ESP32-C3, soft reboots can leave Wi-Fi driver state allocated.
|
||||
# Reset both interfaces and collect before bringing STA up.
|
||||
ap_if = network.WLAN(network.AP_IF)
|
||||
ap_if.active(False)
|
||||
sta_if = network.WLAN(network.STA_IF)
|
||||
if sta_if.active():
|
||||
sta_if.active(False)
|
||||
utime.sleep_ms(100)
|
||||
gc.collect()
|
||||
sta_if.active(True)
|
||||
sta_if.config(pm=network.WLAN.PM_NONE)
|
||||
sta_if.connect(settings["ssid"], settings["password"])
|
||||
while not sta_if.isconnected():
|
||||
utime.sleep(1)
|
||||
wdt.feed()
|
||||
|
||||
try:
|
||||
led_ip = sta_if.ifconfig()[0]
|
||||
except Exception:
|
||||
led_ip = "?"
|
||||
print("led-driver IP:", led_ip, " led-controller IP:", "(not connected)")
|
||||
|
||||
return settings, presets, wdt, sta_if
|
||||
@@ -1,58 +0,0 @@
|
||||
def convert_and_reorder_colors(colors, settings_or_color_order):
|
||||
"""Convert hex color strings to RGB tuples and reorder based on device color order.
|
||||
|
||||
Args:
|
||||
colors: List of colors, either hex strings like "#FF0000" or RGB tuples like (255, 0, 0)
|
||||
settings_or_color_order: Either a Settings object or a color_order string (e.g., "rgb", "grb")
|
||||
|
||||
Returns:
|
||||
List of RGB tuples reordered according to device color order
|
||||
"""
|
||||
# Get channel order from settings or color_order string
|
||||
if hasattr(settings_or_color_order, 'get_rgb_channel_order'):
|
||||
# It's a Settings object
|
||||
channel_order = settings_or_color_order.get_rgb_channel_order()
|
||||
elif isinstance(settings_or_color_order, str):
|
||||
# It's a color_order string, convert to channel order
|
||||
color_order = settings_or_color_order.lower()
|
||||
color_orders = {
|
||||
"rgb": (1, 3, 5),
|
||||
"rbg": (1, 5, 3),
|
||||
"grb": (3, 1, 5),
|
||||
"gbr": (3, 5, 1),
|
||||
"brg": (5, 1, 3),
|
||||
"bgr": (5, 3, 1)
|
||||
}
|
||||
hex_indices = color_orders.get(color_order, (1, 3, 5))
|
||||
# Map hex string positions to RGB channel indices
|
||||
hex_to_channel = {1: 0, 3: 1, 5: 2}
|
||||
channel_order = tuple(hex_to_channel[pos] for pos in hex_indices)
|
||||
else:
|
||||
# Assume it's already a channel order tuple
|
||||
channel_order = settings_or_color_order
|
||||
|
||||
converted_colors = []
|
||||
for color in colors:
|
||||
try:
|
||||
# Convert "#RRGGBB" to (R, G, B)
|
||||
if isinstance(color, str) and color.startswith("#") and len(color) == 7:
|
||||
r = int(color[1:3], 16)
|
||||
g = int(color[3:5], 16)
|
||||
b = int(color[5:7], 16)
|
||||
rgb = (r, g, b)
|
||||
elif isinstance(color, (list, tuple)) and len(color) == 3:
|
||||
# Already a tuple/list, just coerce and clamp.
|
||||
rgb = tuple(max(0, min(255, int(x))) for x in color)
|
||||
else:
|
||||
# Unknown format: ignore safely.
|
||||
continue
|
||||
|
||||
# Reorder based on device color order
|
||||
reordered = (rgb[channel_order[0]], rgb[channel_order[1]], rgb[channel_order[2]])
|
||||
converted_colors.append(reordered)
|
||||
except (TypeError, ValueError, IndexError):
|
||||
# Skip malformed color entries to avoid crashing pattern loops.
|
||||
continue
|
||||
if not converted_colors:
|
||||
converted_colors.append((255, 255, 255))
|
||||
return converted_colors
|
||||
@@ -1,36 +0,0 @@
|
||||
"""Expand short v1 wire keys to long names (MicroPython)."""
|
||||
|
||||
|
||||
K_PRESETS = "p"
|
||||
K_SELECT = "s"
|
||||
K_GROUPS = "g"
|
||||
K_SET_GROUPS = "sg"
|
||||
K_SAVE = "sv"
|
||||
K_DEFAULT = "df"
|
||||
K_DEVICE_CONFIG = "dc"
|
||||
K_CLEAR_PRESETS = "cp"
|
||||
K_MANIFEST = "mf"
|
||||
|
||||
_SHORT_TO_LONG = {
|
||||
K_PRESETS: "presets",
|
||||
K_SELECT: "select",
|
||||
K_GROUPS: "groups",
|
||||
K_SET_GROUPS: "set_groups",
|
||||
K_SAVE: "save",
|
||||
K_DEFAULT: "default",
|
||||
K_DEVICE_CONFIG: "device_config",
|
||||
K_CLEAR_PRESETS: "clear_presets",
|
||||
K_MANIFEST: "manifest",
|
||||
}
|
||||
|
||||
|
||||
def expand_v1(data):
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
out = dict(data)
|
||||
for short_key, long_key in _SHORT_TO_LONG.items():
|
||||
if short_key in data and long_key not in out:
|
||||
out[long_key] = data[short_key]
|
||||
if short_key in out:
|
||||
del out[short_key]
|
||||
return out
|
||||
-129
@@ -1,129 +0,0 @@
|
||||
"""STA connect helpers aligned with tests/test_wifi.py (status polling, fatal codes)."""
|
||||
|
||||
import gc
|
||||
import machine
|
||||
import utime
|
||||
import network
|
||||
|
||||
_CONNECT_TIMEOUT_S = 45
|
||||
_RETRY_DELAY_S = 2
|
||||
|
||||
|
||||
def _wifi_status_label(code):
|
||||
names = {
|
||||
getattr(network, "STAT_IDLE", 0): "idle",
|
||||
getattr(network, "STAT_CONNECTING", 1): "connecting",
|
||||
getattr(network, "STAT_WRONG_PASSWORD", -3): "wrong_password",
|
||||
getattr(network, "STAT_NO_AP_FOUND", -2): "no_ap_found",
|
||||
getattr(network, "STAT_CONNECT_FAIL", -1): "connect_fail",
|
||||
getattr(network, "STAT_GOT_IP", 3): "got_ip",
|
||||
}
|
||||
return names.get(code, str(code))
|
||||
|
||||
|
||||
# Only abort the wait loop immediately on wrong password. NO_AP_FOUND / CONNECT_FAIL are often
|
||||
# transient while the radio is still scanning (ESP32-C3 may report them before the AP appears).
|
||||
_ABORT_WAIT_IMMEDIATE = (
|
||||
getattr(network, "STAT_WRONG_PASSWORD", -3),
|
||||
)
|
||||
|
||||
|
||||
def _one_association_campaign(sta_if, ssid, password, wdt):
|
||||
"""disconnect → connect → wait until connected, wrong password, or timeout. Returns True if connected."""
|
||||
try:
|
||||
sta_if.disconnect()
|
||||
except Exception:
|
||||
pass
|
||||
utime.sleep_ms(200)
|
||||
try:
|
||||
sta_if.connect(ssid, password)
|
||||
except Exception as ex:
|
||||
print("wifi_sta: connect raised:", ex)
|
||||
return False
|
||||
|
||||
start = utime.time()
|
||||
last_status = None
|
||||
while not sta_if.isconnected():
|
||||
status = sta_if.status()
|
||||
if status != last_status:
|
||||
print("wifi_sta: status", status, _wifi_status_label(status))
|
||||
last_status = status
|
||||
if status in _ABORT_WAIT_IMMEDIATE:
|
||||
return False
|
||||
if utime.time() - start >= _CONNECT_TIMEOUT_S:
|
||||
print("wifi_sta: association timeout")
|
||||
return False
|
||||
utime.sleep(1)
|
||||
if wdt is not None:
|
||||
wdt.feed()
|
||||
return True
|
||||
|
||||
|
||||
def boot_sta(settings, wdt):
|
||||
"""Tear down and bring up STA. Call before large heap users (NeoPixel, patterns).
|
||||
|
||||
On ESP32-C3, soft reboots can leave the Wi-Fi driver allocated; init while the
|
||||
heap is still free. If re-init fails after a soft reboot, hard-reset once.
|
||||
"""
|
||||
sta_if = network.WLAN(network.STA_IF)
|
||||
try:
|
||||
if sta_if.active():
|
||||
try:
|
||||
sta_if.disconnect()
|
||||
except Exception:
|
||||
pass
|
||||
sta_if.active(False)
|
||||
except Exception:
|
||||
pass
|
||||
utime.sleep_ms(100)
|
||||
gc.collect()
|
||||
try:
|
||||
sta_if.active(True)
|
||||
except OSError as e:
|
||||
err = str(e)
|
||||
if "Out of Memory" in err or "WiFi" in err:
|
||||
if machine.reset_cause() == machine.SOFT_RESET:
|
||||
print("wifi_sta: init failed after soft reboot, hard reset:", err)
|
||||
machine.reset()
|
||||
raise
|
||||
sta_if.config(pm=network.WLAN.PM_NONE)
|
||||
ssid = settings.get("ssid") or ""
|
||||
if ssid:
|
||||
connect_until_up(sta_if, ssid, settings.get("password") or "", wdt)
|
||||
return sta_if
|
||||
|
||||
|
||||
def connect_until_up(sta_if, ssid, password, wdt):
|
||||
"""Boot: repeat campaigns until STA has a route (same strategy as tests/test_wifi.py)."""
|
||||
if not ssid:
|
||||
print("wifi_sta: no ssid in settings")
|
||||
return False
|
||||
attempt = 0
|
||||
while True:
|
||||
attempt += 1
|
||||
print("wifi_sta: boot attempt", attempt, "ssid=", repr(ssid))
|
||||
if _one_association_campaign(sta_if, ssid, password, wdt):
|
||||
try:
|
||||
print("wifi_sta: connected", sta_if.ifconfig()[0])
|
||||
except Exception:
|
||||
print("wifi_sta: connected")
|
||||
return True
|
||||
print("wifi_sta: retry in", _RETRY_DELAY_S, "s")
|
||||
for _ in range(_RETRY_DELAY_S):
|
||||
utime.sleep(1)
|
||||
if wdt is not None:
|
||||
wdt.feed()
|
||||
|
||||
|
||||
def try_reconnect(sta_if, ssid, password, wdt):
|
||||
"""Runtime: single association campaign after link loss; non-looping."""
|
||||
if not ssid:
|
||||
return False
|
||||
print("wifi_sta: reconnect")
|
||||
ok = _one_association_campaign(sta_if, ssid, password, wdt)
|
||||
if ok:
|
||||
try:
|
||||
print("wifi_sta: connected", sta_if.ifconfig()[0])
|
||||
except Exception:
|
||||
print("wifi_sta: connected")
|
||||
return ok
|
||||
-419
@@ -1,419 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Self-contained led-driver test runner for MicroPython/mpremote.
|
||||
|
||||
Run on device (from led-driver repo root)::
|
||||
|
||||
mpremote connect <port> run tests/all.py
|
||||
|
||||
Or via dev helper::
|
||||
|
||||
python dev.py <port> test
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import utime
|
||||
from machine import WDT
|
||||
|
||||
|
||||
def _bootstrap_import_path():
|
||||
"""Find ``settings`` / ``presets`` whether this file lives in ``tests/`` or ``:/``."""
|
||||
try:
|
||||
import uos as os
|
||||
except ImportError:
|
||||
import os
|
||||
|
||||
candidates = []
|
||||
try:
|
||||
here = __file__.rsplit("/", 1)[0]
|
||||
if here:
|
||||
candidates.append(here)
|
||||
parent = here.rsplit("/", 1)[0]
|
||||
if parent:
|
||||
candidates.append(parent)
|
||||
except NameError:
|
||||
pass
|
||||
candidates.extend([".", "..", "/"])
|
||||
for p in candidates:
|
||||
if p and p not in sys.path:
|
||||
sys.path.insert(0, p)
|
||||
|
||||
|
||||
_bootstrap_import_path()
|
||||
|
||||
from settings import Settings # noqa: E402
|
||||
from presets import Presets, run_tick # noqa: E402
|
||||
from preset import Preset # noqa: E402
|
||||
from utils import convert_and_reorder_colors # noqa: E402
|
||||
|
||||
|
||||
class _TestContext:
|
||||
def __init__(self):
|
||||
self.settings = Settings()
|
||||
self.settings["name"] = self.settings.get("name", "test_device")
|
||||
self.presets = Presets(self.settings["led_pin"], self.settings["num_leds"])
|
||||
self.presets.b = self.settings.get("brightness", 255)
|
||||
self.wdt = WDT(timeout=10000)
|
||||
|
||||
def tick_for_ms(self, duration_ms, sleep_ms=5):
|
||||
start = utime.ticks_ms()
|
||||
while utime.ticks_diff(utime.ticks_ms(), start) < duration_ms:
|
||||
self.wdt.feed()
|
||||
run_tick(self.presets)
|
||||
utime.sleep_ms(sleep_ms)
|
||||
|
||||
|
||||
def _pattern_loaded(ctx, pattern_id):
|
||||
return pattern_id in ctx.presets.patterns
|
||||
|
||||
|
||||
def _smoke_preset(ctx, name, data, ms=80):
|
||||
pattern_id = data.get("p") or data.get("pattern")
|
||||
if not _pattern_loaded(ctx, pattern_id):
|
||||
raise AssertionError("pattern not loaded: %s" % pattern_id)
|
||||
ctx.presets.edit(name, data)
|
||||
if not ctx.presets.select(name):
|
||||
raise AssertionError("select failed: %s" % name)
|
||||
ctx.tick_for_ms(ms)
|
||||
|
||||
|
||||
def _process_message(ctx, payload):
|
||||
"""Small test helper that mirrors the main message handling logic."""
|
||||
try:
|
||||
if isinstance(payload, (bytes, bytearray)):
|
||||
data = json.loads(payload)
|
||||
elif isinstance(payload, str):
|
||||
data = json.loads(payload)
|
||||
else:
|
||||
data = payload
|
||||
except (TypeError, ValueError):
|
||||
return "invalid_json"
|
||||
|
||||
if not isinstance(data, dict):
|
||||
return "invalid_shape"
|
||||
if data.get("v") != "1":
|
||||
return "wrong_version"
|
||||
|
||||
if "b" in data:
|
||||
try:
|
||||
ctx.presets.b = max(0, min(255, int(data["b"])))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
if isinstance(data.get("presets"), dict):
|
||||
for name, preset_data in data["presets"].items():
|
||||
if not isinstance(preset_data, dict):
|
||||
continue
|
||||
color_key = "c" if "c" in preset_data else ("colors" if "colors" in preset_data else None)
|
||||
if color_key is not None:
|
||||
try:
|
||||
preset_data[color_key] = convert_and_reorder_colors(
|
||||
preset_data[color_key], ctx.settings
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
ctx.presets.edit(name, preset_data)
|
||||
|
||||
if isinstance(data.get("select"), dict) and ctx.settings.get("name") in data["select"]:
|
||||
select_list = data["select"][ctx.settings.get("name")]
|
||||
if isinstance(select_list, list) and select_list:
|
||||
preset_name = select_list[0]
|
||||
step = select_list[1] if len(select_list) > 1 else None
|
||||
if isinstance(preset_name, str):
|
||||
ctx.presets.select(preset_name, step=step)
|
||||
|
||||
if "default" in data:
|
||||
default_name = data["default"]
|
||||
this_device_name = ctx.settings.get("name")
|
||||
this_device_name_norm = (
|
||||
this_device_name.strip().lower()
|
||||
if isinstance(this_device_name, str)
|
||||
else None
|
||||
)
|
||||
should_apply_default = True
|
||||
if "targets" in data:
|
||||
should_apply_default = False
|
||||
targets = data.get("targets")
|
||||
if isinstance(targets, list) and this_device_name_norm:
|
||||
normalized_targets = [
|
||||
target.strip().lower()
|
||||
for target in targets
|
||||
if isinstance(target, str) and target.strip()
|
||||
]
|
||||
should_apply_default = this_device_name_norm in normalized_targets
|
||||
if (
|
||||
should_apply_default
|
||||
and isinstance(default_name, str)
|
||||
and default_name
|
||||
and default_name in ctx.presets.presets
|
||||
):
|
||||
ctx.settings["default"] = default_name
|
||||
|
||||
if "save" in data:
|
||||
ctx.presets.save()
|
||||
|
||||
return "ok"
|
||||
|
||||
|
||||
def test_invalid_messages_do_not_crash():
|
||||
ctx = _TestContext()
|
||||
cases = [
|
||||
b"{not-json",
|
||||
"[]",
|
||||
json.dumps({"v": "2"}),
|
||||
json.dumps({"v": "1", "presets": ["bad"]}),
|
||||
json.dumps({"v": "1", "select": {"test_device": "not-list"}}),
|
||||
json.dumps({"v": "1", "presets": {"x": {"c": ["#GG0000"]}}}),
|
||||
]
|
||||
for payload in cases:
|
||||
_process_message(ctx, payload)
|
||||
ctx.wdt.feed()
|
||||
|
||||
|
||||
def test_preset_edit_sanitization():
|
||||
ctx = _TestContext()
|
||||
ctx.presets.edit(
|
||||
"sanitize",
|
||||
{
|
||||
"pattern": "blink",
|
||||
"delay": "120",
|
||||
"brightness": "999",
|
||||
"auto": "false",
|
||||
"n1": "-5",
|
||||
"n2": "7",
|
||||
"unknown_field": "ignored",
|
||||
},
|
||||
)
|
||||
p = ctx.presets.presets["sanitize"]
|
||||
assert p.p == "blink"
|
||||
assert p.d == 120
|
||||
assert p.b == 255
|
||||
assert p.a is False
|
||||
assert p.n1 == 0
|
||||
assert p.n2 == 7
|
||||
assert not hasattr(p, "unknown_field")
|
||||
|
||||
|
||||
def test_preset_mode_alias_maps_to_n6():
|
||||
ctx = _TestContext()
|
||||
ctx.presets.edit(
|
||||
"rainbow_mode",
|
||||
{"pattern": "colour_cycle", "mode": 1, "d": 50, "n1": 2, "a": True},
|
||||
)
|
||||
p = ctx.presets.presets["rainbow_mode"]
|
||||
assert p.p == "colour_cycle"
|
||||
assert p.n6 == 1
|
||||
|
||||
|
||||
def test_style_mode_and_legacy_aliases():
|
||||
from patterns.pattern_modes import style_mode
|
||||
|
||||
p = Preset({"p": "colour_cycle", "mode": 0, "d": 50, "c": [(255, 0, 0)]})
|
||||
assert style_mode(p, 0, {"rainbow": 1}) == 0
|
||||
|
||||
legacy = Preset({"p": "rainbow", "d": 50, "c": [(255, 0, 0)]})
|
||||
assert style_mode(legacy, 0, {"rainbow": 1}) == 1
|
||||
|
||||
ctx = _TestContext()
|
||||
legacy_ids = (
|
||||
"rainbow",
|
||||
"meteor_rain",
|
||||
"snowfall",
|
||||
"sparkle_trail",
|
||||
"marquee",
|
||||
"northern_wave",
|
||||
)
|
||||
for lid in legacy_ids:
|
||||
if not _pattern_loaded(ctx, lid):
|
||||
raise AssertionError("legacy alias not registered: %s" % lid)
|
||||
|
||||
|
||||
def test_colour_conversion_and_transition():
|
||||
ctx = _TestContext()
|
||||
msg = {
|
||||
"v": "1",
|
||||
"presets": {
|
||||
"fade": {
|
||||
"p": "transition",
|
||||
"c": ["#ff0000", "#00ff00"],
|
||||
"d": 80,
|
||||
"a": True,
|
||||
}
|
||||
},
|
||||
"select": {ctx.settings["name"]: ["fade"]},
|
||||
}
|
||||
result = _process_message(ctx, msg)
|
||||
assert result == "ok"
|
||||
assert ctx.presets.selected == "fade"
|
||||
ctx.tick_for_ms(250)
|
||||
|
||||
|
||||
def test_pattern_smoke():
|
||||
ctx = _TestContext()
|
||||
cases = {
|
||||
"t_on": {"p": "on", "c": [(16, 8, 4)]},
|
||||
"t_off": {"p": "off"},
|
||||
"t_blink": {"p": "blink", "c": [(255, 0, 0)], "d": 20},
|
||||
"t_colour_cycle": {"p": "colour_cycle", "n6": 0, "d": 5, "n1": 2, "c": [(255, 0, 0), (0, 255, 0)]},
|
||||
"t_chase": {"p": "chase", "c": [(255, 0, 0), (0, 0, 255)], "n1": 3, "n2": 2, "n3": 1, "n4": 1, "d": 20},
|
||||
}
|
||||
for name, data in cases.items():
|
||||
_smoke_preset(ctx, name, data, ms=100)
|
||||
|
||||
|
||||
def test_merged_pattern_modes():
|
||||
"""Smoke each style (``n6`` / ``mode``) for merged multi-mode patterns."""
|
||||
ctx = _TestContext()
|
||||
colors = [(200, 220, 255), (255, 180, 80)]
|
||||
cases = (
|
||||
("mc_grad", "colour_cycle", {"p": "colour_cycle", "n6": 0, "n1": 2, "d": 8, "c": colors}),
|
||||
("mc_wheel", "colour_cycle", {"p": "colour_cycle", "mode": 1, "n1": 2, "d": 8}),
|
||||
("chase_std", "chase", {"p": "chase", "n6": 0, "n1": 2, "n2": 2, "n3": 1, "n4": 1, "d": 15, "c": colors}),
|
||||
("chase_marq", "chase", {"p": "chase", "n6": 1, "n1": 3, "n2": 2, "n3": 1, "d": 15, "c": colors}),
|
||||
("meteor_0", "meteor", {"p": "meteor", "n6": 0, "n1": 4, "n2": 2, "n3": 8, "d": 10, "c": colors}),
|
||||
("meteor_1", "meteor", {"p": "meteor", "n6": 1, "n1": 3, "n2": 2, "n3": 4, "d": 10, "c": colors}),
|
||||
("part_0", "particles", {"p": "particles", "n6": 0, "n1": 4, "n2": 1, "d": 10, "c": colors}),
|
||||
("part_1", "particles", {"p": "particles", "mode": 1, "n1": 3, "n2": 1, "n3": 4, "d": 10, "c": colors}),
|
||||
("spark_0", "sparkle", {"p": "sparkle", "n6": 0, "n1": 4, "n2": 6, "d": 10, "c": colors}),
|
||||
("spark_1", "sparkle", {"p": "sparkle", "n6": 1, "n1": 3, "n2": 4, "n3": 2, "d": 10, "c": colors}),
|
||||
("aurora_0", "aurora", {"p": "aurora", "n6": 0, "n1": 3, "n2": 2, "n3": 0, "d": 12, "c": colors}),
|
||||
("aurora_1", "aurora", {"p": "aurora", "mode": 1, "n1": 8, "n2": 2, "n3": 1, "d": 12, "c": colors}),
|
||||
)
|
||||
for name, pattern_id, data in cases:
|
||||
if not _pattern_loaded(ctx, pattern_id):
|
||||
continue
|
||||
_smoke_preset(ctx, name, data, ms=60)
|
||||
|
||||
legacy_smoke = (
|
||||
("leg_rainbow", "rainbow", {"p": "rainbow", "d": 8, "n1": 2}),
|
||||
("leg_ice", "ice_sparkle", {"p": "ice_sparkle", "n1": 3, "n2": 2, "n3": 2, "d": 10, "c": colors}),
|
||||
("leg_wave", "northern_wave", {"p": "northern_wave", "n1": 6, "n2": 2, "n3": 1, "d": 12, "c": colors}),
|
||||
("leg_star", "starfall", {"p": "starfall", "n1": 3, "n2": 1, "n3": 3, "d": 10, "c": colors}),
|
||||
)
|
||||
for name, pattern_id, data in legacy_smoke:
|
||||
if not _pattern_loaded(ctx, pattern_id):
|
||||
continue
|
||||
_smoke_preset(ctx, name, data, ms=60)
|
||||
|
||||
|
||||
def test_patterns_do_not_use_blocking_sleep():
|
||||
try:
|
||||
import uos as os
|
||||
except ImportError:
|
||||
import os
|
||||
|
||||
pattern_dir = "patterns"
|
||||
offenders = []
|
||||
try:
|
||||
files = os.listdir(pattern_dir)
|
||||
except OSError:
|
||||
raise AssertionError("patterns directory is missing")
|
||||
|
||||
skip = frozenset(("__init__.py", "main.py", "pattern_modes.py"))
|
||||
for filename in files:
|
||||
if not filename.endswith(".py") or filename in skip:
|
||||
continue
|
||||
path = pattern_dir + "/" + filename
|
||||
try:
|
||||
with open(path, "r") as f:
|
||||
src = f.read()
|
||||
except OSError:
|
||||
offenders.append(filename + " (unreadable)")
|
||||
continue
|
||||
|
||||
if (
|
||||
"utime.sleep(" in src
|
||||
or "utime.sleep_ms(" in src
|
||||
or "time.sleep(" in src
|
||||
or "time.sleep_ms(" in src
|
||||
):
|
||||
offenders.append(filename)
|
||||
|
||||
assert not offenders, "blocking sleep found in patterns: %s" % ", ".join(offenders)
|
||||
|
||||
|
||||
def test_default_requires_existing_preset():
|
||||
ctx = _TestContext()
|
||||
_process_message(ctx, {"v": "1", "default": "missing"})
|
||||
assert ctx.settings.get("default") != "missing"
|
||||
|
||||
ctx.presets.edit("exists", {"p": "on"})
|
||||
_process_message(ctx, {"v": "1", "default": "exists"})
|
||||
assert ctx.settings.get("default") == "exists"
|
||||
|
||||
|
||||
def test_default_targets_gate_by_device_name():
|
||||
ctx = _TestContext()
|
||||
ctx.settings["name"] = "a"
|
||||
ctx.presets.edit("targeted", {"p": "on"})
|
||||
ctx.settings["default"] = "baseline"
|
||||
|
||||
_process_message(
|
||||
ctx,
|
||||
{"v": "1", "default": "targeted", "targets": ["11"]},
|
||||
)
|
||||
assert ctx.settings.get("default") == "baseline"
|
||||
|
||||
_process_message(
|
||||
ctx,
|
||||
{"v": "1", "default": "targeted", "targets": [" A "]},
|
||||
)
|
||||
assert ctx.settings.get("default") == "targeted"
|
||||
|
||||
|
||||
def test_save_and_load_roundtrip():
|
||||
try:
|
||||
import uos as os
|
||||
except ImportError:
|
||||
import os
|
||||
|
||||
ctx = _TestContext()
|
||||
ctx.presets.edit(
|
||||
"persist",
|
||||
{"p": "blink", "c": [(1, 2, 3), (4, 5, 6)], "d": 77, "b": 123, "a": False},
|
||||
)
|
||||
assert ctx.presets.save()
|
||||
|
||||
reloaded = Presets(ctx.settings["led_pin"], ctx.settings["num_leds"])
|
||||
assert reloaded.load(ctx.settings)
|
||||
p = reloaded.presets.get("persist")
|
||||
assert p is not None
|
||||
assert p.p == "blink"
|
||||
assert p.d == 77
|
||||
assert p.b == 123
|
||||
assert p.a is False
|
||||
assert p.c == [(1, 2, 3), (4, 5, 6)]
|
||||
|
||||
try:
|
||||
os.remove("presets.json")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def run_all():
|
||||
tests = [
|
||||
test_invalid_messages_do_not_crash,
|
||||
test_preset_edit_sanitization,
|
||||
test_preset_mode_alias_maps_to_n6,
|
||||
test_style_mode_and_legacy_aliases,
|
||||
test_colour_conversion_and_transition,
|
||||
test_pattern_smoke,
|
||||
test_merged_pattern_modes,
|
||||
test_patterns_do_not_use_blocking_sleep,
|
||||
test_default_requires_existing_preset,
|
||||
test_default_targets_gate_by_device_name,
|
||||
test_save_and_load_roundtrip,
|
||||
]
|
||||
print("=" * 56)
|
||||
print("led-driver self-contained tests")
|
||||
print("=" * 56)
|
||||
for test_func in tests:
|
||||
print("Running %s ..." % test_func.__name__)
|
||||
test_func()
|
||||
print(" PASS")
|
||||
print("-" * 56)
|
||||
print("All tests passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_all()
|
||||
@@ -1,169 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Send blink preset + select to a driver via the ESP-NOW bridge WebSocket.
|
||||
|
||||
Pairs with the on-device demo ``tests/patterns/blink.py``: same preset slot,
|
||||
pattern, and colours; this script reaches the driver over ESP-NOW through
|
||||
``espnow-sender`` (devices envelope, not legacy broadcast JSON).
|
||||
|
||||
Run from the **led-controller** repo (needs ``websockets`` in Pipenv)::
|
||||
|
||||
pipenv run python led-driver/tests/bridge_ws_blink.py
|
||||
|
||||
pipenv run python led-driver/tests/bridge_ws_blink.py \\
|
||||
--url ws://192.168.4.1/ws --mac 18:8b:0e:15:60:a8
|
||||
|
||||
From **led-driver** (if Pipenv/env is the parent project)::
|
||||
|
||||
pipenv run python tests/bridge_ws_blink.py --dry-run
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
# led-driver/tests -> led-driver -> led-controller
|
||||
LED_DRIVER_ROOT = Path(__file__).resolve().parents[1]
|
||||
PROJECT_ROOT = LED_DRIVER_ROOT.parent
|
||||
|
||||
|
||||
def _load_bridge_url(explicit: Optional[str]) -> str:
|
||||
if explicit and explicit.strip():
|
||||
return explicit.strip()
|
||||
for path in (PROJECT_ROOT / "settings.json", LED_DRIVER_ROOT / "settings.json"):
|
||||
if not path.is_file():
|
||||
continue
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
url = str(data.get("bridge_ws_url") or "").strip()
|
||||
if url:
|
||||
return url
|
||||
except (OSError, json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return "ws://192.168.4.1/ws"
|
||||
|
||||
|
||||
def _format_mac(mac: str) -> str:
|
||||
s = re.sub(r"[^0-9a-fA-F]", "", str(mac or "").strip().lower())
|
||||
if len(s) != 12 or not re.fullmatch(r"[0-9a-f]{12}", s):
|
||||
raise ValueError("MAC must be 12 hex digits (e.g. 188b0e1560a8)")
|
||||
return ":".join(s[i : i + 2] for i in range(0, 12, 2))
|
||||
|
||||
|
||||
def build_blink_envelope(
|
||||
mac: str,
|
||||
*,
|
||||
preset_id: str = "2",
|
||||
delay_ms: int = 200,
|
||||
brightness: int = 64,
|
||||
) -> Dict[str, Any]:
|
||||
"""v1 devices envelope: preset body + list select (same shape as the Pi)."""
|
||||
body = {
|
||||
"p": {
|
||||
preset_id: {
|
||||
"p": "blink",
|
||||
"b": max(0, min(255, int(brightness))),
|
||||
"d": max(1, int(delay_ms)),
|
||||
"c": ["#FF0000", "#0000FF"],
|
||||
"a": True,
|
||||
}
|
||||
},
|
||||
"s": [str(preset_id)],
|
||||
}
|
||||
return {"v": "1", "dv": {_format_mac(mac): body}}
|
||||
|
||||
|
||||
async def _send(url: str, envelope: Dict[str, Any], hold_s: float) -> None:
|
||||
import websockets
|
||||
|
||||
packet = json.dumps(envelope, separators=(",", ":")).encode("utf-8")
|
||||
print(f"connecting to {url}")
|
||||
async with websockets.connect(url, ping_interval=20, ping_timeout=20) as ws:
|
||||
print(f"connected, sending {len(packet)} B")
|
||||
print(packet.decode("utf-8"))
|
||||
await ws.send(packet)
|
||||
if hold_s > 0:
|
||||
print(f"holding connection {hold_s}s …")
|
||||
await asyncio.sleep(hold_s)
|
||||
print("done")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Send blink preset+select to one driver via bridge WebSocket.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--url",
|
||||
default=None,
|
||||
help="Bridge WebSocket URL (default: settings.json bridge_ws_url or ws://192.168.4.1/ws)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--mac",
|
||||
default="188b0e1560a8",
|
||||
help="Driver MAC (12 hex, colons optional). Default: registry example id.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--preset-id",
|
||||
default="2",
|
||||
help="Wire preset slot id (default: 2, matches zone push)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--delay-ms",
|
||||
type=int,
|
||||
default=200,
|
||||
help="Blink delay in ms (default: 200)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--brightness",
|
||||
type=int,
|
||||
default=64,
|
||||
help="Preset brightness 0–255 (default: 64)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--hold",
|
||||
type=float,
|
||||
default=2.0,
|
||||
help="Seconds to keep WebSocket open after send (default: 2)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Print envelope only; do not connect",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
url = _load_bridge_url(args.url)
|
||||
try:
|
||||
envelope = build_blink_envelope(
|
||||
args.mac,
|
||||
preset_id=args.preset_id,
|
||||
delay_ms=args.delay_ms,
|
||||
brightness=args.brightness,
|
||||
)
|
||||
except ValueError as e:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(f"url={url!r} mac={_format_mac(args.mac)!r}")
|
||||
if args.dry_run:
|
||||
print(json.dumps(envelope, indent=2))
|
||||
return 0
|
||||
|
||||
try:
|
||||
asyncio.run(_send(url, envelope, args.hold))
|
||||
except KeyboardInterrupt:
|
||||
print("interrupted")
|
||||
return 130
|
||||
except Exception as e:
|
||||
print(f"failed: {e!r}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,116 +0,0 @@
|
||||
"""Device-side radio diagnostic test (MicroPython).
|
||||
|
||||
Checks:
|
||||
1) STA/AP bring-up on channel 5
|
||||
2) ESP-NOW init and broadcast peer add
|
||||
3) Broadcast TX test packet send
|
||||
4) RX wait window to see any incoming ESP-NOW frames
|
||||
"""
|
||||
|
||||
import espnow
|
||||
import machine
|
||||
import network
|
||||
import time
|
||||
import ubinascii
|
||||
|
||||
|
||||
CHANNEL = 5
|
||||
RX_WINDOW_MS = 3000
|
||||
WDT_TIMEOUT_MS = 10000
|
||||
BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
|
||||
TEST_PAYLOAD = b"\x4c\x05\x01\x00\x00\x00"
|
||||
|
||||
|
||||
def _mac_hex(mac_bytes):
|
||||
try:
|
||||
return ubinascii.hexlify(mac_bytes).decode()
|
||||
except Exception:
|
||||
return "?"
|
||||
|
||||
|
||||
def run_diag(channel=CHANNEL, rx_window_ms=RX_WINDOW_MS):
|
||||
wdt = machine.WDT(timeout=WDT_TIMEOUT_MS)
|
||||
wdt.feed()
|
||||
|
||||
print("diag start")
|
||||
print("cpu freq", machine.freq())
|
||||
|
||||
sta = network.WLAN(network.STA_IF)
|
||||
ap = network.WLAN(network.AP_IF)
|
||||
|
||||
# Clean start
|
||||
try:
|
||||
sta.active(False)
|
||||
ap.active(False)
|
||||
time.sleep_ms(100)
|
||||
except Exception as e:
|
||||
print("wifi reset failed", repr(e))
|
||||
|
||||
# STA setup
|
||||
try:
|
||||
sta.active(True)
|
||||
sta.config(pm=network.WLAN.PM_NONE)
|
||||
sta.config(channel=channel)
|
||||
print("sta ok ch", sta.config("channel"), "mac", _mac_hex(sta.config("mac")))
|
||||
except Exception as e:
|
||||
print("sta setup failed", repr(e))
|
||||
|
||||
# AP setup
|
||||
try:
|
||||
ap.active(True)
|
||||
try:
|
||||
ap.config(essid="diag-ap", channel=channel, hidden=True)
|
||||
except TypeError:
|
||||
ap.config(essid="diag-ap", channel=channel)
|
||||
print("ap ok ch", ap.config("channel"), "mac", _mac_hex(ap.config("mac")))
|
||||
except Exception as e:
|
||||
print("ap setup failed", repr(e))
|
||||
|
||||
wdt.feed()
|
||||
|
||||
# ESP-NOW setup
|
||||
try:
|
||||
e = espnow.ESPNow()
|
||||
e.active(True)
|
||||
print("espnow active ok")
|
||||
except Exception as e_err:
|
||||
print("espnow init failed", repr(e_err))
|
||||
return
|
||||
|
||||
# Add broadcast peer
|
||||
try:
|
||||
e.add_peer(BROADCAST_MAC, channel=channel)
|
||||
print("add bcast peer ok")
|
||||
except TypeError:
|
||||
try:
|
||||
e.add_peer(BROADCAST_MAC)
|
||||
print("add bcast peer ok (no channel arg)")
|
||||
except Exception as e_err:
|
||||
print("add bcast peer failed", repr(e_err))
|
||||
except Exception as e_err:
|
||||
print("add bcast peer failed", repr(e_err))
|
||||
|
||||
# TX test
|
||||
try:
|
||||
ok = e.send(BROADCAST_MAC, TEST_PAYLOAD, True)
|
||||
print("tx bcast", ok, "len", len(TEST_PAYLOAD))
|
||||
except Exception as e_err:
|
||||
print("tx bcast failed", repr(e_err))
|
||||
|
||||
# RX window
|
||||
print("rx window ms", rx_window_ms)
|
||||
t_end = time.ticks_add(time.ticks_ms(), rx_window_ms)
|
||||
rx_count = 0
|
||||
while time.ticks_diff(t_end, time.ticks_ms()) > 0:
|
||||
wdt.feed()
|
||||
host, msg = e.recv(100)
|
||||
if host:
|
||||
rx_count += 1
|
||||
print("rx", rx_count, _mac_hex(host), "len", len(msg))
|
||||
time.sleep_ms(5)
|
||||
|
||||
print("diag done rx_count", rx_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_diag()
|
||||
@@ -1,40 +0,0 @@
|
||||
"""Device test: receive ESP-NOW packets on channel 5 (MicroPython)."""
|
||||
|
||||
import espnow
|
||||
import machine
|
||||
import network
|
||||
import ubinascii
|
||||
import time
|
||||
|
||||
|
||||
CHANNEL = 5
|
||||
TIMEOUT_MS = 1000
|
||||
WDT_TIMEOUT_MS = 10000
|
||||
|
||||
|
||||
def _set_channel(channel):
|
||||
sta = network.WLAN(network.STA_IF)
|
||||
sta.active(True)
|
||||
sta.config(pm=network.WLAN.PM_NONE)
|
||||
sta.config(channel=channel)
|
||||
|
||||
|
||||
def recv_loop(channel=CHANNEL, timeout_ms=TIMEOUT_MS):
|
||||
wdt = machine.WDT(timeout=WDT_TIMEOUT_MS)
|
||||
_set_channel(channel)
|
||||
e = espnow.ESPNow()
|
||||
e.active(True)
|
||||
print("recv ready ch", channel)
|
||||
while True:
|
||||
wdt.feed()
|
||||
host, msg = e.recv(timeout_ms)
|
||||
if host:
|
||||
mac_hex = ubinascii.hexlify(host).decode()
|
||||
print("rx", mac_hex, "len", len(msg), "hex", ubinascii.hexlify(msg).decode())
|
||||
else:
|
||||
print("rx timeout")
|
||||
time.sleep_ms(10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
recv_loop()
|
||||
@@ -1,47 +0,0 @@
|
||||
"""Device test: send one ESP-NOW packet on channel 5 (MicroPython)."""
|
||||
|
||||
import espnow
|
||||
import machine
|
||||
import network
|
||||
import ubinascii
|
||||
|
||||
|
||||
CHANNEL = 5
|
||||
DEST_HEX = "ffffffffffff"
|
||||
PAYLOAD_HEX = "4c0501000000"
|
||||
WDT_TIMEOUT_MS = 10000
|
||||
|
||||
|
||||
def _set_channel(channel):
|
||||
sta = network.WLAN(network.STA_IF)
|
||||
sta.active(True)
|
||||
sta.config(pm=network.WLAN.PM_NONE)
|
||||
sta.config(channel=channel)
|
||||
|
||||
|
||||
def _add_peer(esp, dest, channel):
|
||||
try:
|
||||
esp.add_peer(dest, channel=channel)
|
||||
except TypeError:
|
||||
esp.add_peer(dest)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def send_once(dest_hex=DEST_HEX, payload_hex=PAYLOAD_HEX, channel=CHANNEL):
|
||||
wdt = machine.WDT(timeout=WDT_TIMEOUT_MS)
|
||||
wdt.feed()
|
||||
dest = ubinascii.unhexlify(dest_hex)
|
||||
pkt = ubinascii.unhexlify(payload_hex)
|
||||
_set_channel(channel)
|
||||
e = espnow.ESPNow()
|
||||
e.active(True)
|
||||
_add_peer(e, dest, channel)
|
||||
wdt.feed()
|
||||
ok = e.send(dest, pkt, True)
|
||||
print("sent", ok, "ch", channel, "dest", dest_hex, "len", len(pkt))
|
||||
return ok
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
send_once()
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import utime
|
||||
from machine import WDT
|
||||
from settings import Settings
|
||||
from presets import Presets, run_tick
|
||||
|
||||
|
||||
def run_for(p, wdt, ms):
|
||||
start = utime.ticks_ms()
|
||||
while utime.ticks_diff(utime.ticks_ms(), start) < ms:
|
||||
wdt.feed()
|
||||
run_tick(p)
|
||||
utime.sleep_ms(10)
|
||||
|
||||
|
||||
def main():
|
||||
s = Settings()
|
||||
p = Presets(pin=s.get("led_pin", 10), num_leds=s.get("num_leds", 30))
|
||||
wdt = WDT(timeout=10000)
|
||||
|
||||
p.edit("test_aurora", {
|
||||
"p": "aurora",
|
||||
"b": 200,
|
||||
"d": 60,
|
||||
"c": [(255, 0, 0), (0, 0, 255), (0, 255, 0)],
|
||||
"n1": 4,
|
||||
"n2": 2,
|
||||
"n3": 120,
|
||||
"a": True,
|
||||
})
|
||||
p.select("test_aurora")
|
||||
run_for(p, wdt, 3000)
|
||||
|
||||
p.edit("cleanup_off", {"p": "off"})
|
||||
p.select("cleanup_off")
|
||||
run_for(p, wdt, 100)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user