Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac6a900ded | ||
|
|
d4ffb1561d | ||
|
|
05c4bb87f9 | ||
|
|
47f4a6663b | ||
|
|
bf0429c505 | ||
|
|
b3e9fc9663 | ||
|
|
b783d97f13 |
No files matched your search
+2
-1
@@ -1,2 +1,3 @@
|
||||
settings.json
|
||||
__pycache__/
|
||||
__pycache__/
|
||||
c/build/
|
||||
@@ -1,194 +0,0 @@
|
||||
# Dry run: two-commit plan
|
||||
|
||||
## Current state
|
||||
|
||||
- **Staged:** 9 deleted files under old `src/` (boot, dma, main, patterns, settings, static/main.css, web, wifi, ws2812).
|
||||
- **Tracked elsewhere:** `pico/lib/`, `pico/test/leds.py`, `pico/test/rainbow.py` (already in repo).
|
||||
- **Unstaged / untracked:** Rest of restructure (more deletions, new `pico/src/`, `esp32/`, `main.py`, etc.).
|
||||
|
||||
---
|
||||
|
||||
## Commit 1: Folder restructure
|
||||
|
||||
**Goal:** Remove old flat layout; no new code from led-driver yet.
|
||||
|
||||
### 1. Unstage current changes (so we can stage only restructure)
|
||||
|
||||
```bash
|
||||
git restore --staged .
|
||||
```
|
||||
|
||||
### 2. Stage only restructure changes
|
||||
|
||||
**Deletions (remove old layout):**
|
||||
|
||||
```bash
|
||||
# Old top-level src/ (already partially staged; include all)
|
||||
git add -u src/
|
||||
|
||||
# Old lib (microdot, utemplate)
|
||||
git add -u lib/microdot/
|
||||
git add -u lib/utemplate/
|
||||
|
||||
# Old box + test
|
||||
git rm box.scad box.stl test.py 2>/dev/null || true
|
||||
git add -u box.scad box.stl test.py
|
||||
```
|
||||
|
||||
Or in one go (stage all deletions under src/, lib/, and the files):
|
||||
|
||||
```bash
|
||||
git restore --staged .
|
||||
git add -u src/ lib/ box.scad box.stl test.py
|
||||
```
|
||||
|
||||
**Optional for restructure:** If you want commit 1 to also introduce the new tree shape (empty or minimal), you could add only the new directories with a single placeholder each—but Git doesn’t track empty dirs, so the “restructure” commit is usually just the removals.
|
||||
|
||||
**Files that would be in commit 1 (deletions only):**
|
||||
|
||||
| Path | Change |
|
||||
|------|--------|
|
||||
| `src/boot.py` | deleted |
|
||||
| `src/dma.py` | deleted |
|
||||
| `src/main.py` | deleted |
|
||||
| `src/patterns.py` | deleted |
|
||||
| `src/settings.py` | deleted |
|
||||
| `src/static/main.css` | deleted |
|
||||
| `src/static/main.js` | deleted |
|
||||
| `src/templates/index.html` | deleted |
|
||||
| `src/templates/index_html.py` | deleted |
|
||||
| `src/web.py` | deleted |
|
||||
| `src/wifi.py` | deleted |
|
||||
| `src/ws2812.py` | deleted |
|
||||
| `lib/microdot/__init__.py` | deleted |
|
||||
| `lib/microdot/helpers.py` | deleted |
|
||||
| `lib/microdot/microdot.py` | deleted |
|
||||
| `lib/microdot/utemplate.py` | deleted |
|
||||
| `lib/microdot/websocket.py` | deleted |
|
||||
| `lib/utemplate/__init__.py` | deleted |
|
||||
| `lib/utemplate/compiled.py` | deleted |
|
||||
| `lib/utemplate/recompile.py` | deleted |
|
||||
| `lib/utemplate/source.py` | deleted |
|
||||
| `box.scad` | deleted |
|
||||
| `box.stl` | deleted |
|
||||
| `test.py` | deleted |
|
||||
|
||||
**Suggested commit message:**
|
||||
|
||||
```
|
||||
Restructure: remove old flat src/lib layout
|
||||
|
||||
- Remove src/, lib/microdot, lib/utemplate, box.*, test.py
|
||||
- Pico/ESP32 layout and led-driver code in follow-up commit
|
||||
```
|
||||
|
||||
### 3. (Dry run) Show what would be committed
|
||||
|
||||
```bash
|
||||
git status
|
||||
git diff --cached --stat
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Commit 2: Import code from led-driver
|
||||
|
||||
**Goal:** Add pico/ and esp32/ app code and top-level entrypoint (from led-driver).
|
||||
|
||||
### 1. Stage new and modified files
|
||||
|
||||
```bash
|
||||
# New layout: pico app and tests
|
||||
git add pico/src/
|
||||
git add pico/test/patterns/
|
||||
git add pico/test/test_espnow_receive.py
|
||||
git add -u pico/test/leds.py
|
||||
git add -u pico/test/rainbow.py
|
||||
|
||||
# ESP32 app and tests
|
||||
git add esp32/
|
||||
|
||||
# Top-level entrypoint
|
||||
git add main.py
|
||||
|
||||
# Tooling / docs (if you want them in this commit)
|
||||
git add dev.py README.md
|
||||
|
||||
# Optional
|
||||
git add Pipfile Pipfile.lock
|
||||
```
|
||||
|
||||
### 2. Files that would be in commit 2
|
||||
|
||||
**New files (led-driver / app):**
|
||||
|
||||
| Path |
|
||||
|------|
|
||||
| `main.py` |
|
||||
| `pico/src/main.py` |
|
||||
| `pico/src/p2p.py` |
|
||||
| `pico/src/preset.py` |
|
||||
| `pico/src/presets.py` |
|
||||
| `pico/src/settings.py` |
|
||||
| `pico/src/utils.py` |
|
||||
| `pico/src/patterns/__init__.py` |
|
||||
| `pico/src/patterns/blink.py` |
|
||||
| `pico/src/patterns/chase.py` |
|
||||
| `pico/src/patterns/circle.py` |
|
||||
| `pico/src/patterns/pulse.py` |
|
||||
| `pico/src/patterns/rainbow.py` |
|
||||
| `pico/src/patterns/transition.py` |
|
||||
| `esp32/src/main.py` |
|
||||
| `esp32/test/test_uart_send_json.py` |
|
||||
| `esp32/test/test_uart_tx.py` |
|
||||
| `pico/test/patterns/auto_manual.py` |
|
||||
| `pico/test/patterns/blink.py` |
|
||||
| … (other pico/test/patterns/*) |
|
||||
|
||||
**Modified:**
|
||||
|
||||
| Path |
|
||||
|------|
|
||||
| `pico/test/leds.py` |
|
||||
| `pico/test/rainbow.py` |
|
||||
| `dev.py` |
|
||||
| `README.md` (optional) |
|
||||
|
||||
**Optional (tooling):**
|
||||
|
||||
| Path |
|
||||
|------|
|
||||
| `Pipfile` |
|
||||
| `Pipfile.lock` |
|
||||
|
||||
**Suggested commit message:**
|
||||
|
||||
```
|
||||
Import led-driver app: pico/ and esp32/ layout
|
||||
|
||||
- pico/src: main, presets, settings, patterns (UART JSON)
|
||||
- esp32/src: main (UART sender)
|
||||
- main.py top-level entrypoint
|
||||
- pico/test: pattern tests, test_espnow_receive
|
||||
- dev.py: deploy by device (pico | esp32)
|
||||
```
|
||||
|
||||
### 3. (Dry run) Show what would be committed
|
||||
|
||||
```bash
|
||||
git status
|
||||
git diff --cached --stat
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
| Step | Action | Commit message |
|
||||
|------|--------|----------------|
|
||||
| 1 | `git restore --staged .` then stage only `src/` `lib/` `box.scad` `box.stl` `test.py` deletions | Restructure: remove old flat src/lib layout |
|
||||
| 2 | Commit | (above) |
|
||||
| 3 | Stage `pico/src/`, `pico/test/` changes, `esp32/`, `main.py`, optionally `dev.py` `README.md` `Pipfile*` | Import led-driver app: pico/ and esp32/ layout |
|
||||
| 4 | Commit | (above) |
|
||||
|
||||
No commits are made in this dry run; run the `git add` and `git status` / `git diff --cached --stat` commands to confirm before running `git commit`.
|
||||
@@ -0,0 +1,99 @@
|
||||
cmake_minimum_required(VERSION 3.13)
|
||||
|
||||
set(PICO_BOARD pico2_w CACHE STRING "Board type")
|
||||
|
||||
include(pico_sdk_import.cmake)
|
||||
|
||||
project(led_hoop C CXX ASM)
|
||||
|
||||
pico_sdk_init()
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
file(GLOB_RECURSE SRC_SOURCES CONFIGURE_DEPENDS
|
||||
"${CMAKE_CURRENT_LIST_DIR}/src/*.c"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/src/*.cpp"
|
||||
)
|
||||
file(GLOB_RECURSE LIB_SOURCES CONFIGURE_DEPENDS
|
||||
"${CMAKE_CURRENT_LIST_DIR}/lib/*.c"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/lib/*.cpp"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/lib/**/*.c"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/lib/**/*.cpp"
|
||||
)
|
||||
|
||||
# Embed web UI from normal files under web/ (headers generated into build/)
|
||||
set(WEB_GEN_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated")
|
||||
set(EMBED_SCRIPT "${CMAKE_CURRENT_LIST_DIR}/scripts/embed_file.py")
|
||||
set(WEB_ASSETS
|
||||
"${WEB_GEN_DIR}/web_index_html.h"
|
||||
"${WEB_GEN_DIR}/web_main_js.h"
|
||||
"${WEB_GEN_DIR}/web_styles_css.h"
|
||||
)
|
||||
add_custom_command(
|
||||
OUTPUT "${WEB_GEN_DIR}/web_index_html.h"
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${WEB_GEN_DIR}"
|
||||
COMMAND python3 "${EMBED_SCRIPT}"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/web/index.html" web_index_html
|
||||
"${WEB_GEN_DIR}/web_index_html.h"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/web/index.html" "${EMBED_SCRIPT}"
|
||||
VERBATIM
|
||||
)
|
||||
add_custom_command(
|
||||
OUTPUT "${WEB_GEN_DIR}/web_main_js.h"
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${WEB_GEN_DIR}"
|
||||
COMMAND python3 "${EMBED_SCRIPT}"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/web/static/main.js" web_main_js
|
||||
"${WEB_GEN_DIR}/web_main_js.h"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/web/static/main.js" "${EMBED_SCRIPT}"
|
||||
VERBATIM
|
||||
)
|
||||
add_custom_command(
|
||||
OUTPUT "${WEB_GEN_DIR}/web_styles_css.h"
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${WEB_GEN_DIR}"
|
||||
COMMAND python3 "${EMBED_SCRIPT}"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/web/static/styles.css" web_styles_css
|
||||
"${WEB_GEN_DIR}/web_styles_css.h"
|
||||
DEPENDS "${CMAKE_CURRENT_LIST_DIR}/web/static/styles.css" "${EMBED_SCRIPT}"
|
||||
VERBATIM
|
||||
)
|
||||
add_custom_target(web_assets DEPENDS ${WEB_ASSETS})
|
||||
|
||||
add_executable(led_hoop
|
||||
${SRC_SOURCES}
|
||||
${LIB_SOURCES}
|
||||
)
|
||||
add_dependencies(led_hoop web_assets)
|
||||
|
||||
target_include_directories(led_hoop PRIVATE
|
||||
${CMAKE_CURRENT_LIST_DIR}
|
||||
${CMAKE_CURRENT_LIST_DIR}/src
|
||||
${CMAKE_CURRENT_LIST_DIR}/lib
|
||||
${CMAKE_CURRENT_LIST_DIR}/lib/httpserver
|
||||
${WEB_GEN_DIR}
|
||||
)
|
||||
|
||||
target_link_libraries(led_hoop
|
||||
pico_stdlib
|
||||
pico_multicore
|
||||
hardware_pio
|
||||
hardware_dma
|
||||
hardware_clocks
|
||||
hardware_flash
|
||||
pico_cyw43_arch_lwip_threadsafe_background
|
||||
pico_bootsel_via_double_reset
|
||||
)
|
||||
|
||||
# Ensure picotool can force the running app into BOOTSEL (no button)
|
||||
target_compile_definitions(led_hoop PRIVATE
|
||||
PICO_ENABLE_USB_RESET_VIA_VENDOR_INTERFACE=1
|
||||
PICO_ENABLE_USB_RESET_VIA_BAUD_RATE=1
|
||||
)
|
||||
|
||||
pico_configure_ip4_address(led_hoop PRIVATE
|
||||
CYW43_DEFAULT_IP_AP_ADDRESS 192.168.4.1
|
||||
)
|
||||
|
||||
pico_enable_stdio_usb(led_hoop 1)
|
||||
pico_enable_stdio_uart(led_hoop 0)
|
||||
|
||||
pico_add_extra_outputs(led_hoop)
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# Pico 2 W firmware
|
||||
#
|
||||
# make build | flash | test | reset | monitor | clean
|
||||
# make monitor PORT=/dev/ttyACM0
|
||||
|
||||
PICO_SDK_PATH ?= $(HOME)/pico-sdk
|
||||
CMAKE_PREFIX_PATH ?= $(HOME)/.local
|
||||
BUILD_DIR ?= build
|
||||
TARGET ?= led_hoop
|
||||
PORT ?= /dev/ttyACM0
|
||||
BAUD ?= 115200
|
||||
FLASH_WAIT_S ?= 20
|
||||
|
||||
export PICO_SDK_PATH
|
||||
export PATH := $(HOME)/.local/bin:$(PATH)
|
||||
|
||||
UF2 := $(BUILD_DIR)/$(TARGET).uf2
|
||||
|
||||
.PHONY: all build flash test reset monitor clean
|
||||
|
||||
all: build
|
||||
|
||||
build:
|
||||
cmake -S . -B $(BUILD_DIR) -DCMAKE_PREFIX_PATH=$(CMAKE_PREFIX_PATH)
|
||||
cmake --build $(BUILD_DIR) -j$$(nproc)
|
||||
|
||||
flash: build
|
||||
picotool load -fx $(UF2)
|
||||
|
||||
test: build
|
||||
picotool info $(UF2)
|
||||
|
||||
reset:
|
||||
picotool reboot -af
|
||||
|
||||
monitor:
|
||||
@echo "Waiting for $(PORT)..."
|
||||
@until [ -e "$(PORT)" ]; do sleep 0.25; done
|
||||
@sleep 0.5
|
||||
picocom -b $(BAUD) $(PORT)
|
||||
|
||||
clean:
|
||||
rm -rf $(BUILD_DIR)
|
||||
@@ -0,0 +1,309 @@
|
||||
/*
|
||||
* This file is part of the MicroPython project, http://micropython.org/
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2018-2019 Damien P. George
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// For DHCP specs see:
|
||||
// https://www.ietf.org/rfc/rfc2131.txt
|
||||
// https://tools.ietf.org/html/rfc2132 -- DHCP Options and BOOTP Vendor Extensions
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
#include "cyw43_config.h"
|
||||
#include "dhcpserver.h"
|
||||
#include "lwip/udp.h"
|
||||
|
||||
#define DHCPDISCOVER (1)
|
||||
#define DHCPOFFER (2)
|
||||
#define DHCPREQUEST (3)
|
||||
#define DHCPDECLINE (4)
|
||||
#define DHCPACK (5)
|
||||
#define DHCPNACK (6)
|
||||
#define DHCPRELEASE (7)
|
||||
#define DHCPINFORM (8)
|
||||
|
||||
#define DHCP_OPT_PAD (0)
|
||||
#define DHCP_OPT_SUBNET_MASK (1)
|
||||
#define DHCP_OPT_ROUTER (3)
|
||||
#define DHCP_OPT_DNS (6)
|
||||
#define DHCP_OPT_HOST_NAME (12)
|
||||
#define DHCP_OPT_REQUESTED_IP (50)
|
||||
#define DHCP_OPT_IP_LEASE_TIME (51)
|
||||
#define DHCP_OPT_MSG_TYPE (53)
|
||||
#define DHCP_OPT_SERVER_ID (54)
|
||||
#define DHCP_OPT_PARAM_REQUEST_LIST (55)
|
||||
#define DHCP_OPT_MAX_MSG_SIZE (57)
|
||||
#define DHCP_OPT_VENDOR_CLASS_ID (60)
|
||||
#define DHCP_OPT_CLIENT_ID (61)
|
||||
#define DHCP_OPT_END (255)
|
||||
|
||||
#define PORT_DHCP_SERVER (67)
|
||||
#define PORT_DHCP_CLIENT (68)
|
||||
|
||||
#define DEFAULT_LEASE_TIME_S (24 * 60 * 60) // in seconds
|
||||
|
||||
#define MAC_LEN (6)
|
||||
#define MAKE_IP4(a, b, c, d) ((a) << 24 | (b) << 16 | (c) << 8 | (d))
|
||||
|
||||
typedef struct {
|
||||
uint8_t op; // message opcode
|
||||
uint8_t htype; // hardware address type
|
||||
uint8_t hlen; // hardware address length
|
||||
uint8_t hops;
|
||||
uint32_t xid; // transaction id, chosen by client
|
||||
uint16_t secs; // client seconds elapsed
|
||||
uint16_t flags;
|
||||
uint8_t ciaddr[4]; // client IP address
|
||||
uint8_t yiaddr[4]; // your IP address
|
||||
uint8_t siaddr[4]; // next server IP address
|
||||
uint8_t giaddr[4]; // relay agent IP address
|
||||
uint8_t chaddr[16]; // client hardware address
|
||||
uint8_t sname[64]; // server host name
|
||||
uint8_t file[128]; // boot file name
|
||||
uint8_t options[312]; // optional parameters, variable, starts with magic
|
||||
} dhcp_msg_t;
|
||||
|
||||
static int dhcp_socket_new_dgram(struct udp_pcb **udp, void *cb_data, udp_recv_fn cb_udp_recv) {
|
||||
// family is AF_INET
|
||||
// type is SOCK_DGRAM
|
||||
|
||||
*udp = udp_new();
|
||||
if (*udp == NULL) {
|
||||
return -ENOMEM;
|
||||
}
|
||||
|
||||
// Register callback
|
||||
udp_recv(*udp, cb_udp_recv, (void *)cb_data);
|
||||
|
||||
return 0; // success
|
||||
}
|
||||
|
||||
static void dhcp_socket_free(struct udp_pcb **udp) {
|
||||
if (*udp != NULL) {
|
||||
udp_remove(*udp);
|
||||
*udp = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static int dhcp_socket_bind(struct udp_pcb **udp, uint16_t port) {
|
||||
// TODO convert lwIP errors to errno
|
||||
return udp_bind(*udp, IP_ANY_TYPE, port);
|
||||
}
|
||||
|
||||
static int dhcp_socket_sendto(struct udp_pcb **udp, struct netif *nif, const void *buf, size_t len, uint32_t ip, uint16_t port) {
|
||||
if (len > 0xffff) {
|
||||
len = 0xffff;
|
||||
}
|
||||
|
||||
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
|
||||
if (p == NULL) {
|
||||
return -ENOMEM;
|
||||
}
|
||||
|
||||
memcpy(p->payload, buf, len);
|
||||
|
||||
ip_addr_t dest;
|
||||
IP4_ADDR(ip_2_ip4(&dest), ip >> 24 & 0xff, ip >> 16 & 0xff, ip >> 8 & 0xff, ip & 0xff);
|
||||
err_t err;
|
||||
if (nif != NULL) {
|
||||
err = udp_sendto_if(*udp, p, &dest, port, nif);
|
||||
} else {
|
||||
err = udp_sendto(*udp, p, &dest, port);
|
||||
}
|
||||
|
||||
pbuf_free(p);
|
||||
|
||||
if (err != ERR_OK) {
|
||||
return err;
|
||||
}
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
static uint8_t *opt_find(uint8_t *opt, uint8_t cmd) {
|
||||
for (int i = 0; i < 308 && opt[i] != DHCP_OPT_END;) {
|
||||
if (opt[i] == cmd) {
|
||||
return &opt[i];
|
||||
}
|
||||
i += 2 + opt[i + 1];
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void opt_write_n(uint8_t **opt, uint8_t cmd, size_t n, const void *data) {
|
||||
uint8_t *o = *opt;
|
||||
*o++ = cmd;
|
||||
*o++ = n;
|
||||
memcpy(o, data, n);
|
||||
*opt = o + n;
|
||||
}
|
||||
|
||||
static void opt_write_u8(uint8_t **opt, uint8_t cmd, uint8_t val) {
|
||||
uint8_t *o = *opt;
|
||||
*o++ = cmd;
|
||||
*o++ = 1;
|
||||
*o++ = val;
|
||||
*opt = o;
|
||||
}
|
||||
|
||||
static void opt_write_u32(uint8_t **opt, uint8_t cmd, uint32_t val) {
|
||||
uint8_t *o = *opt;
|
||||
*o++ = cmd;
|
||||
*o++ = 4;
|
||||
*o++ = val >> 24;
|
||||
*o++ = val >> 16;
|
||||
*o++ = val >> 8;
|
||||
*o++ = val;
|
||||
*opt = o;
|
||||
}
|
||||
|
||||
static void dhcp_server_process(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *src_addr, u16_t src_port) {
|
||||
dhcp_server_t *d = arg;
|
||||
(void)upcb;
|
||||
(void)src_addr;
|
||||
(void)src_port;
|
||||
|
||||
// This is around 548 bytes
|
||||
dhcp_msg_t dhcp_msg;
|
||||
|
||||
#define DHCP_MIN_SIZE (240 + 3)
|
||||
if (p->tot_len < DHCP_MIN_SIZE) {
|
||||
goto ignore_request;
|
||||
}
|
||||
|
||||
size_t len = pbuf_copy_partial(p, &dhcp_msg, sizeof(dhcp_msg), 0);
|
||||
if (len < DHCP_MIN_SIZE) {
|
||||
goto ignore_request;
|
||||
}
|
||||
|
||||
dhcp_msg.op = DHCPOFFER;
|
||||
memcpy(&dhcp_msg.yiaddr, &ip4_addr_get_u32(ip_2_ip4(&d->ip)), 4);
|
||||
|
||||
uint8_t *opt = (uint8_t *)&dhcp_msg.options;
|
||||
opt += 4; // assume magic cookie: 99, 130, 83, 99
|
||||
|
||||
uint8_t *msgtype = opt_find(opt, DHCP_OPT_MSG_TYPE);
|
||||
if (msgtype == NULL) {
|
||||
// A DHCP package without MSG_TYPE?
|
||||
goto ignore_request;
|
||||
}
|
||||
|
||||
switch (msgtype[2]) {
|
||||
case DHCPDISCOVER: {
|
||||
int yi = DHCPS_MAX_IP;
|
||||
for (int i = 0; i < DHCPS_MAX_IP; ++i) {
|
||||
if (memcmp(d->lease[i].mac, dhcp_msg.chaddr, MAC_LEN) == 0) {
|
||||
// MAC match, use this IP address
|
||||
yi = i;
|
||||
break;
|
||||
}
|
||||
if (yi == DHCPS_MAX_IP) {
|
||||
// Look for a free IP address
|
||||
if (memcmp(d->lease[i].mac, "\x00\x00\x00\x00\x00\x00", MAC_LEN) == 0) {
|
||||
// IP available
|
||||
yi = i;
|
||||
}
|
||||
uint32_t expiry = d->lease[i].expiry << 16 | 0xffff;
|
||||
if ((int32_t)(expiry - cyw43_hal_ticks_ms()) < 0) {
|
||||
// IP expired, reuse it
|
||||
memset(d->lease[i].mac, 0, MAC_LEN);
|
||||
yi = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (yi == DHCPS_MAX_IP) {
|
||||
// No more IP addresses left
|
||||
goto ignore_request;
|
||||
}
|
||||
dhcp_msg.yiaddr[3] = DHCPS_BASE_IP + yi;
|
||||
opt_write_u8(&opt, DHCP_OPT_MSG_TYPE, DHCPOFFER);
|
||||
break;
|
||||
}
|
||||
|
||||
case DHCPREQUEST: {
|
||||
uint8_t *o = opt_find(opt, DHCP_OPT_REQUESTED_IP);
|
||||
if (o == NULL) {
|
||||
// Should be NACK
|
||||
goto ignore_request;
|
||||
}
|
||||
if (memcmp(o + 2, &ip4_addr_get_u32(ip_2_ip4(&d->ip)), 3) != 0) {
|
||||
// Should be NACK
|
||||
goto ignore_request;
|
||||
}
|
||||
uint8_t yi = o[5] - DHCPS_BASE_IP;
|
||||
if (yi >= DHCPS_MAX_IP) {
|
||||
// Should be NACK
|
||||
goto ignore_request;
|
||||
}
|
||||
if (memcmp(d->lease[yi].mac, dhcp_msg.chaddr, MAC_LEN) == 0) {
|
||||
// MAC match, ok to use this IP address
|
||||
} else if (memcmp(d->lease[yi].mac, "\x00\x00\x00\x00\x00\x00", MAC_LEN) == 0) {
|
||||
// IP unused, ok to use this IP address
|
||||
memcpy(d->lease[yi].mac, dhcp_msg.chaddr, MAC_LEN);
|
||||
} else {
|
||||
// IP already in use
|
||||
// Should be NACK
|
||||
goto ignore_request;
|
||||
}
|
||||
d->lease[yi].expiry = (cyw43_hal_ticks_ms() + DEFAULT_LEASE_TIME_S * 1000) >> 16;
|
||||
dhcp_msg.yiaddr[3] = DHCPS_BASE_IP + yi;
|
||||
opt_write_u8(&opt, DHCP_OPT_MSG_TYPE, DHCPACK);
|
||||
printf("DHCPS: client connected: MAC=%02x:%02x:%02x:%02x:%02x:%02x IP=%u.%u.%u.%u\n",
|
||||
dhcp_msg.chaddr[0], dhcp_msg.chaddr[1], dhcp_msg.chaddr[2], dhcp_msg.chaddr[3], dhcp_msg.chaddr[4], dhcp_msg.chaddr[5],
|
||||
dhcp_msg.yiaddr[0], dhcp_msg.yiaddr[1], dhcp_msg.yiaddr[2], dhcp_msg.yiaddr[3]);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
goto ignore_request;
|
||||
}
|
||||
|
||||
opt_write_n(&opt, DHCP_OPT_SERVER_ID, 4, &ip4_addr_get_u32(ip_2_ip4(&d->ip)));
|
||||
opt_write_n(&opt, DHCP_OPT_SUBNET_MASK, 4, &ip4_addr_get_u32(ip_2_ip4(&d->nm)));
|
||||
opt_write_n(&opt, DHCP_OPT_ROUTER, 4, &ip4_addr_get_u32(ip_2_ip4(&d->ip))); // aka gateway; can have multiple addresses
|
||||
opt_write_n(&opt, DHCP_OPT_DNS, 4, &ip4_addr_get_u32(ip_2_ip4(&d->ip))); // this server is the dns
|
||||
opt_write_u32(&opt, DHCP_OPT_IP_LEASE_TIME, DEFAULT_LEASE_TIME_S);
|
||||
*opt++ = DHCP_OPT_END;
|
||||
struct netif *nif = ip_current_input_netif();
|
||||
dhcp_socket_sendto(&d->udp, nif, &dhcp_msg, opt - (uint8_t *)&dhcp_msg, 0xffffffff, PORT_DHCP_CLIENT);
|
||||
|
||||
ignore_request:
|
||||
pbuf_free(p);
|
||||
}
|
||||
|
||||
void dhcp_server_init(dhcp_server_t *d, ip_addr_t *ip, ip_addr_t *nm) {
|
||||
ip_addr_copy(d->ip, *ip);
|
||||
ip_addr_copy(d->nm, *nm);
|
||||
memset(d->lease, 0, sizeof(d->lease));
|
||||
if (dhcp_socket_new_dgram(&d->udp, d, dhcp_server_process) != 0) {
|
||||
return;
|
||||
}
|
||||
dhcp_socket_bind(&d->udp, PORT_DHCP_SERVER);
|
||||
}
|
||||
|
||||
void dhcp_server_deinit(dhcp_server_t *d) {
|
||||
dhcp_socket_free(&d->udp);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* This file is part of the MicroPython project, http://micropython.org/
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2018-2019 Damien P. George
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
#ifndef MICROPY_INCLUDED_LIB_NETUTILS_DHCPSERVER_H
|
||||
#define MICROPY_INCLUDED_LIB_NETUTILS_DHCPSERVER_H
|
||||
|
||||
#include "lwip/ip_addr.h"
|
||||
|
||||
#define DHCPS_BASE_IP (16)
|
||||
#define DHCPS_MAX_IP (8)
|
||||
|
||||
typedef struct _dhcp_server_lease_t {
|
||||
uint8_t mac[6];
|
||||
uint16_t expiry;
|
||||
} dhcp_server_lease_t;
|
||||
|
||||
typedef struct _dhcp_server_t {
|
||||
ip_addr_t ip;
|
||||
ip_addr_t nm;
|
||||
dhcp_server_lease_t lease[DHCPS_MAX_IP];
|
||||
struct udp_pcb *udp;
|
||||
} dhcp_server_t;
|
||||
|
||||
void dhcp_server_init(dhcp_server_t *d, ip_addr_t *ip, ip_addr_t *nm);
|
||||
void dhcp_server_deinit(dhcp_server_t *d);
|
||||
|
||||
#endif // MICROPY_INCLUDED_LIB_NETUTILS_DHCPSERVER_H
|
||||
@@ -0,0 +1,815 @@
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "pico/cyw43_arch.h"
|
||||
#include "lwip/pbuf.h"
|
||||
#include "lwip/tcp.h"
|
||||
|
||||
#include "httpserver.h"
|
||||
|
||||
#define HS_POLL_INTERVAL 20
|
||||
#define HS_MAX_CONNS 4
|
||||
#define HS_MAX_ROUTES 16
|
||||
#define HS_MAX_WS_ROUTES 4
|
||||
#define HS_REQ_BUF 8192
|
||||
#define HS_HDR_BUF 512
|
||||
#define HS_WS_PAYLOAD_MAX 2048
|
||||
#define HS_SEND_CHUNK 1400
|
||||
#define HS_WS_GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
typedef enum {
|
||||
CONN_FREE = 0,
|
||||
CONN_HTTP,
|
||||
CONN_WS,
|
||||
} conn_mode_t;
|
||||
|
||||
typedef struct {
|
||||
const char *method;
|
||||
const char *path;
|
||||
httpserver_handler_t fn;
|
||||
} route_t;
|
||||
|
||||
typedef struct {
|
||||
const char *path;
|
||||
httpserver_ws_open_t on_open;
|
||||
httpserver_ws_msg_t on_msg;
|
||||
httpserver_ws_close_t on_close;
|
||||
} ws_route_t;
|
||||
|
||||
struct httpserver_conn {
|
||||
conn_mode_t mode;
|
||||
httpserver_t *server;
|
||||
struct tcp_pcb *pcb;
|
||||
const ws_route_t *ws_route;
|
||||
char buf[HS_REQ_BUF];
|
||||
int buf_len;
|
||||
int header_end; /* index of first body byte, or -1 */
|
||||
int content_length;
|
||||
bool headers_complete;
|
||||
bool dispatched;
|
||||
|
||||
/* streaming static response */
|
||||
const uint8_t *static_body;
|
||||
size_t static_len;
|
||||
size_t static_sent; /* bytes queued via tcp_write */
|
||||
size_t tx_acked; /* bytes ACKed (from tcp_sent) */
|
||||
size_t tx_total; /* hdr_len + static_len */
|
||||
bool write_done;
|
||||
char hdr[HS_HDR_BUF];
|
||||
int hdr_len;
|
||||
int hdr_sent;
|
||||
};
|
||||
|
||||
struct httpserver {
|
||||
struct tcp_pcb *server_pcb;
|
||||
route_t routes[HS_MAX_ROUTES];
|
||||
int route_count;
|
||||
ws_route_t ws_routes[HS_MAX_WS_ROUTES];
|
||||
int ws_route_count;
|
||||
httpserver_conn_t conns[HS_MAX_CONNS];
|
||||
};
|
||||
|
||||
static httpserver_t g_server;
|
||||
|
||||
/* ---- SHA-1 ---- */
|
||||
|
||||
typedef struct {
|
||||
uint32_t state[5];
|
||||
uint32_t count[2];
|
||||
uint8_t buffer[64];
|
||||
} sha1_ctx_t;
|
||||
|
||||
static uint32_t sha1_rol(uint32_t v, uint32_t bits) {
|
||||
return (v << bits) | (v >> (32 - bits));
|
||||
}
|
||||
|
||||
static void sha1_transform(uint32_t state[5], const uint8_t *block) {
|
||||
uint32_t w[80];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
w[i] = ((uint32_t)block[i * 4] << 24) | ((uint32_t)block[i * 4 + 1] << 16) |
|
||||
((uint32_t)block[i * 4 + 2] << 8) | ((uint32_t)block[i * 4 + 3]);
|
||||
}
|
||||
for (int i = 16; i < 80; i++) {
|
||||
w[i] = sha1_rol(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
|
||||
}
|
||||
uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4];
|
||||
for (int i = 0; i < 80; i++) {
|
||||
uint32_t f, k;
|
||||
if (i < 20) {
|
||||
f = (b & c) | ((~b) & d);
|
||||
k = 0x5A827999;
|
||||
} else if (i < 40) {
|
||||
f = b ^ c ^ d;
|
||||
k = 0x6ED9EBA1;
|
||||
} else if (i < 60) {
|
||||
f = (b & c) | (b & d) | (c & d);
|
||||
k = 0x8F1BBCDC;
|
||||
} else {
|
||||
f = b ^ c ^ d;
|
||||
k = 0xCA62C1D6;
|
||||
}
|
||||
uint32_t t = sha1_rol(a, 5) + f + e + k + w[i];
|
||||
e = d;
|
||||
d = c;
|
||||
c = sha1_rol(b, 30);
|
||||
b = a;
|
||||
a = t;
|
||||
}
|
||||
state[0] += a;
|
||||
state[1] += b;
|
||||
state[2] += c;
|
||||
state[3] += d;
|
||||
state[4] += e;
|
||||
}
|
||||
|
||||
static void sha1_init(sha1_ctx_t *ctx) {
|
||||
ctx->state[0] = 0x67452301;
|
||||
ctx->state[1] = 0xEFCDAB89;
|
||||
ctx->state[2] = 0x98BADCFE;
|
||||
ctx->state[3] = 0x10325476;
|
||||
ctx->state[4] = 0xC3D2E1F0;
|
||||
ctx->count[0] = ctx->count[1] = 0;
|
||||
}
|
||||
|
||||
static void sha1_update(sha1_ctx_t *ctx, const uint8_t *data, size_t len) {
|
||||
size_t i;
|
||||
size_t idx = (ctx->count[0] >> 3) & 63;
|
||||
ctx->count[0] += (uint32_t)(len << 3);
|
||||
if (ctx->count[0] < (len << 3)) {
|
||||
ctx->count[1]++;
|
||||
}
|
||||
ctx->count[1] += (uint32_t)(len >> 29);
|
||||
size_t part = 64 - idx;
|
||||
if (len >= part) {
|
||||
memcpy(&ctx->buffer[idx], data, part);
|
||||
sha1_transform(ctx->state, ctx->buffer);
|
||||
for (i = part; i + 63 < len; i += 64) {
|
||||
sha1_transform(ctx->state, &data[i]);
|
||||
}
|
||||
idx = 0;
|
||||
} else {
|
||||
i = 0;
|
||||
}
|
||||
memcpy(&ctx->buffer[idx], &data[i], len - i);
|
||||
}
|
||||
|
||||
static void sha1_final(sha1_ctx_t *ctx, uint8_t digest[20]) {
|
||||
uint8_t finalcount[8];
|
||||
for (int i = 0; i < 8; i++) {
|
||||
finalcount[i] = (uint8_t)((ctx->count[(i >= 4) ? 0 : 1] >> ((3 - (i & 3)) * 8)) & 255);
|
||||
}
|
||||
uint8_t c = 0x80;
|
||||
sha1_update(ctx, &c, 1);
|
||||
while ((ctx->count[0] & 504) != 448) {
|
||||
c = 0x00;
|
||||
sha1_update(ctx, &c, 1);
|
||||
}
|
||||
sha1_update(ctx, finalcount, 8);
|
||||
for (int i = 0; i < 20; i++) {
|
||||
digest[i] = (uint8_t)((ctx->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
|
||||
}
|
||||
}
|
||||
|
||||
static void base64_encode_20(const uint8_t in[20], char out[29]) {
|
||||
static const char tbl[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
int o = 0;
|
||||
for (int i = 0; i < 18; i += 3) {
|
||||
uint32_t v = ((uint32_t)in[i] << 16) | ((uint32_t)in[i + 1] << 8) | in[i + 2];
|
||||
out[o++] = tbl[(v >> 18) & 63];
|
||||
out[o++] = tbl[(v >> 12) & 63];
|
||||
out[o++] = tbl[(v >> 6) & 63];
|
||||
out[o++] = tbl[v & 63];
|
||||
}
|
||||
uint32_t v = ((uint32_t)in[18] << 16) | ((uint32_t)in[19] << 8);
|
||||
out[o++] = tbl[(v >> 18) & 63];
|
||||
out[o++] = tbl[(v >> 12) & 63];
|
||||
out[o++] = tbl[(v >> 6) & 63];
|
||||
out[o++] = '=';
|
||||
out[o] = '\0';
|
||||
}
|
||||
|
||||
static void ws_accept_key(const char *client_key, char out[29]) {
|
||||
char material[80];
|
||||
snprintf(material, sizeof(material), "%s%s", client_key, HS_WS_GUID);
|
||||
sha1_ctx_t ctx;
|
||||
uint8_t digest[20];
|
||||
sha1_init(&ctx);
|
||||
sha1_update(&ctx, (const uint8_t *)material, strlen(material));
|
||||
sha1_final(&ctx, digest);
|
||||
base64_encode_20(digest, out);
|
||||
}
|
||||
|
||||
static httpserver_conn_t *conn_alloc(httpserver_t *s, struct tcp_pcb *pcb) {
|
||||
for (int i = 0; i < HS_MAX_CONNS; i++) {
|
||||
if (s->conns[i].mode == CONN_FREE) {
|
||||
memset(&s->conns[i], 0, sizeof(s->conns[i]));
|
||||
s->conns[i].mode = CONN_HTTP;
|
||||
s->conns[i].server = s;
|
||||
s->conns[i].pcb = pcb;
|
||||
s->conns[i].header_end = -1;
|
||||
s->conns[i].content_length = -1;
|
||||
return &s->conns[i];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void conn_free(httpserver_conn_t *conn) {
|
||||
if (conn) {
|
||||
memset(conn, 0, sizeof(*conn));
|
||||
}
|
||||
}
|
||||
|
||||
static err_t close_conn(httpserver_conn_t *conn, struct tcp_pcb *pcb, err_t err) {
|
||||
if (conn && conn->mode == CONN_WS && conn->ws_route && conn->ws_route->on_close) {
|
||||
conn->ws_route->on_close(conn);
|
||||
}
|
||||
if (!pcb) {
|
||||
conn_free(conn);
|
||||
return err;
|
||||
}
|
||||
tcp_arg(pcb, NULL);
|
||||
tcp_poll(pcb, NULL, 0);
|
||||
tcp_sent(pcb, NULL);
|
||||
tcp_recv(pcb, NULL);
|
||||
tcp_err(pcb, NULL);
|
||||
if (tcp_close(pcb) != ERR_OK) {
|
||||
tcp_abort(pcb);
|
||||
err = ERR_ABRT;
|
||||
}
|
||||
conn_free(conn);
|
||||
return err;
|
||||
}
|
||||
|
||||
static bool header_has(const char *req, const char *name) {
|
||||
const char *p = req;
|
||||
size_t nlen = strlen(name);
|
||||
while (*p) {
|
||||
const char *eol = strstr(p, "\r\n");
|
||||
if (!eol) {
|
||||
break;
|
||||
}
|
||||
if ((size_t)(eol - p) >= nlen) {
|
||||
bool match = true;
|
||||
for (size_t i = 0; i < nlen; i++) {
|
||||
if (tolower((unsigned char)p[i]) != tolower((unsigned char)name[i])) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
p = eol + 2;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool header_value(const char *req, const char *name, char *out, size_t out_len) {
|
||||
const char *p = req;
|
||||
size_t nlen = strlen(name);
|
||||
while (*p) {
|
||||
const char *eol = strstr(p, "\r\n");
|
||||
if (!eol) {
|
||||
break;
|
||||
}
|
||||
if ((size_t)(eol - p) > nlen + 1) {
|
||||
bool match = true;
|
||||
for (size_t i = 0; i < nlen; i++) {
|
||||
if (tolower((unsigned char)p[i]) != tolower((unsigned char)name[i])) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match && p[nlen] == ':') {
|
||||
const char *v = p + nlen + 1;
|
||||
while (v < eol && (*v == ' ' || *v == '\t')) {
|
||||
v++;
|
||||
}
|
||||
size_t len = (size_t)(eol - v);
|
||||
if (len >= out_len) {
|
||||
len = out_len - 1;
|
||||
}
|
||||
memcpy(out, v, len);
|
||||
out[len] = '\0';
|
||||
return true;
|
||||
}
|
||||
}
|
||||
p = eol + 2;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static const char *status_text(int status) {
|
||||
switch (status) {
|
||||
case 200: return "OK";
|
||||
case 404: return "Not Found";
|
||||
case 405: return "Method Not Allowed";
|
||||
case 500: return "Internal Server Error";
|
||||
default: return "OK";
|
||||
}
|
||||
}
|
||||
|
||||
static const ws_route_t *find_ws_route(httpserver_t *s, const char *path) {
|
||||
for (int i = 0; i < s->ws_route_count; i++) {
|
||||
if (strcmp(s->ws_routes[i].path, path) == 0) {
|
||||
return &s->ws_routes[i];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static const route_t *find_route(httpserver_t *s, const char *method, const char *path) {
|
||||
for (int i = 0; i < s->route_count; i++) {
|
||||
if (strcmp(s->routes[i].method, method) == 0 && strcmp(s->routes[i].path, path) == 0) {
|
||||
return &s->routes[i];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static bool parse_request_line(const char *req, char *method, size_t method_len,
|
||||
char *path, size_t path_len, char *query, size_t query_len) {
|
||||
method[0] = path[0] = query[0] = '\0';
|
||||
const char *eol = strstr(req, "\r\n");
|
||||
if (!eol) {
|
||||
return false;
|
||||
}
|
||||
char line[160];
|
||||
size_t line_len = (size_t)(eol - req);
|
||||
if (line_len >= sizeof(line)) {
|
||||
line_len = sizeof(line) - 1;
|
||||
}
|
||||
memcpy(line, req, line_len);
|
||||
line[line_len] = '\0';
|
||||
char *sp1 = strchr(line, ' ');
|
||||
if (!sp1) {
|
||||
return false;
|
||||
}
|
||||
*sp1 = '\0';
|
||||
snprintf(method, method_len, "%s", line);
|
||||
char *uri = sp1 + 1;
|
||||
char *sp2 = strchr(uri, ' ');
|
||||
if (sp2) {
|
||||
*sp2 = '\0';
|
||||
}
|
||||
char *q = strchr(uri, '?');
|
||||
if (q) {
|
||||
*q = '\0';
|
||||
snprintf(query, query_len, "%s", q + 1);
|
||||
}
|
||||
snprintf(path, path_len, "%s", uri);
|
||||
return true;
|
||||
}
|
||||
|
||||
static err_t pump_static(httpserver_conn_t *conn) {
|
||||
if (!conn->pcb || !conn->static_body) {
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
while (conn->hdr_sent < conn->hdr_len) {
|
||||
size_t left = (size_t)(conn->hdr_len - conn->hdr_sent);
|
||||
u16_t space = tcp_sndbuf(conn->pcb);
|
||||
if (space == 0) {
|
||||
tcp_output(conn->pcb);
|
||||
return ERR_OK;
|
||||
}
|
||||
u16_t n = left < space ? (u16_t)left : space;
|
||||
if (n > HS_SEND_CHUNK) {
|
||||
n = HS_SEND_CHUNK;
|
||||
}
|
||||
err_t err = tcp_write(conn->pcb, conn->hdr + conn->hdr_sent, n, TCP_WRITE_FLAG_COPY);
|
||||
if (err == ERR_MEM) {
|
||||
tcp_output(conn->pcb);
|
||||
return ERR_OK;
|
||||
}
|
||||
if (err != ERR_OK) {
|
||||
return close_conn(conn, conn->pcb, ERR_ABRT);
|
||||
}
|
||||
conn->hdr_sent += n;
|
||||
}
|
||||
|
||||
while (conn->static_sent < conn->static_len) {
|
||||
size_t left = conn->static_len - conn->static_sent;
|
||||
u16_t space = tcp_sndbuf(conn->pcb);
|
||||
if (space == 0) {
|
||||
tcp_output(conn->pcb);
|
||||
return ERR_OK;
|
||||
}
|
||||
u16_t n = left < space ? (u16_t)left : space;
|
||||
if (n > HS_SEND_CHUNK) {
|
||||
n = HS_SEND_CHUNK;
|
||||
}
|
||||
err_t err = tcp_write(conn->pcb, conn->static_body + conn->static_sent, n, TCP_WRITE_FLAG_COPY);
|
||||
if (err == ERR_MEM) {
|
||||
tcp_output(conn->pcb);
|
||||
return ERR_OK;
|
||||
}
|
||||
if (err != ERR_OK) {
|
||||
return close_conn(conn, conn->pcb, ERR_ABRT);
|
||||
}
|
||||
conn->static_sent += n;
|
||||
}
|
||||
|
||||
tcp_output(conn->pcb);
|
||||
conn->write_done = true;
|
||||
|
||||
/* Only close after peer has ACKed every queued byte — closing earlier
|
||||
* truncates the response and triggers ERR_CONTENT_LENGTH_MISMATCH. */
|
||||
if (conn->tx_acked >= conn->tx_total) {
|
||||
return close_conn(conn, conn->pcb, ERR_OK);
|
||||
}
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
static err_t ws_send_frame(httpserver_conn_t *conn, uint8_t opcode, const void *payload, size_t len) {
|
||||
if (!conn || conn->mode != CONN_WS || !conn->pcb) {
|
||||
return ERR_VAL;
|
||||
}
|
||||
if (len > HS_WS_PAYLOAD_MAX) {
|
||||
return ERR_VAL;
|
||||
}
|
||||
uint8_t frame[4 + HS_WS_PAYLOAD_MAX];
|
||||
size_t hdr = 2;
|
||||
frame[0] = 0x80 | (opcode & 0x0f);
|
||||
if (len < 126) {
|
||||
frame[1] = (uint8_t)len;
|
||||
} else {
|
||||
frame[1] = 126;
|
||||
frame[2] = (uint8_t)((len >> 8) & 0xff);
|
||||
frame[3] = (uint8_t)(len & 0xff);
|
||||
hdr = 4;
|
||||
}
|
||||
if (len) {
|
||||
memcpy(frame + hdr, payload, len);
|
||||
}
|
||||
if (tcp_write(conn->pcb, frame, (u16_t)(hdr + len), TCP_WRITE_FLAG_COPY) != ERR_OK) {
|
||||
return ERR_MEM;
|
||||
}
|
||||
tcp_output(conn->pcb);
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
static err_t ws_upgrade(httpserver_conn_t *conn, const char *req, const char *path) {
|
||||
const ws_route_t *ws = find_ws_route(conn->server, path);
|
||||
if (!ws) {
|
||||
httpserver_send(conn, 404, "text/plain", "Not Found", 9);
|
||||
return ERR_OK;
|
||||
}
|
||||
char key[64];
|
||||
char accept[29];
|
||||
if (!header_value(req, "Sec-WebSocket-Key", key, sizeof(key))) {
|
||||
return close_conn(conn, conn->pcb, ERR_VAL);
|
||||
}
|
||||
ws_accept_key(key, accept);
|
||||
char resp[180];
|
||||
int n = snprintf(resp, sizeof(resp),
|
||||
"HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: %s\r\n"
|
||||
"\r\n",
|
||||
accept);
|
||||
if (tcp_write(conn->pcb, resp, n, TCP_WRITE_FLAG_COPY) != ERR_OK) {
|
||||
return close_conn(conn, conn->pcb, ERR_ABRT);
|
||||
}
|
||||
tcp_output(conn->pcb);
|
||||
conn->mode = CONN_WS;
|
||||
conn->ws_route = ws;
|
||||
conn->buf_len = 0;
|
||||
conn->headers_complete = false;
|
||||
if (ws->on_open) {
|
||||
ws->on_open(conn);
|
||||
}
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
static err_t ws_handle_frames(httpserver_conn_t *conn) {
|
||||
while (conn->buf_len >= 2) {
|
||||
uint8_t b0 = (uint8_t)conn->buf[0];
|
||||
uint8_t b1 = (uint8_t)conn->buf[1];
|
||||
uint8_t opcode = b0 & 0x0f;
|
||||
bool masked = (b1 & 0x80) != 0;
|
||||
size_t payload_len = b1 & 0x7f;
|
||||
size_t header_len = 2;
|
||||
if (payload_len == 126) {
|
||||
if (conn->buf_len < 4) {
|
||||
break;
|
||||
}
|
||||
payload_len = ((size_t)(uint8_t)conn->buf[2] << 8) | (uint8_t)conn->buf[3];
|
||||
header_len = 4;
|
||||
} else if (payload_len == 127) {
|
||||
return close_conn(conn, conn->pcb, ERR_VAL);
|
||||
}
|
||||
if (masked) {
|
||||
header_len += 4;
|
||||
}
|
||||
if ((size_t)conn->buf_len < header_len + payload_len) {
|
||||
break;
|
||||
}
|
||||
if (payload_len > HS_WS_PAYLOAD_MAX) {
|
||||
return close_conn(conn, conn->pcb, ERR_VAL);
|
||||
}
|
||||
const uint8_t *mask = masked ? (const uint8_t *)&conn->buf[header_len - 4] : NULL;
|
||||
uint8_t payload[HS_WS_PAYLOAD_MAX + 1];
|
||||
memcpy(payload, &conn->buf[header_len], payload_len);
|
||||
if (masked) {
|
||||
for (size_t i = 0; i < payload_len; i++) {
|
||||
payload[i] ^= mask[i & 3];
|
||||
}
|
||||
}
|
||||
payload[payload_len] = '\0';
|
||||
size_t consumed = header_len + payload_len;
|
||||
memmove(conn->buf, conn->buf + consumed, conn->buf_len - consumed);
|
||||
conn->buf_len -= (int)consumed;
|
||||
if (opcode == 0x8) {
|
||||
ws_send_frame(conn, 0x8, NULL, 0);
|
||||
return close_conn(conn, conn->pcb, ERR_OK);
|
||||
}
|
||||
if (opcode == 0x9) {
|
||||
ws_send_frame(conn, 0xA, payload, payload_len);
|
||||
continue;
|
||||
}
|
||||
if (opcode == 0x1 || opcode == 0x2) {
|
||||
if (conn->ws_route && conn->ws_route->on_msg) {
|
||||
conn->ws_route->on_msg(conn, payload, payload_len, opcode == 0x1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
static err_t dispatch_http(httpserver_conn_t *conn) {
|
||||
char method[8];
|
||||
char path[64];
|
||||
char query[64];
|
||||
if (!parse_request_line(conn->buf, method, sizeof(method), path, sizeof(path), query, sizeof(query))) {
|
||||
return close_conn(conn, conn->pcb, ERR_VAL);
|
||||
}
|
||||
bool is_ws = header_has(conn->buf, "Upgrade:") && header_has(conn->buf, "Sec-WebSocket-Key:");
|
||||
if (is_ws && strcmp(method, "GET") == 0) {
|
||||
return ws_upgrade(conn, conn->buf, path);
|
||||
}
|
||||
const route_t *route = find_route(conn->server, method, path);
|
||||
if (!route) {
|
||||
httpserver_send(conn, 404, "text/plain", "Not Found", 9);
|
||||
return ERR_OK;
|
||||
}
|
||||
conn->dispatched = true;
|
||||
route->fn(conn, path, query);
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
static err_t try_dispatch(httpserver_conn_t *conn) {
|
||||
if (conn->dispatched) {
|
||||
return ERR_OK;
|
||||
}
|
||||
if (!conn->headers_complete) {
|
||||
char *end = strstr(conn->buf, "\r\n\r\n");
|
||||
if (!end) {
|
||||
return ERR_OK;
|
||||
}
|
||||
conn->header_end = (int)(end - conn->buf) + 4;
|
||||
conn->headers_complete = true;
|
||||
char cl[16];
|
||||
if (header_value(conn->buf, "Content-Length", cl, sizeof(cl))) {
|
||||
conn->content_length = atoi(cl);
|
||||
} else {
|
||||
conn->content_length = 0;
|
||||
}
|
||||
}
|
||||
int body_have = conn->buf_len - conn->header_end;
|
||||
if (conn->content_length > 0 && body_have < conn->content_length) {
|
||||
return ERR_OK;
|
||||
}
|
||||
return dispatch_http(conn);
|
||||
}
|
||||
|
||||
static err_t on_sent(void *arg, struct tcp_pcb *pcb, u16_t len) {
|
||||
httpserver_conn_t *conn = arg;
|
||||
(void)pcb;
|
||||
if (conn->mode != CONN_HTTP) {
|
||||
return ERR_OK;
|
||||
}
|
||||
conn->tx_acked += len;
|
||||
if (conn->static_body) {
|
||||
return pump_static(conn);
|
||||
}
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
static err_t on_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) {
|
||||
httpserver_conn_t *conn = arg;
|
||||
(void)err;
|
||||
if (!p) {
|
||||
return close_conn(conn, pcb, ERR_OK);
|
||||
}
|
||||
if (p->tot_len > 0) {
|
||||
u16_t space = (u16_t)(sizeof(conn->buf) - 1 - conn->buf_len);
|
||||
u16_t n = p->tot_len > space ? space : p->tot_len;
|
||||
pbuf_copy_partial(p, conn->buf + conn->buf_len, n, 0);
|
||||
conn->buf_len += n;
|
||||
conn->buf[conn->buf_len] = '\0';
|
||||
tcp_recved(pcb, p->tot_len);
|
||||
err_t r = ERR_OK;
|
||||
if (conn->mode == CONN_WS) {
|
||||
r = ws_handle_frames(conn);
|
||||
} else {
|
||||
r = try_dispatch(conn);
|
||||
}
|
||||
pbuf_free(p);
|
||||
return r;
|
||||
}
|
||||
pbuf_free(p);
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
static err_t on_poll(void *arg, struct tcp_pcb *pcb) {
|
||||
httpserver_conn_t *conn = arg;
|
||||
if (conn->mode == CONN_WS) {
|
||||
return ERR_OK;
|
||||
}
|
||||
/* Keep pumping / waiting for ACK on static responses */
|
||||
if (conn->static_body) {
|
||||
return pump_static(conn);
|
||||
}
|
||||
if (conn->dispatched) {
|
||||
return close_conn(conn, pcb, ERR_OK);
|
||||
}
|
||||
return close_conn(conn, pcb, ERR_OK);
|
||||
}
|
||||
|
||||
static void on_err(void *arg, err_t err) {
|
||||
httpserver_conn_t *conn = arg;
|
||||
(void)err;
|
||||
if (conn && conn->mode == CONN_WS && conn->ws_route && conn->ws_route->on_close) {
|
||||
conn->ws_route->on_close(conn);
|
||||
}
|
||||
conn_free(conn);
|
||||
}
|
||||
|
||||
static err_t on_accept(void *arg, struct tcp_pcb *client_pcb, err_t err) {
|
||||
httpserver_t *s = arg;
|
||||
if (err != ERR_OK || !client_pcb) {
|
||||
return ERR_VAL;
|
||||
}
|
||||
httpserver_conn_t *conn = conn_alloc(s, client_pcb);
|
||||
if (!conn) {
|
||||
tcp_abort(client_pcb);
|
||||
return ERR_MEM;
|
||||
}
|
||||
tcp_arg(client_pcb, conn);
|
||||
tcp_sent(client_pcb, on_sent);
|
||||
tcp_recv(client_pcb, on_recv);
|
||||
tcp_poll(client_pcb, on_poll, HS_POLL_INTERVAL);
|
||||
tcp_err(client_pcb, on_err);
|
||||
tcp_nagle_disable(client_pcb);
|
||||
return ERR_OK;
|
||||
}
|
||||
|
||||
httpserver_t *httpserver_create(void) {
|
||||
memset(&g_server, 0, sizeof(g_server));
|
||||
return &g_server;
|
||||
}
|
||||
|
||||
void httpserver_route(httpserver_t *s, const char *method, const char *path, httpserver_handler_t fn) {
|
||||
if (!s || s->route_count >= HS_MAX_ROUTES || !method || !path || !fn) {
|
||||
return;
|
||||
}
|
||||
s->routes[s->route_count].method = method;
|
||||
s->routes[s->route_count].path = path;
|
||||
s->routes[s->route_count].fn = fn;
|
||||
s->route_count++;
|
||||
}
|
||||
|
||||
void httpserver_websocket(httpserver_t *s, const char *path,
|
||||
httpserver_ws_open_t on_open,
|
||||
httpserver_ws_msg_t on_msg,
|
||||
httpserver_ws_close_t on_close) {
|
||||
if (!s || s->ws_route_count >= HS_MAX_WS_ROUTES || !path) {
|
||||
return;
|
||||
}
|
||||
s->ws_routes[s->ws_route_count].path = path;
|
||||
s->ws_routes[s->ws_route_count].on_open = on_open;
|
||||
s->ws_routes[s->ws_route_count].on_msg = on_msg;
|
||||
s->ws_routes[s->ws_route_count].on_close = on_close;
|
||||
s->ws_route_count++;
|
||||
}
|
||||
|
||||
bool httpserver_listen(httpserver_t *s, uint16_t port) {
|
||||
if (!s) {
|
||||
return false;
|
||||
}
|
||||
cyw43_arch_lwip_begin();
|
||||
struct tcp_pcb *pcb = tcp_new_ip_type(IPADDR_TYPE_ANY);
|
||||
if (!pcb) {
|
||||
cyw43_arch_lwip_end();
|
||||
return false;
|
||||
}
|
||||
if (tcp_bind(pcb, IP_ANY_TYPE, port) != ERR_OK) {
|
||||
tcp_close(pcb);
|
||||
cyw43_arch_lwip_end();
|
||||
return false;
|
||||
}
|
||||
s->server_pcb = tcp_listen_with_backlog(pcb, HS_MAX_CONNS);
|
||||
if (!s->server_pcb) {
|
||||
tcp_close(pcb);
|
||||
cyw43_arch_lwip_end();
|
||||
return false;
|
||||
}
|
||||
tcp_arg(s->server_pcb, s);
|
||||
tcp_accept(s->server_pcb, on_accept);
|
||||
cyw43_arch_lwip_end();
|
||||
printf("httpserver: listening on port %u\n", port);
|
||||
return true;
|
||||
}
|
||||
|
||||
void httpserver_send_static(httpserver_conn_t *conn, int status, const char *content_type,
|
||||
const uint8_t *body, size_t body_len,
|
||||
const char *content_encoding) {
|
||||
if (!conn || conn->mode != CONN_HTTP || !conn->pcb) {
|
||||
return;
|
||||
}
|
||||
if (!content_type) {
|
||||
content_type = "application/octet-stream";
|
||||
}
|
||||
if (content_encoding && content_encoding[0]) {
|
||||
conn->hdr_len = snprintf(conn->hdr, sizeof(conn->hdr),
|
||||
"HTTP/1.1 %d %s\r\n"
|
||||
"Content-Type: %s\r\n"
|
||||
"Content-Encoding: %s\r\n"
|
||||
"Content-Length: %u\r\n"
|
||||
"Connection: close\r\n"
|
||||
"\r\n",
|
||||
status, status_text(status), content_type, content_encoding,
|
||||
(unsigned)body_len);
|
||||
} else {
|
||||
conn->hdr_len = snprintf(conn->hdr, sizeof(conn->hdr),
|
||||
"HTTP/1.1 %d %s\r\n"
|
||||
"Content-Type: %s\r\n"
|
||||
"Content-Length: %u\r\n"
|
||||
"Connection: close\r\n"
|
||||
"\r\n",
|
||||
status, status_text(status), content_type, (unsigned)body_len);
|
||||
}
|
||||
conn->hdr_sent = 0;
|
||||
conn->static_body = body ? body : (const uint8_t *)"";
|
||||
conn->static_len = body_len;
|
||||
conn->static_sent = 0;
|
||||
conn->tx_acked = 0;
|
||||
conn->tx_total = (size_t)conn->hdr_len + body_len;
|
||||
conn->write_done = false;
|
||||
pump_static(conn);
|
||||
}
|
||||
|
||||
void httpserver_send(httpserver_conn_t *conn, int status, const char *content_type,
|
||||
const void *body, size_t body_len) {
|
||||
httpserver_send_static(conn, status, content_type, (const uint8_t *)body, body_len, NULL);
|
||||
}
|
||||
|
||||
void httpserver_send_html(httpserver_conn_t *conn, const char *html) {
|
||||
if (!html) {
|
||||
html = "";
|
||||
}
|
||||
httpserver_send(conn, 200, "text/html; charset=utf-8", html, strlen(html));
|
||||
}
|
||||
|
||||
const char *httpserver_request_body(httpserver_conn_t *conn, size_t *len_out) {
|
||||
if (!conn || conn->header_end < 0) {
|
||||
if (len_out) {
|
||||
*len_out = 0;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
size_t len = (size_t)(conn->buf_len - conn->header_end);
|
||||
if (conn->content_length >= 0 && (size_t)conn->content_length < len) {
|
||||
len = (size_t)conn->content_length;
|
||||
}
|
||||
if (len_out) {
|
||||
*len_out = len;
|
||||
}
|
||||
return conn->buf + conn->header_end;
|
||||
}
|
||||
|
||||
bool httpserver_ws_send(httpserver_conn_t *ws, const void *data, size_t len, bool text) {
|
||||
return ws_send_frame(ws, text ? 0x1 : 0x2, data, len) == ERR_OK;
|
||||
}
|
||||
|
||||
void httpserver_ws_broadcast(httpserver_t *s, const void *data, size_t len, bool text) {
|
||||
if (!s) {
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < HS_MAX_CONNS; i++) {
|
||||
if (s->conns[i].mode == CONN_WS) {
|
||||
httpserver_ws_send(&s->conns[i], data, len, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
httpserver_t *httpserver_conn_server(httpserver_conn_t *conn) {
|
||||
return conn ? conn->server : NULL;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#ifndef HTTPSERVER_H
|
||||
#define HTTPSERVER_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct httpserver httpserver_t;
|
||||
typedef struct httpserver_conn httpserver_conn_t;
|
||||
|
||||
typedef void (*httpserver_handler_t)(httpserver_conn_t *conn, const char *path, const char *query);
|
||||
typedef void (*httpserver_ws_open_t)(httpserver_conn_t *ws);
|
||||
typedef void (*httpserver_ws_msg_t)(httpserver_conn_t *ws, const uint8_t *data, size_t len, bool text);
|
||||
typedef void (*httpserver_ws_close_t)(httpserver_conn_t *ws);
|
||||
|
||||
httpserver_t *httpserver_create(void);
|
||||
|
||||
void httpserver_route(httpserver_t *s, const char *method, const char *path, httpserver_handler_t fn);
|
||||
|
||||
void httpserver_websocket(httpserver_t *s, const char *path,
|
||||
httpserver_ws_open_t on_open,
|
||||
httpserver_ws_msg_t on_msg,
|
||||
httpserver_ws_close_t on_close);
|
||||
|
||||
bool httpserver_listen(httpserver_t *s, uint16_t port);
|
||||
|
||||
void httpserver_send(httpserver_conn_t *conn, int status, const char *content_type,
|
||||
const void *body, size_t body_len);
|
||||
|
||||
/* Stream a large const body (no copy of entire file into conn buffer).
|
||||
* content_encoding may be NULL, or e.g. "gzip". */
|
||||
void httpserver_send_static(httpserver_conn_t *conn, int status, const char *content_type,
|
||||
const uint8_t *body, size_t body_len,
|
||||
const char *content_encoding);
|
||||
|
||||
void httpserver_send_html(httpserver_conn_t *conn, const char *html);
|
||||
|
||||
/* POST/PUT body after headers (points into connection buffer). */
|
||||
const char *httpserver_request_body(httpserver_conn_t *conn, size_t *len_out);
|
||||
|
||||
bool httpserver_ws_send(httpserver_conn_t *ws, const void *data, size_t len, bool text);
|
||||
|
||||
void httpserver_ws_broadcast(httpserver_t *s, const void *data, size_t len, bool text);
|
||||
|
||||
httpserver_t *httpserver_conn_server(httpserver_conn_t *conn);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct RGB {
|
||||
uint8_t r = 0;
|
||||
uint8_t g = 0;
|
||||
uint8_t b = 0;
|
||||
};
|
||||
|
||||
class Preset {
|
||||
public:
|
||||
std::string p = "off";
|
||||
int d = 100;
|
||||
int b = 127;
|
||||
std::vector<RGB> c{{255, 255, 255}};
|
||||
bool a = true;
|
||||
int n1 = 0, n2 = 0, n3 = 0, n4 = 0;
|
||||
int n5 = 0, n6 = 0, n7 = 0, n8 = 0;
|
||||
|
||||
Preset() = default;
|
||||
explicit Preset(std::string pattern) : p(std::move(pattern)) {}
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
#include "leds/presets.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include "patterns/patterns.hpp"
|
||||
|
||||
namespace {
|
||||
struct StripConfig { uint pin, count, midpoint; };
|
||||
constexpr StripConfig kConfig[] = {
|
||||
{6, 291, 291 / 2}, {29, 290, 290 / 2 - 1}, {3, 283, 283 / 2},
|
||||
{28, 278, 278 / 2 - 1}, {2, 278, 275 / 2}, {0, 283, 278 / 2 - 1},
|
||||
{4, 290, 283 / 2}, {7, 291, 290 / 2 - 1},
|
||||
};
|
||||
}
|
||||
|
||||
Presets::Presets() {
|
||||
for (size_t i = 0; i < kStripCount; ++i) {
|
||||
strips[i] = std::make_unique<WS2812B>(kConfig[i].count, kConfig[i].pin, i);
|
||||
strip_midpoints[i] = kConfig[i].midpoint;
|
||||
scale_map[i].resize(kConfig[0].count);
|
||||
for (size_t led = 0; led < scale_map[i].size(); ++led)
|
||||
scale_map[i][led] = led * kConfig[i].count / kConfig[0].count;
|
||||
}
|
||||
}
|
||||
Presets::~Presets() = default;
|
||||
|
||||
std::unique_ptr<Pattern> Presets::make_pattern(const std::string& name) const {
|
||||
#define MAKE(name) if (name == #name) return std::make_unique<name>();
|
||||
if (name == "off" || name == "on") return nullptr;
|
||||
if (name == "blink") return std::make_unique<Blink>();
|
||||
if (name == "rainbow") return std::make_unique<Rainbow>();
|
||||
if (name == "pulse") return std::make_unique<Pulse>();
|
||||
if (name == "transition") return std::make_unique<Transition>();
|
||||
if (name == "chase") return std::make_unique<Chase>();
|
||||
if (name == "circle") return std::make_unique<Circle>();
|
||||
if (name == "roll") return std::make_unique<Roll>();
|
||||
if (name == "calibration") return std::make_unique<Calibration>();
|
||||
if (name == "test") return std::make_unique<Test>();
|
||||
if (name == "grab") return std::make_unique<Grab>();
|
||||
if (name == "spin") return std::make_unique<Spin>();
|
||||
if (name == "lift") return std::make_unique<Lift>();
|
||||
if (name == "flare") return std::make_unique<Flare>();
|
||||
if (name == "hook") return std::make_unique<Hook>();
|
||||
if (name == "pose") return std::make_unique<Pose>();
|
||||
if (name == "point") return std::make_unique<Point>();
|
||||
if (name == "scale_test") return std::make_unique<ScaleTest>();
|
||||
return nullptr;
|
||||
#undef MAKE
|
||||
}
|
||||
|
||||
bool Presets::select(const std::string& name, int next_step) {
|
||||
auto saved = presets.find(name);
|
||||
Preset* preset = saved == presets.end() ? nullptr : &saved->second;
|
||||
const std::string pattern = preset ? preset->p : name;
|
||||
if (pattern == "off") { off(); current.reset(); selected = name; step = 0; return true; }
|
||||
if (pattern == "on") {
|
||||
static Preset default_on("on");
|
||||
on(preset ? preset : &default_on); current.reset(); selected = name; return true;
|
||||
}
|
||||
current = make_pattern(pattern);
|
||||
if (!current) return false;
|
||||
static Preset built_in;
|
||||
if (!preset) { built_in = Preset(pattern); preset = &built_in; }
|
||||
if (next_step >= 0) step = next_step;
|
||||
else if (selected != name) step = 0;
|
||||
current->start(*this, preset);
|
||||
selected = name;
|
||||
return true;
|
||||
}
|
||||
bool Presets::edit(const std::string& name, const Preset& preset) { presets[name] = preset; return true; }
|
||||
bool Presets::remove(const std::string& name) { return presets.erase(name) != 0; }
|
||||
void Presets::tick() { if (current && !current->tick()) current.reset(); }
|
||||
void Presets::fill(RGB color) { for (auto& strip : strips) strip->fill(color); }
|
||||
void Presets::fill_n(RGB color, int first, int last) {
|
||||
first = std::max(0, first); last = std::min<int>(kConfig[0].count, last);
|
||||
for (int i = first; i < last; ++i) for (size_t s = 0; s < kStripCount; ++s) set(s, i, color);
|
||||
}
|
||||
bool Presets::set(size_t strip, int index, RGB color) {
|
||||
if (strip >= kStripCount || index < 0 || index >= static_cast<int>(scale_map[strip].size())) return false;
|
||||
strips[strip]->set(scale_map[strip][index], color); return true;
|
||||
}
|
||||
RGB Presets::apply_brightness(RGB color, int local) const {
|
||||
const int effective = std::clamp(local, 0, 255) * b / 255;
|
||||
return {static_cast<uint8_t>(color.r * effective / 255), static_cast<uint8_t>(color.g * effective / 255),
|
||||
static_cast<uint8_t>(color.b * effective / 255)};
|
||||
}
|
||||
void Presets::show_all() { for (auto& strip : strips) strip->show(); }
|
||||
void Presets::show_all_parallel() {
|
||||
uint32_t mask = 0;
|
||||
for (auto& strip : strips) { strip->prepare_show(); mask |= 1u << strip->dma_channel; }
|
||||
dma_start_channel_mask(mask);
|
||||
}
|
||||
void Presets::off() { fill({0, 0, 0}); show_all_parallel(); }
|
||||
void Presets::on(Preset* preset) {
|
||||
const RGB color = preset && !preset->c.empty() ? preset->c[0] : RGB{255, 255, 255};
|
||||
fill(apply_brightness(color, preset ? preset->b : 255)); show_all_parallel();
|
||||
}
|
||||
uint16_t Presets::strip_length(size_t strip) const { return strip < kStripCount ? strips[strip]->num_leds : 0; }
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "leds/preset.hpp"
|
||||
#include "leds/ws2812.hpp"
|
||||
|
||||
class Pattern;
|
||||
|
||||
class Presets {
|
||||
public:
|
||||
static constexpr size_t kStripCount = 8;
|
||||
Presets();
|
||||
~Presets();
|
||||
|
||||
bool select(const std::string& name, int step = -1);
|
||||
bool edit(const std::string& name, const Preset& preset);
|
||||
bool remove(const std::string& name);
|
||||
void tick();
|
||||
void fill(RGB color);
|
||||
void fill_n(RGB color, int first, int last);
|
||||
bool set(size_t strip, int reference_index, RGB color);
|
||||
RGB apply_brightness(RGB color, int local = 255) const;
|
||||
void show_all();
|
||||
void show_all_parallel();
|
||||
void off();
|
||||
void on(Preset* preset);
|
||||
uint16_t strip_length(size_t strip) const;
|
||||
|
||||
std::array<std::unique_ptr<WS2812B>, kStripCount> strips;
|
||||
std::array<uint16_t, kStripCount> strip_midpoints{};
|
||||
std::array<std::vector<uint16_t>, kStripCount> scale_map;
|
||||
std::unordered_map<std::string, Preset> presets;
|
||||
std::unique_ptr<Pattern> current;
|
||||
std::string selected;
|
||||
int step = 0;
|
||||
int last_roll_head = 0;
|
||||
uint8_t b = 255;
|
||||
|
||||
private:
|
||||
std::unique_ptr<Pattern> make_pattern(const std::string& name) const;
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
#include "leds/ws2812.hpp"
|
||||
|
||||
#include "hardware/clocks.h"
|
||||
#include "hardware/gpio.h"
|
||||
#include "leds/preset.hpp"
|
||||
|
||||
namespace {
|
||||
constexpr uint T1 = 2, T2 = 5, T3 = 3;
|
||||
const uint16_t ws2812_instructions[] = {
|
||||
static_cast<uint16_t>(pio_encode_out(pio_x, 1) | pio_encode_sideset(1, 0) | pio_encode_delay(T3 - 1)),
|
||||
static_cast<uint16_t>(pio_encode_jmp_not_x(3) | pio_encode_sideset(1, 1) | pio_encode_delay(T1 - 1)),
|
||||
static_cast<uint16_t>(pio_encode_jmp(0) | pio_encode_sideset(1, 1) | pio_encode_delay(T2 - 1)),
|
||||
static_cast<uint16_t>(pio_encode_nop() | pio_encode_sideset(1, 0) | pio_encode_delay(T2 - 1)),
|
||||
};
|
||||
const pio_program ws2812_program = {
|
||||
.instructions = ws2812_instructions, .length = 4, .origin = -1,
|
||||
};
|
||||
bool pio_program_added[2] = {};
|
||||
uint pio_offsets[2] = {};
|
||||
|
||||
uint program_offset(PIO pio) {
|
||||
const uint index = pio == pio0 ? 0 : 1;
|
||||
if (!pio_program_added[index]) {
|
||||
pio_offsets[index] = pio_add_program(pio, &ws2812_program);
|
||||
pio_program_added[index] = true;
|
||||
}
|
||||
return pio_offsets[index];
|
||||
}
|
||||
} // namespace
|
||||
|
||||
WS2812B::WS2812B(uint16_t count, uint pin, uint strip_index, float level)
|
||||
: num_leds(count), brightness(level), buffer(static_cast<size_t>(count) * 3),
|
||||
pio(strip_index < 4 ? pio0 : pio1), sm(strip_index % 4), pin_(pin) {
|
||||
const uint offset = program_offset(pio);
|
||||
pio_gpio_init(pio, pin_);
|
||||
pio_sm_set_consecutive_pindirs(pio, sm, pin_, 1, true);
|
||||
pio_sm_config config = pio_get_default_sm_config();
|
||||
sm_config_set_wrap(&config, offset, offset + 3);
|
||||
sm_config_set_sideset(&config, 1, false, false);
|
||||
sm_config_set_sideset_pins(&config, pin_);
|
||||
sm_config_set_out_shift(&config, false, true, 8);
|
||||
sm_config_set_fifo_join(&config, PIO_FIFO_JOIN_TX);
|
||||
sm_config_set_clkdiv(&config, static_cast<float>(clock_get_hz(clk_sys)) / 8000000.0f);
|
||||
pio_sm_init(pio, sm, offset, &config);
|
||||
pio_sm_set_enabled(pio, sm, true);
|
||||
|
||||
dma_channel = dma_claim_unused_channel(true);
|
||||
dma_channel_config dma_config = dma_channel_get_default_config(dma_channel);
|
||||
channel_config_set_transfer_data_size(&dma_config, DMA_SIZE_8);
|
||||
channel_config_set_dreq(&dma_config, pio_get_dreq(pio, sm, true));
|
||||
channel_config_set_read_increment(&dma_config, true);
|
||||
channel_config_set_write_increment(&dma_config, false);
|
||||
dma_channel_configure(dma_channel, &dma_config, &pio->txf[sm], nullptr,
|
||||
buffer.size(), false);
|
||||
}
|
||||
|
||||
WS2812B::~WS2812B() {
|
||||
if (dma_channel >= 0) dma_channel_unclaim(dma_channel);
|
||||
}
|
||||
|
||||
void WS2812B::set(uint16_t index, RGB color) {
|
||||
if (index >= num_leds) return;
|
||||
const size_t pos = static_cast<size_t>(index) * 3;
|
||||
buffer[pos] = static_cast<uint8_t>(color.g * brightness);
|
||||
buffer[pos + 1] = static_cast<uint8_t>(color.r * brightness);
|
||||
buffer[pos + 2] = static_cast<uint8_t>(color.b * brightness);
|
||||
}
|
||||
|
||||
void WS2812B::fill(RGB color) {
|
||||
for (uint16_t i = 0; i < num_leds; ++i) set(i, color);
|
||||
}
|
||||
|
||||
void WS2812B::prepare_show(const uint8_t* source, size_t offset) {
|
||||
if (!source) source = buffer.data();
|
||||
dma_channel_set_read_addr(dma_channel, source + offset, false);
|
||||
dma_channel_set_trans_count(dma_channel, buffer.size(), false);
|
||||
}
|
||||
|
||||
void WS2812B::trigger() { dma_channel_start(dma_channel); }
|
||||
void WS2812B::show(const uint8_t* source, size_t offset) {
|
||||
prepare_show(source, offset);
|
||||
trigger();
|
||||
}
|
||||
bool WS2812B::busy() const { return dma_channel_is_busy(dma_channel); }
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include "hardware/dma.h"
|
||||
#include "hardware/pio.h"
|
||||
|
||||
struct RGB;
|
||||
|
||||
class WS2812B {
|
||||
public:
|
||||
WS2812B(uint16_t num_leds, uint pin, uint strip_index, float brightness = 1.0f);
|
||||
~WS2812B();
|
||||
WS2812B(const WS2812B&) = delete;
|
||||
WS2812B& operator=(const WS2812B&) = delete;
|
||||
|
||||
void fill(RGB color);
|
||||
void set(uint16_t index, RGB color);
|
||||
void show(const uint8_t* buffer = nullptr, size_t offset = 0);
|
||||
void prepare_show(const uint8_t* buffer = nullptr, size_t offset = 0);
|
||||
void trigger();
|
||||
bool busy() const;
|
||||
|
||||
uint16_t num_leds;
|
||||
float brightness;
|
||||
std::vector<uint8_t> buffer;
|
||||
int dma_channel = -1;
|
||||
PIO pio = pio0;
|
||||
uint sm = 0;
|
||||
|
||||
private:
|
||||
uint pin_;
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef _LWIPOPTS_H
|
||||
#define _LWIPOPTS_H
|
||||
|
||||
#ifndef NO_SYS
|
||||
#define NO_SYS 1
|
||||
#endif
|
||||
#ifndef LWIP_SOCKET
|
||||
#define LWIP_SOCKET 0
|
||||
#endif
|
||||
#if PICO_CYW43_ARCH_POLL
|
||||
#define MEM_LIBC_MALLOC 1
|
||||
#else
|
||||
#define MEM_LIBC_MALLOC 0
|
||||
#endif
|
||||
#define MEM_ALIGNMENT 4
|
||||
#ifndef MEM_SIZE
|
||||
#define MEM_SIZE 16000
|
||||
#endif
|
||||
#define MEMP_NUM_TCP_SEG 32
|
||||
#define MEMP_NUM_ARP_QUEUE 10
|
||||
#define PBUF_POOL_SIZE 24
|
||||
#define LWIP_ARP 1
|
||||
#define LWIP_ETHERNET 1
|
||||
#define LWIP_ICMP 1
|
||||
#define LWIP_RAW 1
|
||||
#define TCP_WND (8 * TCP_MSS)
|
||||
#define TCP_MSS 1460
|
||||
#define TCP_SND_BUF (8 * TCP_MSS)
|
||||
#define TCP_SND_QUEUELEN ((4 * (TCP_SND_BUF) + (TCP_MSS - 1)) / (TCP_MSS))
|
||||
#define LWIP_NETIF_STATUS_CALLBACK 1
|
||||
#define LWIP_NETIF_LINK_CALLBACK 1
|
||||
#define LWIP_NETIF_HOSTNAME 1
|
||||
#define LWIP_NETCONN 0
|
||||
#define MEM_STATS 0
|
||||
#define SYS_STATS 0
|
||||
#define MEMP_STATS 0
|
||||
#define LINK_STATS 0
|
||||
#define LWIP_CHKSUM_ALGORITHM 3
|
||||
#define LWIP_DHCP 1
|
||||
#define LWIP_IPV4 1
|
||||
#define LWIP_TCP 1
|
||||
#define LWIP_UDP 1
|
||||
#define LWIP_DNS 1
|
||||
#define LWIP_TCP_KEEPALIVE 1
|
||||
#define LWIP_NETIF_TX_SINGLE_PBUF 1
|
||||
#define DHCP_DOES_ARP_CHECK 0
|
||||
#define LWIP_DHCP_DOES_ACD_CHECK 0
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,121 @@
|
||||
# This is a copy of <PICO_SDK_PATH>/external/pico_sdk_import.cmake
|
||||
|
||||
# This can be dropped into an external project to help locate this SDK
|
||||
# It should be include()ed prior to project()
|
||||
|
||||
# Copyright 2020 (c) 2020 Raspberry Pi (Trading) Ltd.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
|
||||
# following conditions are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
|
||||
# disclaimer.
|
||||
#
|
||||
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
|
||||
# disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
#
|
||||
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
|
||||
# derived from this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
|
||||
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH))
|
||||
set(PICO_SDK_PATH $ENV{PICO_SDK_PATH})
|
||||
message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')")
|
||||
endif ()
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT))
|
||||
set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT})
|
||||
message("Using PICO_SDK_FETCH_FROM_GIT from environment ('${PICO_SDK_FETCH_FROM_GIT}')")
|
||||
endif ()
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH))
|
||||
set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH})
|
||||
message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')")
|
||||
endif ()
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_TAG} AND (NOT PICO_SDK_FETCH_FROM_GIT_TAG))
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG $ENV{PICO_SDK_FETCH_FROM_GIT_TAG})
|
||||
message("Using PICO_SDK_FETCH_FROM_GIT_TAG from environment ('${PICO_SDK_FETCH_FROM_GIT_TAG}')")
|
||||
endif ()
|
||||
|
||||
if (PICO_SDK_FETCH_FROM_GIT AND NOT PICO_SDK_FETCH_FROM_GIT_TAG)
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG "master")
|
||||
message("Using master as default value for PICO_SDK_FETCH_FROM_GIT_TAG")
|
||||
endif()
|
||||
|
||||
set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK")
|
||||
set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable")
|
||||
set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK")
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG "${PICO_SDK_FETCH_FROM_GIT_TAG}" CACHE FILEPATH "release tag for SDK")
|
||||
|
||||
if (NOT PICO_SDK_PATH)
|
||||
if (PICO_SDK_FETCH_FROM_GIT)
|
||||
include(FetchContent)
|
||||
set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR})
|
||||
if (PICO_SDK_FETCH_FROM_GIT_PATH)
|
||||
get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")
|
||||
endif ()
|
||||
FetchContent_Declare(
|
||||
pico_sdk
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
|
||||
)
|
||||
|
||||
if (NOT pico_sdk)
|
||||
message("Downloading Raspberry Pi Pico SDK")
|
||||
# GIT_SUBMODULES_RECURSE was added in 3.17
|
||||
if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.17.0")
|
||||
FetchContent_Populate(
|
||||
pico_sdk
|
||||
QUIET
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
|
||||
GIT_SUBMODULES_RECURSE FALSE
|
||||
|
||||
SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-src
|
||||
BINARY_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-build
|
||||
SUBBUILD_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-subbuild
|
||||
)
|
||||
else ()
|
||||
FetchContent_Populate(
|
||||
pico_sdk
|
||||
QUIET
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
|
||||
|
||||
SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-src
|
||||
BINARY_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-build
|
||||
SUBBUILD_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-subbuild
|
||||
)
|
||||
endif ()
|
||||
|
||||
set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR})
|
||||
endif ()
|
||||
set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE})
|
||||
else ()
|
||||
message(FATAL_ERROR
|
||||
"SDK location was not specified. Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT to on to fetch from git."
|
||||
)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
get_filename_component(PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")
|
||||
if (NOT EXISTS ${PICO_SDK_PATH})
|
||||
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found")
|
||||
endif ()
|
||||
|
||||
set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake)
|
||||
if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE})
|
||||
message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' does not appear to contain the Raspberry Pi Pico SDK")
|
||||
endif ()
|
||||
|
||||
set(PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to the Raspberry Pi Pico SDK" FORCE)
|
||||
|
||||
include(${PICO_SDK_INIT_CMAKE_FILE})
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minify + gzip a web asset, then emit a C byte-array header."""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def minify_html(text: str) -> str:
|
||||
text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
|
||||
text = re.sub(r">\s+<", "><", text)
|
||||
text = re.sub(r"\s+", " ", text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def minify_css(text: str) -> str:
|
||||
text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
|
||||
text = re.sub(r"\s+", " ", text)
|
||||
text = re.sub(r"\s*([{};:,>~+])\s*", r"\1", text)
|
||||
text = re.sub(r";}", "}", text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def minify_js(text: str, src: Path) -> str:
|
||||
terser = shutil.which("terser")
|
||||
cmd = None
|
||||
if terser:
|
||||
cmd = [terser, str(src), "--compress", "--mangle"]
|
||||
elif shutil.which("npx"):
|
||||
cmd = ["npx", "--yes", "terser", str(src), "--compress", "--mangle"]
|
||||
if cmd:
|
||||
try:
|
||||
r = subprocess.run(cmd, check=True, capture_output=True, text=True)
|
||||
if r.stdout.strip():
|
||||
return r.stdout
|
||||
except (subprocess.CalledProcessError, OSError) as e:
|
||||
print(f"embed_file: terser failed ({e}); using light JS minify", file=sys.stderr)
|
||||
|
||||
# Light fallback: drop block/line comments and collapse blank lines.
|
||||
text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
|
||||
text = re.sub(r"(?m)^\s*//.*$", "", text)
|
||||
text = re.sub(r"\n\s*\n+", "\n", text)
|
||||
return text.strip() + "\n"
|
||||
|
||||
|
||||
def minify(src: Path, data: bytes) -> bytes:
|
||||
suffix = src.suffix.lower()
|
||||
text = data.decode("utf-8")
|
||||
if suffix in (".html", ".htm"):
|
||||
return minify_html(text).encode("utf-8")
|
||||
if suffix == ".css":
|
||||
return minify_css(text).encode("utf-8")
|
||||
if suffix == ".js":
|
||||
return minify_js(text, src).encode("utf-8")
|
||||
return data
|
||||
|
||||
|
||||
def write_header(out: Path, symbol: str, src: Path, data: bytes, raw_len: int, min_len: int) -> None:
|
||||
lines = [
|
||||
f"/* auto-generated from {src} (minified+gzip) — do not edit */",
|
||||
f"/* raw={raw_len} minified={min_len} gzipped={len(data)} */",
|
||||
"#pragma once",
|
||||
"#include <stddef.h>",
|
||||
"#include <stdint.h>",
|
||||
f"static const uint8_t {symbol}[] = {{",
|
||||
]
|
||||
for i in range(0, len(data), 16):
|
||||
chunk = ", ".join(f"0x{b:02x}" for b in data[i : i + 16])
|
||||
lines.append(f" {chunk},")
|
||||
lines.append("};")
|
||||
lines.append(f"static const size_t {symbol}_len = sizeof({symbol});")
|
||||
lines.append("")
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text("\n".join(lines), encoding="utf-8")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 4:
|
||||
print(f"usage: {sys.argv[0]} <input> <symbol> <output.h>", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
src = Path(sys.argv[1])
|
||||
symbol = sys.argv[2]
|
||||
out = Path(sys.argv[3])
|
||||
raw = src.read_bytes()
|
||||
mini = minify(src, raw)
|
||||
gz = gzip.compress(mini, compresslevel=9, mtime=0)
|
||||
write_header(out, symbol, src, gz, len(raw), len(mini))
|
||||
print(f"embed {src.name}: {len(raw)} -> {len(mini)} min -> {len(gz)} gzip")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#include <stdio.h>
|
||||
|
||||
#include "pico/stdlib.h"
|
||||
#include "pico/cyw43_arch.h"
|
||||
#include "cyw43.h"
|
||||
#include "lwip/ip_addr.h"
|
||||
|
||||
#include "ap.h"
|
||||
#include "dhcpserver.h"
|
||||
|
||||
static dhcp_server_t dhcp_server;
|
||||
|
||||
bool ap_start(void) {
|
||||
cyw43_arch_enable_ap_mode(AP_SSID, AP_PASS, CYW43_AUTH_WPA2_AES_PSK);
|
||||
cyw43_wifi_pm(&cyw43_state, CYW43_NONE_PM);
|
||||
|
||||
ip_addr_t gw, mask;
|
||||
|
||||
gw.addr = PP_HTONL(CYW43_DEFAULT_IP_AP_ADDRESS);
|
||||
mask.addr = PP_HTONL(CYW43_DEFAULT_IP_MASK);
|
||||
|
||||
dhcp_server_init(&dhcp_server, &gw, &mask);
|
||||
|
||||
|
||||
printf("AP up: SSID=%s pass=%s ip=%s\n",
|
||||
AP_SSID, AP_PASS, ipaddr_ntoa(&gw));
|
||||
|
||||
return true;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
#ifndef AP_H
|
||||
#define AP_H
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#define AP_SSID "hoop"
|
||||
#define AP_PASS "hoop-1234"
|
||||
|
||||
// Start soft-AP + DHCP. cyw43_arch_init() must already have succeeded.
|
||||
bool ap_start(void);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,65 @@
|
||||
#include "cmd_queue.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include "hardware/sync.h"
|
||||
#include "pico/multicore.h"
|
||||
|
||||
/* RP2350 SIO FIFO is 4 entries deep; keep the pool the same size. */
|
||||
#define CMD_QUEUE_SIZE 4
|
||||
|
||||
static led_cmd_t slots[CMD_QUEUE_SIZE];
|
||||
static uint8_t free_stack[CMD_QUEUE_SIZE];
|
||||
static int free_top;
|
||||
static bool inited;
|
||||
|
||||
void cmd_queue_init(void) {
|
||||
free_top = 0;
|
||||
for (int i = 0; i < CMD_QUEUE_SIZE; i++) {
|
||||
free_stack[free_top++] = (uint8_t)i;
|
||||
}
|
||||
inited = true;
|
||||
}
|
||||
|
||||
/* Core0: reclaim slot indices returned by core1. */
|
||||
static void reclaim_returns(void) {
|
||||
while (multicore_fifo_rvalid()) {
|
||||
uint32_t idx = multicore_fifo_pop_blocking();
|
||||
if (idx < CMD_QUEUE_SIZE && free_top < CMD_QUEUE_SIZE) {
|
||||
free_stack[free_top++] = (uint8_t)idx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool cmd_queue_push(const led_cmd_t *cmd) {
|
||||
if (!inited || !cmd) {
|
||||
return false;
|
||||
}
|
||||
reclaim_returns();
|
||||
if (free_top == 0) {
|
||||
return false;
|
||||
}
|
||||
uint8_t idx = free_stack[--free_top];
|
||||
slots[idx] = *cmd;
|
||||
__dmb();
|
||||
if (!multicore_fifo_push_timeout_us(idx, 0)) {
|
||||
free_stack[free_top++] = idx;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool cmd_queue_pop(led_cmd_t *cmd) {
|
||||
if (!cmd || !multicore_fifo_rvalid()) {
|
||||
return false;
|
||||
}
|
||||
uint32_t idx = multicore_fifo_pop_blocking();
|
||||
if (idx >= CMD_QUEUE_SIZE) {
|
||||
return false;
|
||||
}
|
||||
__dmb();
|
||||
*cmd = slots[idx];
|
||||
/* Return slot ownership to core0 via the opposite FIFO. */
|
||||
multicore_fifo_push_blocking(idx);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#ifndef CMD_QUEUE_H
|
||||
#define CMD_QUEUE_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef enum {
|
||||
CMD_SELECT = 1,
|
||||
CMD_EDIT,
|
||||
CMD_DELETE,
|
||||
CMD_SAVE,
|
||||
CMD_BRIGHTNESS,
|
||||
} cmd_type_t;
|
||||
|
||||
#define CMD_NAME_MAX 32
|
||||
#define CMD_PATTERN_MAX 32
|
||||
#define CMD_COLORS_MAX 16
|
||||
|
||||
typedef struct {
|
||||
uint8_t r;
|
||||
uint8_t g;
|
||||
uint8_t b;
|
||||
} cmd_rgb_t;
|
||||
|
||||
/* Typed preset fields for CMD_EDIT (parsed from JSON on core 0). */
|
||||
typedef struct {
|
||||
char pattern[CMD_PATTERN_MAX];
|
||||
int d;
|
||||
int b;
|
||||
cmd_rgb_t c[CMD_COLORS_MAX];
|
||||
uint8_t c_count;
|
||||
int n1, n2, n3, n4;
|
||||
int n5, n6, n7, n8;
|
||||
} cmd_preset_t;
|
||||
|
||||
typedef struct {
|
||||
cmd_type_t type;
|
||||
char name[CMD_NAME_MAX];
|
||||
union {
|
||||
cmd_preset_t edit;
|
||||
int brightness;
|
||||
} u;
|
||||
} led_cmd_t;
|
||||
|
||||
/* Call on core0 before multicore_launch_core1. */
|
||||
void cmd_queue_init(void);
|
||||
|
||||
bool cmd_queue_push(const led_cmd_t *cmd);
|
||||
bool cmd_queue_pop(led_cmd_t *cmd);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,74 @@
|
||||
#include "flash_store.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "hardware/flash.h"
|
||||
#include "hardware/sync.h"
|
||||
#include "pico/stdlib.h"
|
||||
|
||||
/* Two sectors near end of flash: buttons, presets */
|
||||
#ifndef PICO_FLASH_SIZE_BYTES
|
||||
#define PICO_FLASH_SIZE_BYTES (2 * 1024 * 1024)
|
||||
#endif
|
||||
|
||||
#define STORE_MAGIC 0x484F4F50u /* HOOP */
|
||||
|
||||
typedef struct {
|
||||
uint32_t magic;
|
||||
uint32_t len;
|
||||
char name[16];
|
||||
char data[FLASH_STORE_MAX - 24];
|
||||
} store_blob_t;
|
||||
|
||||
_Static_assert(sizeof(store_blob_t) <= FLASH_SECTOR_SIZE, "blob too big");
|
||||
|
||||
static uint32_t slot_offset(const char *name) {
|
||||
uint32_t base = PICO_FLASH_SIZE_BYTES - 2 * FLASH_SECTOR_SIZE;
|
||||
if (strcmp(name, "buttons") == 0) {
|
||||
return base;
|
||||
}
|
||||
return base + FLASH_SECTOR_SIZE; /* presets */
|
||||
}
|
||||
|
||||
bool flash_store_load(const char *name, char *out, size_t out_len, size_t *out_size) {
|
||||
if (!name || !out || out_len == 0) {
|
||||
return false;
|
||||
}
|
||||
const store_blob_t *blob = (const store_blob_t *)(XIP_BASE + slot_offset(name));
|
||||
if (blob->magic != STORE_MAGIC || blob->len == 0 || blob->len >= sizeof(blob->data)) {
|
||||
return false;
|
||||
}
|
||||
if (strncmp(blob->name, name, sizeof(blob->name)) != 0) {
|
||||
return false;
|
||||
}
|
||||
size_t n = blob->len;
|
||||
if (n >= out_len) {
|
||||
n = out_len - 1;
|
||||
}
|
||||
memcpy(out, blob->data, n);
|
||||
out[n] = '\0';
|
||||
if (out_size) {
|
||||
*out_size = n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool flash_store_save(const char *name, const char *data, size_t len) {
|
||||
if (!name || !data || len >= FLASH_STORE_MAX - 24) {
|
||||
return false;
|
||||
}
|
||||
store_blob_t blob;
|
||||
memset(&blob, 0, sizeof(blob));
|
||||
blob.magic = STORE_MAGIC;
|
||||
blob.len = (uint32_t)len;
|
||||
snprintf(blob.name, sizeof(blob.name), "%s", name);
|
||||
memcpy(blob.data, data, len);
|
||||
|
||||
uint32_t off = slot_offset(name);
|
||||
uint32_t ints = save_and_disable_interrupts();
|
||||
flash_range_erase(off, FLASH_SECTOR_SIZE);
|
||||
flash_range_program(off, (const uint8_t *)&blob, sizeof(blob));
|
||||
restore_interrupts(ints);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef FLASH_STORE_H
|
||||
#define FLASH_STORE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define FLASH_STORE_MAX 4096
|
||||
|
||||
bool flash_store_load(const char *name, char *out, size_t out_len, size_t *out_size);
|
||||
bool flash_store_save(const char *name, const char *data, size_t len);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
#include "led_core.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
|
||||
#include "pico/stdlib.h"
|
||||
|
||||
#include "cmd_queue.h"
|
||||
#include "leds/presets.hpp"
|
||||
#include "leds/preset.hpp"
|
||||
|
||||
static Preset preset_from_cmd(const cmd_preset_t &src) {
|
||||
Preset p;
|
||||
p.p = src.pattern;
|
||||
p.d = src.d;
|
||||
p.b = src.b;
|
||||
p.n1 = src.n1;
|
||||
p.n2 = src.n2;
|
||||
p.n3 = src.n3;
|
||||
p.n4 = src.n4;
|
||||
p.n5 = src.n5;
|
||||
p.n6 = src.n6;
|
||||
p.n7 = src.n7;
|
||||
p.n8 = src.n8;
|
||||
p.c.clear();
|
||||
uint8_t n = src.c_count;
|
||||
if (n > CMD_COLORS_MAX) {
|
||||
n = CMD_COLORS_MAX;
|
||||
}
|
||||
for (uint8_t i = 0; i < n; i++) {
|
||||
p.c.push_back({src.c[i].r, src.c[i].g, src.c[i].b});
|
||||
}
|
||||
if (p.c.empty()) {
|
||||
p.c.push_back({255, 255, 255});
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
static void apply_cmd(Presets &presets, const led_cmd_t &cmd) {
|
||||
switch (cmd.type) {
|
||||
case CMD_SELECT:
|
||||
presets.select(cmd.name);
|
||||
break;
|
||||
case CMD_EDIT:
|
||||
presets.edit(cmd.name, preset_from_cmd(cmd.u.edit));
|
||||
break;
|
||||
case CMD_DELETE:
|
||||
presets.remove(cmd.name);
|
||||
break;
|
||||
case CMD_SAVE:
|
||||
/* RAM only for now; flash persistence of presets can be added later */
|
||||
printf("led: preset_save acknowledged (%zu presets)\n", presets.presets.size());
|
||||
break;
|
||||
case CMD_BRIGHTNESS:
|
||||
presets.b = (uint8_t)cmd.u.brightness;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" void led_core_entry(void) {
|
||||
Presets presets;
|
||||
presets.select("off");
|
||||
printf("led core1: ready (%zu strips)\n", Presets::kStripCount);
|
||||
|
||||
while (true) {
|
||||
led_cmd_t cmd;
|
||||
while (cmd_queue_pop(&cmd)) {
|
||||
apply_cmd(presets, cmd);
|
||||
}
|
||||
presets.tick();
|
||||
if (presets.current) {
|
||||
presets.show_all_parallel();
|
||||
}
|
||||
sleep_ms(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#ifndef LED_CORE_H
|
||||
#define LED_CORE_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
void led_core_entry(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,38 @@
|
||||
#include <stdio.h>
|
||||
|
||||
#include "pico/stdlib.h"
|
||||
#include "pico/multicore.h"
|
||||
#include "pico/cyw43_arch.h"
|
||||
|
||||
#include "ap.h"
|
||||
#include "web.h"
|
||||
#include "led_core.h"
|
||||
#include "cmd_queue.h"
|
||||
|
||||
int main() {
|
||||
stdio_init_all();
|
||||
sleep_ms(200);
|
||||
|
||||
while (cyw43_arch_init()) {
|
||||
printf("cyw43_arch_init failed; retrying...\n");
|
||||
sleep_ms(1000);
|
||||
}
|
||||
|
||||
printf("led_hoop: Soft-AP + web + LEDs\n");
|
||||
|
||||
cmd_queue_init();
|
||||
multicore_launch_core1(led_core_entry);
|
||||
|
||||
ap_start();
|
||||
web_start();
|
||||
|
||||
unsigned count = 0;
|
||||
while (true) {
|
||||
/* Keep core0 responsive for cyw43 background; light status print */
|
||||
if (count % 20 == 0) {
|
||||
printf("core0 alive count=%u\n", count);
|
||||
}
|
||||
count++;
|
||||
sleep_ms(500);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
#include "mini_json.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static const char *skip_ws(const char *p) {
|
||||
while (*p && isspace((unsigned char)*p)) {
|
||||
p++;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
static const char *find_key(const char *json, const char *key) {
|
||||
char pat[64];
|
||||
snprintf(pat, sizeof(pat), "\"%s\"", key);
|
||||
const char *p = json;
|
||||
while ((p = strstr(p, pat)) != NULL) {
|
||||
const char *after = p + strlen(pat);
|
||||
after = skip_ws(after);
|
||||
if (*after == ':') {
|
||||
return skip_ws(after + 1);
|
||||
}
|
||||
p++;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static bool copy_string_value(const char *p, char *out, size_t out_len) {
|
||||
p = skip_ws(p);
|
||||
if (*p != '"') {
|
||||
return false;
|
||||
}
|
||||
p++;
|
||||
size_t i = 0;
|
||||
while (*p && *p != '"' && i + 1 < out_len) {
|
||||
if (*p == '\\' && p[1]) {
|
||||
p++;
|
||||
}
|
||||
out[i++] = *p++;
|
||||
}
|
||||
out[i] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
bool json_get_string(const char *json, const char *key, char *out, size_t out_len) {
|
||||
const char *p = find_key(json, key);
|
||||
if (!p) {
|
||||
return false;
|
||||
}
|
||||
return copy_string_value(p, out, out_len);
|
||||
}
|
||||
|
||||
bool json_get_object(const char *json, const char *key, char *out, size_t out_len) {
|
||||
const char *p = find_key(json, key);
|
||||
if (!p) {
|
||||
return false;
|
||||
}
|
||||
p = skip_ws(p);
|
||||
if (*p != '{') {
|
||||
return false;
|
||||
}
|
||||
int depth = 0;
|
||||
const char *start = p;
|
||||
do {
|
||||
if (*p == '{') {
|
||||
depth++;
|
||||
} else if (*p == '}') {
|
||||
depth--;
|
||||
} else if (*p == '"') {
|
||||
p++;
|
||||
while (*p && *p != '"') {
|
||||
if (*p == '\\' && p[1]) {
|
||||
p++;
|
||||
}
|
||||
p++;
|
||||
}
|
||||
}
|
||||
if (!*p) {
|
||||
return false;
|
||||
}
|
||||
p++;
|
||||
} while (depth > 0);
|
||||
size_t n = (size_t)(p - start);
|
||||
if (n >= out_len) {
|
||||
n = out_len - 1;
|
||||
}
|
||||
memcpy(out, start, n);
|
||||
out[n] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
bool json_get_bool(const char *json, const char *key, bool *out) {
|
||||
const char *p = find_key(json, key);
|
||||
if (!p || !out) {
|
||||
return false;
|
||||
}
|
||||
p = skip_ws(p);
|
||||
if (strncmp(p, "true", 4) == 0) {
|
||||
*out = true;
|
||||
return true;
|
||||
}
|
||||
if (strncmp(p, "false", 5) == 0) {
|
||||
*out = false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool json_get_int(const char *json, const char *key, int *out) {
|
||||
const char *p = find_key(json, key);
|
||||
if (!p || !out) {
|
||||
return false;
|
||||
}
|
||||
p = skip_ws(p);
|
||||
char *end = NULL;
|
||||
long v = strtol(p, &end, 10);
|
||||
if (end == p) {
|
||||
return false;
|
||||
}
|
||||
*out = (int)v;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool json_get_rgb_array(const char *json, const char *key,
|
||||
uint8_t (*out)[3], size_t max, size_t *count_out) {
|
||||
if (!json || !key || !out || !count_out || max == 0) {
|
||||
return false;
|
||||
}
|
||||
const char *p = find_key(json, key);
|
||||
if (!p) {
|
||||
return false;
|
||||
}
|
||||
p = skip_ws(p);
|
||||
if (*p != '[') {
|
||||
return false;
|
||||
}
|
||||
size_t n = 0;
|
||||
const char *scan = p;
|
||||
while (n < max && (scan = strchr(scan, '[')) != NULL) {
|
||||
if (scan == p) {
|
||||
scan++;
|
||||
continue;
|
||||
}
|
||||
int r = 0, g = 0, b = 0;
|
||||
if (sscanf(scan, "[%d,%d,%d]", &r, &g, &b) == 3) {
|
||||
out[n][0] = (uint8_t)r;
|
||||
out[n][1] = (uint8_t)g;
|
||||
out[n][2] = (uint8_t)b;
|
||||
n++;
|
||||
}
|
||||
scan++;
|
||||
}
|
||||
*count_out = n;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool json_get_select_name(const char *json, char *out, size_t out_len) {
|
||||
const char *p = find_key(json, "select");
|
||||
if (!p) {
|
||||
return false;
|
||||
}
|
||||
p = skip_ws(p);
|
||||
if (*p == '"') {
|
||||
return copy_string_value(p, out, out_len);
|
||||
}
|
||||
if (*p == '[') {
|
||||
/* ["id","name"] — take second string */
|
||||
p++;
|
||||
p = skip_ws(p);
|
||||
if (*p == '"') {
|
||||
char tmp[64];
|
||||
if (!copy_string_value(p, tmp, sizeof(tmp))) {
|
||||
return false;
|
||||
}
|
||||
p = strchr(p + 1, '"');
|
||||
if (!p) {
|
||||
return false;
|
||||
}
|
||||
p++;
|
||||
p = skip_ws(p);
|
||||
if (*p == ',') {
|
||||
p = skip_ws(p + 1);
|
||||
}
|
||||
return copy_string_value(p, out, out_len);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef MINI_JSON_H
|
||||
#define MINI_JSON_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Extract JSON string value for key into out (unescaped simple strings). */
|
||||
bool json_get_string(const char *json, const char *key, char *out, size_t out_len);
|
||||
|
||||
/* Extract nested object text for key into out (raw substring including braces). */
|
||||
bool json_get_object(const char *json, const char *key, char *out, size_t out_len);
|
||||
|
||||
bool json_get_bool(const char *json, const char *key, bool *out);
|
||||
bool json_get_int(const char *json, const char *key, int *out);
|
||||
|
||||
/* Parse "key":[[r,g,b],...] into out[i][0..2]. Returns false if key missing. */
|
||||
bool json_get_rgb_array(const char *json, const char *key,
|
||||
uint8_t (*out)[3], size_t max, size_t *count_out);
|
||||
|
||||
/* If select is a string, copy it; if ["id","name"], copy name. */
|
||||
bool json_get_select_name(const char *json, char *out, size_t out_len);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,201 @@
|
||||
#include "patterns/patterns.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include "pico/stdlib.h"
|
||||
#include "leds/presets.hpp"
|
||||
|
||||
namespace {
|
||||
uint32_t now() { return to_ms_since_boot(get_absolute_time()); }
|
||||
bool due(uint32_t& last, uint32_t ms) {
|
||||
const uint32_t current = now();
|
||||
if (current - last < ms) return false;
|
||||
last = current; return true;
|
||||
}
|
||||
RGB black() { return {0, 0, 0}; }
|
||||
RGB lerp(RGB a, RGB b, float t) {
|
||||
return {static_cast<uint8_t>(a.r + (b.r - a.r) * t), static_cast<uint8_t>(a.g + (b.g - a.g) * t),
|
||||
static_cast<uint8_t>(a.b + (b.b - a.b) * t)};
|
||||
}
|
||||
RGB hue(int hue) {
|
||||
hue = ((hue % 360) + 360) % 360;
|
||||
const float x = 1.0f - std::abs(std::fmod(hue / 60.0f, 2.0f) - 1.0f);
|
||||
if (hue < 60) return {255, static_cast<uint8_t>(x * 255), 0};
|
||||
if (hue < 120) return {static_cast<uint8_t>(x * 255), 255, 0};
|
||||
if (hue < 180) return {0, 255, static_cast<uint8_t>(x * 255)};
|
||||
if (hue < 240) return {0, static_cast<uint8_t>(x * 255), 255};
|
||||
if (hue < 300) return {static_cast<uint8_t>(x * 255), 0, 255};
|
||||
return {255, 0, static_cast<uint8_t>(x * 255)};
|
||||
}
|
||||
RGB color(const Preset* p, size_t index, RGB fallback = {255, 255, 255}) {
|
||||
return p->c.empty() ? fallback : p->c[index % p->c.size()];
|
||||
}
|
||||
void begin(Presets*& dest, Preset*& preset_dest, uint32_t& started, uint32_t& last,
|
||||
Presets& ps, Preset* p) {
|
||||
dest = &ps; preset_dest = p; started = last = now();
|
||||
}
|
||||
void static_done(Presets*& ps, Preset*& p, uint32_t& started, uint32_t& last,
|
||||
Presets& x, Preset* y) { begin(ps, p, started, last, x, y); }
|
||||
}
|
||||
|
||||
#define START(CLASS) void CLASS::start(Presets& ps, Preset* p) { begin(ps_, p_, started_, last_, ps, p); step_ = head_ = tail_ = phase_ = 0; drawn_ = false; }
|
||||
|
||||
START(Blink)
|
||||
bool Blink::tick() {
|
||||
if (!due(last_, std::max(1, p_->d))) return true;
|
||||
if (phase_++ % 2 == 0) ps_->fill(ps_->apply_brightness(color(p_, step_++), p_->b));
|
||||
else ps_->fill(black());
|
||||
ps_->show_all_parallel(); return true;
|
||||
}
|
||||
|
||||
START(Rainbow)
|
||||
bool Rainbow::tick() {
|
||||
if (!due(last_, p_->a ? std::max(1, p_->d) : 0)) return true;
|
||||
const int advance = std::max(1, p_->n1);
|
||||
for (size_t s = 0; s < Presets::kStripCount; ++s)
|
||||
for (uint16_t i = 0; i < ps_->strips[s]->num_leds; ++i)
|
||||
ps_->strips[s]->set(i, ps_->apply_brightness(hue((i * 720 / ps_->strips[s]->num_leds) + step_), p_->b));
|
||||
ps_->show_all_parallel(); step_ += advance; ps_->step = step_ * 256 / 873;
|
||||
return p_->a;
|
||||
}
|
||||
|
||||
START(Pulse)
|
||||
bool Pulse::tick() {
|
||||
const int attack = std::max(0, p_->n1), hold = std::max(0, p_->n2), decay = std::max(0, p_->n3);
|
||||
const int total = std::max(1, attack + hold + decay + std::max(0, p_->d));
|
||||
const uint32_t elapsed = now() - started_;
|
||||
float factor = 0;
|
||||
if (elapsed < static_cast<uint32_t>(attack) && attack) factor = float(elapsed) / attack;
|
||||
else if (elapsed < static_cast<uint32_t>(attack + hold)) factor = 1;
|
||||
else if (elapsed < static_cast<uint32_t>(attack + hold + decay) && decay)
|
||||
factor = 1.0f - float(elapsed - attack - hold) / decay;
|
||||
ps_->fill(ps_->apply_brightness(lerp(black(), color(p_, step_), factor), p_->b));
|
||||
ps_->show_all_parallel();
|
||||
if (elapsed >= static_cast<uint32_t>(total)) { started_ = now(); ++step_; return p_->a; }
|
||||
return true;
|
||||
}
|
||||
|
||||
START(Transition)
|
||||
bool Transition::tick() {
|
||||
if (p_->c.empty()) { ps_->off(); return false; }
|
||||
if (p_->c.size() == 1) { ps_->fill(ps_->apply_brightness(p_->c[0], p_->b)); ps_->show_all_parallel(); return true; }
|
||||
const int duration = std::max(10, p_->d); const uint32_t elapsed = now() - started_;
|
||||
if (elapsed >= static_cast<uint32_t>(duration)) {
|
||||
ps_->fill(ps_->apply_brightness(color(p_, step_ + 1), p_->b)); ps_->show_all_parallel();
|
||||
if (!p_->a) return false; ++step_; started_ = now(); return true;
|
||||
}
|
||||
ps_->fill(ps_->apply_brightness(lerp(color(p_, step_), color(p_, step_ + 1), float(elapsed) / duration), p_->b));
|
||||
ps_->show_all_parallel(); return true;
|
||||
}
|
||||
|
||||
START(Chase)
|
||||
bool Chase::tick() {
|
||||
if (drawn_ && (!p_->a || !due(last_, std::max(10, p_->d)))) return p_->a;
|
||||
const int n1 = std::max(1, p_->n1), n2 = std::max(1, p_->n2), len = n1 + n2;
|
||||
const int position = (step_ % 2 == 0 ? (step_ / 2) * (p_->n3 + p_->n4) + p_->n3
|
||||
: ((step_ + 1) / 2) * (p_->n3 + p_->n4));
|
||||
for (int i = 0; i < 291; ++i) ps_->fill_n(ps_->apply_brightness(((i - position + len * 100) % len) < n1 ? color(p_, 0) : color(p_, 1), p_->b), i, i + 1);
|
||||
ps_->show_all_parallel(); ps_->step = ++step_; drawn_ = true; return p_->a;
|
||||
}
|
||||
|
||||
START(Circle)
|
||||
bool Circle::tick() {
|
||||
const int head_delay = 1000 / std::max(1, p_->n1), tail_delay = 1000 / std::max(1, p_->n3);
|
||||
const int max_len = std::max(1, p_->n2), min_len = std::max(0, p_->n4);
|
||||
if (due(last_, head_delay)) ++head_;
|
||||
if (phase_ == 1 && due(started_, tail_delay)) ++tail_;
|
||||
const int length = std::max(0, head_ - tail_);
|
||||
if (phase_ == 0 && length >= max_len) phase_ = 1;
|
||||
if (phase_ == 1 && length <= min_len) phase_ = min_len ? 0 : 2;
|
||||
if (phase_ == 2) { phase_ = 0; tail_ = head_; }
|
||||
ps_->fill(phase_ == 2 ? ps_->apply_brightness(color(p_, 1, black()), p_->b) : black());
|
||||
for (int i = 0; i <= length; ++i) ps_->fill_n(ps_->apply_brightness(color(p_, 0), p_->b), tail_ + i, tail_ + i + 1);
|
||||
ps_->show_all_parallel(); return true;
|
||||
}
|
||||
|
||||
START(Roll)
|
||||
bool Roll::tick() {
|
||||
if (drawn_ && (!p_->a || !due(last_, std::max(1, p_->d)))) return p_->a;
|
||||
const int head = (p_->n4 == 0 ? step_ : 7 - step_) & 7; ps_->last_roll_head = head;
|
||||
const RGB c1 = ps_->apply_brightness(color(p_, 0), p_->b), c2 = ps_->apply_brightness(color(p_, 1, black()), p_->b);
|
||||
for (int s = 0; s < 8; ++s) {
|
||||
const int dist = p_->n4 == 0 ? (head - s + 8) % 8 : (s - head + 8) % 8;
|
||||
const RGB c = lerp(c1, c2, dist / 7.0f); auto& strip = *ps_->strips[s];
|
||||
const int begin_at = std::max(0, p_->n1), end_at = std::max(begin_at, int(strip.num_leds) - std::max(0, p_->n2));
|
||||
for (uint16_t i = 0; i < strip.num_leds; ++i) strip.set(i, i >= begin_at && i < end_at ? c : black());
|
||||
}
|
||||
ps_->show_all_parallel(); ++step_; ps_->step = step_; drawn_ = true;
|
||||
return !(p_->n3 > 0 && step_ >= p_->n3 * 8);
|
||||
}
|
||||
|
||||
START(Calibration)
|
||||
bool Calibration::tick() {
|
||||
if (drawn_) return true;
|
||||
for (int s = 0; s < 8; ++s) for (uint16_t i = 0; i < ps_->strips[s]->num_leds; ++i)
|
||||
ps_->strips[s]->set(i, (s == 2 || s == 6) ? (i < 10 ? RGB{0,25,0} : (((i-10)/10)%2 ? RGB{25,0,0} : RGB{0,0,25})) : black());
|
||||
ps_->show_all_parallel(); drawn_ = true; return true;
|
||||
}
|
||||
START(Test)
|
||||
bool Test::tick() {
|
||||
if (drawn_) return true;
|
||||
ps_->fill(black()); for (int s = 0; s < 8; ++s) { for (int i=0;i<=s;++i) ps_->strips[s]->set(i,{127,0,0}); ps_->strips[s]->set(ps_->strip_midpoints[s],{127,0,0}); }
|
||||
ps_->show_all_parallel(); drawn_=true; return true;
|
||||
}
|
||||
START(Grab)
|
||||
bool Grab::tick() {
|
||||
if (drawn_) return true; ps_->fill(black());
|
||||
for (int s=0;s<8;++s) for (int i=std::max(0,int(ps_->strip_midpoints[s])-10); i<=int(ps_->strip_midpoints[s])+10; ++i) ps_->strips[s]->set(i,color(p_,0,{180,0,255}));
|
||||
ps_->show_all_parallel(); drawn_=true; return true;
|
||||
}
|
||||
|
||||
START(Spin)
|
||||
bool Spin::tick() {
|
||||
if (!due(last_, std::max(1,p_->d))) return true;
|
||||
const int rate=std::max(1,p_->n1), margin=std::max(0,p_->n2);
|
||||
for (int s : {0,4}) { auto& strip=*ps_->strips[s]; int mid=ps_->strip_midpoints[s], expand=step_*(s==0?std::max(1,rate/2):rate);
|
||||
int left=std::max(margin,mid-10-expand), right=std::min(int(strip.num_leds)-margin,mid+11+expand);
|
||||
for(int i=left;i<mid-10;++i) strip.set(i,lerp(color(p_,1),color(p_,0),float(i-left)/std::max(1,mid-10-left-1)));
|
||||
for(int i=mid+11;i<right;++i) strip.set(i,lerp(color(p_,0),color(p_,1),float(i-mid-11)/std::max(1,right-mid-12))); }
|
||||
ps_->show_all_parallel(); ++step_; return true;
|
||||
}
|
||||
START(Lift)
|
||||
bool Lift::tick() {
|
||||
if (!due(last_,std::max(1,p_->d))) return true;
|
||||
const int rate=std::max(1,p_->n1), margin=std::max(0,p_->n2); bool done=true;
|
||||
for(int s : {0,4}) { auto& strip=*ps_->strips[s]; int mid=ps_->strip_midpoints[s], shrink=step_*(s==0?std::max(1,rate/2):rate);
|
||||
int left=std::min(mid-10,margin+shrink), right=std::max(mid+11,int(strip.num_leds)-margin-shrink);
|
||||
for(int i=margin;i<mid-10;++i) strip.set(i,black()); for(int i=mid+11;i<int(strip.num_leds)-margin;++i) strip.set(i,black());
|
||||
for(int i=left;i<mid-10;++i) strip.set(i,lerp(color(p_,1),color(p_,0),float(i-left)/std::max(1,mid-10-left-1)));
|
||||
for(int i=mid+11;i<right;++i) strip.set(i,lerp(color(p_,0),color(p_,1),float(i-mid-11)/std::max(1,right-mid-12)));
|
||||
done &= left==mid-10 && right==mid+11; }
|
||||
ps_->show_all_parallel(); ++step_; return true; // Lift holds its final image.
|
||||
}
|
||||
START(Flare)
|
||||
bool Flare::tick() {
|
||||
const int fade=std::max(1,p_->d); const float f=std::min(1.0f,float(now()-started_)/fade); auto& strip=*ps_->strips[std::clamp(ps_->last_roll_head,0,7)];
|
||||
const int count=std::clamp(p_->n1,0,int(strip.num_leds)); for(uint16_t i=0;i<strip.num_leds;++i) strip.set(i,ps_->apply_brightness(lerp(black(),color(p_,i<count?0:1,black()),f),p_->b));
|
||||
strip.show(); return true;
|
||||
}
|
||||
START(Hook)
|
||||
bool Hook::tick() {
|
||||
if(drawn_) return true; ps_->fill(black()); const int a=std::max(0,p_->n1),b=std::min(7,std::max(a,p_->n2)),span=std::max(0,p_->n3);
|
||||
for(int s=a;s<=b;++s) { int center=ps_->strip_midpoints[s]+p_->n4; for(int i=std::max(0,center-span);i<=std::min(int(ps_->strips[s]->num_leds)-1,center+span);++i) ps_->strips[s]->set(i,color(p_,0,black())); }
|
||||
ps_->show_all_parallel(); drawn_=true; return true;
|
||||
}
|
||||
START(Pose)
|
||||
bool Pose::tick() {
|
||||
if(drawn_) return true; const int ranges[8]={p_->n1,p_->n2,p_->n3,p_->n4,p_->n5,p_->n6,p_->n7,p_->n8};
|
||||
for(auto& sp:ps_->strips) for(uint16_t i=0;i<sp->num_leds;++i) { RGB out=black(); for(int n=0;n<4;++n) {int a=std::min(ranges[n*2],ranges[n*2+1]),b=std::max(ranges[n*2],ranges[n*2+1]);if(i>=a&&i<=b)out=ps_->apply_brightness(color(p_,n,black()),p_->b);} sp->set(i,out); }
|
||||
ps_->show_all_parallel();drawn_=true;return true;
|
||||
}
|
||||
START(Point)
|
||||
bool Point::tick() {
|
||||
if(drawn_) return false; ps_->fill(black()); const int r[8]={p_->n1,p_->n2,p_->n3,p_->n4,p_->n5,p_->n6,p_->n7,p_->n8};
|
||||
for(int n=0;n<4;++n) ps_->fill_n(ps_->apply_brightness(color(p_,n,black()),p_->b),r[n*2],r[n*2+1]);
|
||||
ps_->show_all_parallel();drawn_=true;return false;
|
||||
}
|
||||
START(ScaleTest)
|
||||
bool ScaleTest::tick() {
|
||||
if(!due(last_,std::max(1,p_->d)))return true;ps_->fill(black());for(size_t s=0;s<8;++s)ps_->set(s,step_%291,ps_->apply_brightness({255,0,0},p_->b));ps_->show_all_parallel();ps_->step=++step_;return true;
|
||||
}
|
||||
#undef START
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
class Presets;
|
||||
class Preset;
|
||||
|
||||
class Pattern {
|
||||
public:
|
||||
virtual ~Pattern() = default;
|
||||
virtual void start(Presets& presets, Preset* preset) = 0;
|
||||
virtual bool tick() = 0;
|
||||
};
|
||||
|
||||
#define DECLARE_PATTERN(name) class name final : public Pattern { public: void start(Presets&, Preset*) override; bool tick() override; private: Presets* ps_ = nullptr; Preset* p_ = nullptr; uint32_t started_ = 0, last_ = 0; int step_ = 0, head_ = 0, tail_ = 0, phase_ = 0; bool drawn_ = false; };
|
||||
DECLARE_PATTERN(Blink)
|
||||
DECLARE_PATTERN(Rainbow)
|
||||
DECLARE_PATTERN(Pulse)
|
||||
DECLARE_PATTERN(Transition)
|
||||
DECLARE_PATTERN(Chase)
|
||||
DECLARE_PATTERN(Circle)
|
||||
DECLARE_PATTERN(Roll)
|
||||
DECLARE_PATTERN(Calibration)
|
||||
DECLARE_PATTERN(Test)
|
||||
DECLARE_PATTERN(Grab)
|
||||
DECLARE_PATTERN(Spin)
|
||||
DECLARE_PATTERN(Lift)
|
||||
DECLARE_PATTERN(Flare)
|
||||
DECLARE_PATTERN(Hook)
|
||||
DECLARE_PATTERN(Pose)
|
||||
DECLARE_PATTERN(Point)
|
||||
DECLARE_PATTERN(ScaleTest)
|
||||
#undef DECLARE_PATTERN
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "httpserver.h"
|
||||
#include "web.h"
|
||||
#include "web_index_html.h"
|
||||
#include "web_main_js.h"
|
||||
#include "web_styles_css.h"
|
||||
#include "flash_store.h"
|
||||
#include "mini_json.h"
|
||||
#include "cmd_queue.h"
|
||||
|
||||
#define WS_MSG_MAX 2048
|
||||
#define JSON_OBJ_MAX 1024
|
||||
|
||||
static httpserver_t *g_http;
|
||||
static char g_buttons_json[FLASH_STORE_MAX];
|
||||
|
||||
static void buttons_load(void) {
|
||||
size_t n = 0;
|
||||
if (!flash_store_load("buttons", g_buttons_json, sizeof(g_buttons_json), &n)) {
|
||||
snprintf(g_buttons_json, sizeof(g_buttons_json), "{\"buttons\":[]}");
|
||||
}
|
||||
}
|
||||
|
||||
static void on_index(httpserver_conn_t *conn, const char *path, const char *query) {
|
||||
(void)path;
|
||||
(void)query;
|
||||
httpserver_send_static(conn, 200, "text/html; charset=utf-8",
|
||||
web_index_html, web_index_html_len, "gzip");
|
||||
}
|
||||
|
||||
static void on_main_js(httpserver_conn_t *conn, const char *path, const char *query) {
|
||||
(void)path;
|
||||
(void)query;
|
||||
httpserver_send_static(conn, 200, "application/javascript; charset=utf-8",
|
||||
web_main_js, web_main_js_len, "gzip");
|
||||
}
|
||||
|
||||
static void on_styles_css(httpserver_conn_t *conn, const char *path, const char *query) {
|
||||
(void)path;
|
||||
(void)query;
|
||||
httpserver_send_static(conn, 200, "text/css; charset=utf-8",
|
||||
web_styles_css, web_styles_css_len, "gzip");
|
||||
}
|
||||
|
||||
static void on_get_buttons(httpserver_conn_t *conn, const char *path, const char *query) {
|
||||
(void)path;
|
||||
(void)query;
|
||||
httpserver_send(conn, 200, "application/json", g_buttons_json, strlen(g_buttons_json));
|
||||
}
|
||||
|
||||
static void on_post_buttons(httpserver_conn_t *conn, const char *path, const char *query) {
|
||||
(void)path;
|
||||
(void)query;
|
||||
size_t len = 0;
|
||||
const char *body = httpserver_request_body(conn, &len);
|
||||
if (!body || len == 0 || len >= sizeof(g_buttons_json)) {
|
||||
httpserver_send(conn, 500, "application/json", "{\"ok\":false}", 12);
|
||||
return;
|
||||
}
|
||||
memcpy(g_buttons_json, body, len);
|
||||
g_buttons_json[len] = '\0';
|
||||
if (!flash_store_save("buttons", g_buttons_json, len)) {
|
||||
httpserver_send(conn, 500, "application/json", "{\"ok\":false,\"error\":\"save failed\"}", 34);
|
||||
return;
|
||||
}
|
||||
httpserver_send(conn, 200, "application/json", "{\"ok\":true}", 11);
|
||||
}
|
||||
|
||||
static void on_ws_open(httpserver_conn_t *ws) {
|
||||
(void)ws;
|
||||
printf("ws: open\n");
|
||||
}
|
||||
|
||||
static void push_select(const char *name) {
|
||||
led_cmd_t cmd;
|
||||
memset(&cmd, 0, sizeof(cmd));
|
||||
cmd.type = CMD_SELECT;
|
||||
snprintf(cmd.name, sizeof(cmd.name), "%s", name);
|
||||
cmd_queue_push(&cmd);
|
||||
}
|
||||
|
||||
static void parse_preset_fields(const char *json, cmd_preset_t *p) {
|
||||
memset(p, 0, sizeof(*p));
|
||||
p->d = 100;
|
||||
p->b = 127;
|
||||
snprintf(p->pattern, sizeof(p->pattern), "off");
|
||||
|
||||
char s[CMD_PATTERN_MAX];
|
||||
if (json_get_string(json, "p", s, sizeof(s))) {
|
||||
snprintf(p->pattern, sizeof(p->pattern), "%s", s);
|
||||
}
|
||||
json_get_int(json, "d", &p->d);
|
||||
json_get_int(json, "b", &p->b);
|
||||
json_get_int(json, "n1", &p->n1);
|
||||
json_get_int(json, "n2", &p->n2);
|
||||
json_get_int(json, "n3", &p->n3);
|
||||
json_get_int(json, "n4", &p->n4);
|
||||
json_get_int(json, "n5", &p->n5);
|
||||
json_get_int(json, "n6", &p->n6);
|
||||
json_get_int(json, "n7", &p->n7);
|
||||
json_get_int(json, "n8", &p->n8);
|
||||
|
||||
uint8_t colors[CMD_COLORS_MAX][3];
|
||||
size_t n = 0;
|
||||
if (json_get_rgb_array(json, "c", colors, CMD_COLORS_MAX, &n) && n > 0) {
|
||||
p->c_count = (uint8_t)n;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
p->c[i].r = colors[i][0];
|
||||
p->c[i].g = colors[i][1];
|
||||
p->c[i].b = colors[i][2];
|
||||
}
|
||||
} else {
|
||||
p->c_count = 1;
|
||||
p->c[0].r = 255;
|
||||
p->c[0].g = 255;
|
||||
p->c[0].b = 255;
|
||||
}
|
||||
}
|
||||
|
||||
static void on_ws_msg(httpserver_conn_t *ws, const uint8_t *data, size_t len, bool text) {
|
||||
(void)text;
|
||||
char msg[WS_MSG_MAX + 1];
|
||||
if (len >= sizeof(msg)) {
|
||||
len = sizeof(msg) - 1;
|
||||
}
|
||||
memcpy(msg, data, len);
|
||||
msg[len] = '\0';
|
||||
printf("ws: %s\n", msg);
|
||||
|
||||
char name[CMD_NAME_MAX];
|
||||
if (json_get_select_name(msg, name, sizeof(name))) {
|
||||
push_select(name);
|
||||
char out[96];
|
||||
int n = snprintf(out, sizeof(out), "{\"select\":\"%s\"}", name);
|
||||
if (g_http) {
|
||||
httpserver_ws_broadcast(g_http, out, (size_t)n, true);
|
||||
} else {
|
||||
httpserver_ws_send(ws, out, (size_t)n, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
char obj[JSON_OBJ_MAX];
|
||||
if (json_get_object(msg, "preset_edit", obj, sizeof(obj))) {
|
||||
led_cmd_t cmd;
|
||||
memset(&cmd, 0, sizeof(cmd));
|
||||
cmd.type = CMD_EDIT;
|
||||
if (!json_get_string(obj, "name", cmd.name, sizeof(cmd.name))) {
|
||||
return;
|
||||
}
|
||||
char data[JSON_OBJ_MAX];
|
||||
if (json_get_object(obj, "data", data, sizeof(data))) {
|
||||
parse_preset_fields(data, &cmd.u.edit);
|
||||
} else {
|
||||
parse_preset_fields(obj, &cmd.u.edit);
|
||||
}
|
||||
cmd_queue_push(&cmd);
|
||||
return;
|
||||
}
|
||||
|
||||
if (json_get_string(msg, "preset_delete", name, sizeof(name))) {
|
||||
led_cmd_t cmd;
|
||||
memset(&cmd, 0, sizeof(cmd));
|
||||
cmd.type = CMD_DELETE;
|
||||
snprintf(cmd.name, sizeof(cmd.name), "%s", name);
|
||||
cmd_queue_push(&cmd);
|
||||
return;
|
||||
}
|
||||
|
||||
bool save = false;
|
||||
if (json_get_bool(msg, "preset_save", &save) && save) {
|
||||
led_cmd_t cmd;
|
||||
memset(&cmd, 0, sizeof(cmd));
|
||||
cmd.type = CMD_SAVE;
|
||||
cmd_queue_push(&cmd);
|
||||
return;
|
||||
}
|
||||
|
||||
int b = 0;
|
||||
if (json_get_int(msg, "b", &b)) {
|
||||
led_cmd_t cmd;
|
||||
memset(&cmd, 0, sizeof(cmd));
|
||||
cmd.type = CMD_BRIGHTNESS;
|
||||
cmd.u.brightness = b;
|
||||
cmd_queue_push(&cmd);
|
||||
}
|
||||
}
|
||||
|
||||
static void on_ws_close(httpserver_conn_t *ws) {
|
||||
(void)ws;
|
||||
printf("ws: close\n");
|
||||
}
|
||||
|
||||
bool web_start(void) {
|
||||
buttons_load();
|
||||
g_http = httpserver_create();
|
||||
httpserver_route(g_http, "GET", "/", on_index);
|
||||
httpserver_route(g_http, "GET", "/static/main.js", on_main_js);
|
||||
httpserver_route(g_http, "GET", "/static/styles.css", on_styles_css);
|
||||
httpserver_route(g_http, "GET", "/api/buttons", on_get_buttons);
|
||||
httpserver_route(g_http, "POST", "/api/buttons", on_post_buttons);
|
||||
httpserver_websocket(g_http, "/ws", on_ws_open, on_ws_msg, on_ws_close);
|
||||
return httpserver_listen(g_http, 80);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#ifndef WEB_H
|
||||
#define WEB_H
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
bool web_start(void);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,140 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Led Hoop</title>
|
||||
<link rel="stylesheet" href="static/styles.css" />
|
||||
</head>
|
||||
<body data-device-id="1">
|
||||
<div class="header">
|
||||
<button class="menu-btn" type="button" onclick="toggleMenu()" aria-label="Menu">☰ Menu</button>
|
||||
<div class="menu" id="menu">
|
||||
<button class="menu-item off" type="button" onclick="sendSelect('off', null); closeMenu();">Off</button>
|
||||
<button class="menu-item" type="button" onclick="sendSelect('test', null); closeMenu();">Test</button>
|
||||
<button class="menu-item" type="button" onclick="sendSelect('calibration', null); closeMenu();">Calibration</button>
|
||||
<button class="menu-item" type="button" onclick="closeMenu(); openNewButtonEditor();">Add button</button>
|
||||
<button class="menu-item" type="button" onclick="closeMenu(); saveCurrentButtons();">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="buttons" id="buttonsContainer">
|
||||
</div>
|
||||
|
||||
<div class="preset-editor" id="buttonEditor">
|
||||
<div class="preset-editor-inner">
|
||||
<h2 class="preset-editor-title" id="buttonEditorTitle">Button</h2>
|
||||
<label class="preset-editor-field">
|
||||
<span>Button label</span>
|
||||
<input id="be-label" type="text" placeholder="e.g. grab" />
|
||||
</label>
|
||||
<label class="preset-editor-field">
|
||||
<span>Preset name</span>
|
||||
<input id="be-preset" type="text" placeholder="e.g. grab" />
|
||||
</label>
|
||||
<label class="preset-editor-field">
|
||||
<span>Pattern (p)</span>
|
||||
<select id="be-pattern">
|
||||
<option value="spin">spin</option>
|
||||
<option value="roll">roll</option>
|
||||
<option value="grab">grab</option>
|
||||
<option value="lift">lift</option>
|
||||
<option value="flare">flare</option>
|
||||
<option value="hook">hook</option>
|
||||
<option value="invertsplit">invertsplit</option>
|
||||
<option value="pose">pose</option>
|
||||
<option value="backbalance">backbalance</option>
|
||||
<option value="beat">beat</option>
|
||||
<option value="crouch">crouch</option>
|
||||
<option value="backbendsplit">backbendsplit</option>
|
||||
<option value="straddle">straddle</option>
|
||||
<option value="frontbalance">frontbalance</option>
|
||||
<option value="elbowhang">elbowhang</option>
|
||||
<option value="elbowhangspin">elbowhangspin</option>
|
||||
<option value="dismount">dismount</option>
|
||||
<option value="fluff">fluff</option>
|
||||
<option value="elbowhangsplit">elbowhangsplit</option>
|
||||
<option value="invert">invert</option>
|
||||
<option value="backbend">backbend</option>
|
||||
<option value="seat">seat</option>
|
||||
<option value="kneehang">kneehang</option>
|
||||
<option value="legswoop">legswoop</option>
|
||||
<option value="split">split</option>
|
||||
<option value="foothang">foothang</option>
|
||||
<option value="point">point</option>
|
||||
<option value="off">off</option>
|
||||
<option value="on">on</option>
|
||||
<option value="blink">blink</option>
|
||||
<option value="rainbow">rainbow</option>
|
||||
<option value="pulse">pulse</option>
|
||||
<option value="transition">transition</option>
|
||||
<option value="chase">chase</option>
|
||||
<option value="circle">circle</option>
|
||||
<option value="calibration">calibration</option>
|
||||
<option value="test">test</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="preset-editor-row">
|
||||
<label class="preset-editor-field">
|
||||
<span>Delay (d)</span>
|
||||
<input id="be-delay" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
<label class="preset-editor-field">
|
||||
<span>Brightness (b)</span>
|
||||
<input id="be-brightness" type="number" inputmode="numeric" min="0" max="255" />
|
||||
</label>
|
||||
</div>
|
||||
<label class="preset-editor-field">
|
||||
<span>Colors (c)</span>
|
||||
<input id="be-colors" type="text" placeholder="r,g,b; r,g,b (0–255)" />
|
||||
</label>
|
||||
<div class="preset-editor-row">
|
||||
<label class="preset-editor-field small">
|
||||
<span>n1</span>
|
||||
<input id="be-n1" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
<label class="preset-editor-field small">
|
||||
<span>n2</span>
|
||||
<input id="be-n2" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="preset-editor-row">
|
||||
<label class="preset-editor-field small">
|
||||
<span>n3</span>
|
||||
<input id="be-n3" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
<label class="preset-editor-field small">
|
||||
<span>n4</span>
|
||||
<input id="be-n4" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="preset-editor-row">
|
||||
<label class="preset-editor-field small">
|
||||
<span>n5</span>
|
||||
<input id="be-n5" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
<label class="preset-editor-field small">
|
||||
<span>n6</span>
|
||||
<input id="be-n6" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="preset-editor-row">
|
||||
<label class="preset-editor-field small">
|
||||
<span>n7</span>
|
||||
<input id="be-n7" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
<label class="preset-editor-field small">
|
||||
<span>n8</span>
|
||||
<input id="be-n8" type="number" inputmode="numeric" />
|
||||
</label>
|
||||
</div>
|
||||
<div class="preset-editor-actions">
|
||||
<button type="button" class="preset-editor-btn primary" onclick="saveButtonFromEditor()">Save</button>
|
||||
<button type="button" class="preset-editor-btn" onclick="closeButtonEditor()">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button class="next-btn" type="button" onclick="nextPreset()">Next</button>
|
||||
<script src="static/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,617 @@
|
||||
var deviceId = document.body.getAttribute('data-device-id') || '1';
|
||||
var ws = null;
|
||||
var currentEditIndex = -1; // -1 means "new button"
|
||||
|
||||
function getButtonsFromDom() {
|
||||
var btns = document.querySelectorAll('#buttonsContainer .btn');
|
||||
return Array.prototype.map.call(btns, function (el) {
|
||||
var obj = {
|
||||
id: el.getAttribute('data-id') || el.textContent.trim(),
|
||||
preset: el.getAttribute('data-preset') || ''
|
||||
};
|
||||
var p = el.getAttribute('data-p');
|
||||
if (p) obj.p = p;
|
||||
var d = el.getAttribute('data-d');
|
||||
if (d !== null && d !== '') obj.d = parseInt(d, 10) || 0;
|
||||
var b = el.getAttribute('data-b');
|
||||
if (b !== null && b !== '') obj.b = parseInt(b, 10) || 0;
|
||||
var c = el.getAttribute('data-c');
|
||||
if (c) {
|
||||
try {
|
||||
var parsed = JSON.parse(c);
|
||||
if (Array.isArray(parsed)) obj.c = parsed;
|
||||
} catch (e) {}
|
||||
}
|
||||
for (var i = 1; i <= 8; i++) {
|
||||
var key = 'n' + i;
|
||||
var v = el.getAttribute('data-' + key);
|
||||
if (v !== null && v !== '') {
|
||||
obj[key] = parseInt(v, 10) || 0;
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
});
|
||||
}
|
||||
|
||||
function renderButtons(buttons) {
|
||||
var container = document.getElementById('buttonsContainer');
|
||||
container.innerHTML = '';
|
||||
buttons.forEach(function (btn, idx) {
|
||||
var el = document.createElement('button');
|
||||
el.className = 'btn';
|
||||
el.type = 'button';
|
||||
el.setAttribute('data-preset', btn.preset);
|
||||
el.setAttribute('data-id', btn.id);
|
||||
el.setAttribute('data-index', String(idx));
|
||||
// Optional preset config stored per button
|
||||
if (btn.p !== undefined) el.setAttribute('data-p', btn.p);
|
||||
if (btn.d !== undefined) el.setAttribute('data-d', String(btn.d));
|
||||
if (btn.b !== undefined) el.setAttribute('data-b', String(btn.b));
|
||||
if (btn.c !== undefined) {
|
||||
try {
|
||||
el.setAttribute('data-c', JSON.stringify(btn.c));
|
||||
} catch (e) {}
|
||||
}
|
||||
for (var i = 1; i <= 8; i++) {
|
||||
var key = 'n' + i;
|
||||
if (btn[key] !== undefined) {
|
||||
el.setAttribute('data-' + key, String(btn[key]));
|
||||
}
|
||||
}
|
||||
el.draggable = true;
|
||||
el.textContent = btn.id;
|
||||
container.appendChild(el);
|
||||
});
|
||||
attachButtonListeners();
|
||||
}
|
||||
|
||||
function attachButtonListeners() {
|
||||
var container = document.getElementById('buttonsContainer');
|
||||
if (!container) return;
|
||||
var btns = container.querySelectorAll('.btn');
|
||||
for (var i = 0; i < btns.length; i++) {
|
||||
var el = btns[i];
|
||||
el.setAttribute('data-index', String(i));
|
||||
el.onclick = function(ev) {
|
||||
if (longPressTriggered) {
|
||||
ev.preventDefault();
|
||||
return;
|
||||
}
|
||||
var btn = ev.currentTarget;
|
||||
sendSelect(btn.getAttribute('data-preset'), btn);
|
||||
};
|
||||
el.oncontextmenu = function(ev) {
|
||||
ev.preventDefault();
|
||||
showButtonContextMenu(ev, ev.currentTarget);
|
||||
};
|
||||
(function(buttonEl) {
|
||||
var startX, startY;
|
||||
el.ontouchstart = function(ev) {
|
||||
if (ev.touches.length !== 1) return;
|
||||
longPressTriggered = false;
|
||||
startX = ev.touches[0].clientX;
|
||||
startY = ev.touches[0].clientY;
|
||||
longPressTimer = setTimeout(function() {
|
||||
longPressTimer = null;
|
||||
longPressTriggered = true;
|
||||
showButtonContextMenu({ clientX: startX, clientY: startY }, buttonEl);
|
||||
}, 500);
|
||||
};
|
||||
el.ontouchmove = function(ev) {
|
||||
if (longPressTimer && ev.touches.length === 1) {
|
||||
var dx = ev.touches[0].clientX - startX;
|
||||
var dy = ev.touches[0].clientY - startY;
|
||||
if (dx * dx + dy * dy > 100) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
el.ontouchend = el.ontouchcancel = function() {
|
||||
if (longPressTimer) {
|
||||
clearTimeout(longPressTimer);
|
||||
longPressTimer = null;
|
||||
}
|
||||
setTimeout(function() { longPressTriggered = false; }, 400);
|
||||
};
|
||||
})(el);
|
||||
el.ondragstart = function(ev) {
|
||||
ev.dataTransfer.setData('text/plain', ev.currentTarget.getAttribute('data-index'));
|
||||
ev.dataTransfer.effectAllowed = 'move';
|
||||
ev.currentTarget.classList.add('dragging');
|
||||
};
|
||||
el.ondragend = function(ev) {
|
||||
ev.currentTarget.classList.remove('dragging');
|
||||
};
|
||||
el.ondragover = function(ev) {
|
||||
ev.preventDefault();
|
||||
ev.dataTransfer.dropEffect = 'move';
|
||||
var target = ev.currentTarget;
|
||||
if (target.classList.contains('dragging')) return;
|
||||
target.classList.add('drop-target');
|
||||
};
|
||||
el.ondragleave = function(ev) {
|
||||
ev.currentTarget.classList.remove('drop-target');
|
||||
};
|
||||
el.ondrop = function(ev) {
|
||||
ev.preventDefault();
|
||||
ev.currentTarget.classList.remove('drop-target');
|
||||
var fromIdx = parseInt(ev.dataTransfer.getData('text/plain'), 10);
|
||||
var toIdx = parseInt(ev.currentTarget.getAttribute('data-index'), 10);
|
||||
if (fromIdx === toIdx) return;
|
||||
var buttons = getButtonsFromDom();
|
||||
var item = buttons.splice(fromIdx, 1)[0];
|
||||
buttons.splice(toIdx, 0, item);
|
||||
renderButtons(buttons);
|
||||
saveButtons(buttons);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Button editor (per-button preset config)
|
||||
|
||||
function saveButtons(buttons, callback) {
|
||||
fetch('/api/buttons', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ buttons: buttons })
|
||||
}).then(function(r) { return r.json(); }).then(function(data) {
|
||||
if (callback) callback(data);
|
||||
else showToast(data.ok ? 'Saved' : (data.error || 'Save failed'));
|
||||
}).catch(function() {
|
||||
if (callback) callback({ ok: false });
|
||||
else showToast('Save failed');
|
||||
});
|
||||
}
|
||||
|
||||
function saveCurrentButtons() {
|
||||
var buttons = getButtonsFromDom();
|
||||
saveButtons(buttons, function(data) {
|
||||
showToast(data.ok ? 'Saved' : (data.error || 'Save failed'));
|
||||
});
|
||||
}
|
||||
|
||||
var toastTimer = null;
|
||||
|
||||
function showToast(message) {
|
||||
var el = document.getElementById('toast');
|
||||
if (!el) {
|
||||
el = document.createElement('div');
|
||||
el.id = 'toast';
|
||||
el.className = 'toast';
|
||||
document.body.appendChild(el);
|
||||
}
|
||||
el.textContent = message;
|
||||
el.classList.add('toast-visible');
|
||||
if (toastTimer) clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(function() {
|
||||
el.classList.remove('toast-visible');
|
||||
toastTimer = null;
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function addButton(button) {
|
||||
var buttons = getButtonsFromDom();
|
||||
buttons.push(button);
|
||||
renderButtons(buttons);
|
||||
saveButtons(buttons);
|
||||
}
|
||||
|
||||
var contextMenuEl = null;
|
||||
var longPressTimer = null;
|
||||
var longPressTriggered = false;
|
||||
|
||||
function openNewButtonEditor() {
|
||||
currentEditIndex = -1;
|
||||
var title = document.getElementById('buttonEditorTitle');
|
||||
if (title) title.textContent = 'New button';
|
||||
fillButtonEditorFields({
|
||||
id: '',
|
||||
preset: '',
|
||||
p: 'off',
|
||||
d: 0,
|
||||
b: 0,
|
||||
c: [[0, 0, 0]]
|
||||
});
|
||||
openButtonEditor();
|
||||
}
|
||||
|
||||
function openExistingButtonEditor(index) {
|
||||
currentEditIndex = index;
|
||||
var buttons = getButtonsFromDom();
|
||||
var btn = buttons[index];
|
||||
var title = document.getElementById('buttonEditorTitle');
|
||||
if (title) title.textContent = 'Edit button';
|
||||
fillButtonEditorFields(btn);
|
||||
openButtonEditor();
|
||||
}
|
||||
|
||||
function openButtonEditor() {
|
||||
var editor = document.getElementById('buttonEditor');
|
||||
if (!editor) return;
|
||||
editor.classList.add('open');
|
||||
document.body.classList.add('button-editor-open');
|
||||
}
|
||||
|
||||
function closeButtonEditor() {
|
||||
var editor = document.getElementById('buttonEditor');
|
||||
if (!editor) return;
|
||||
editor.classList.remove('open');
|
||||
document.body.classList.remove('button-editor-open');
|
||||
}
|
||||
|
||||
function fillButtonEditorFields(btn) {
|
||||
document.getElementById('be-label').value = btn.id || '';
|
||||
document.getElementById('be-preset').value = btn.preset || btn.id || '';
|
||||
var pattern = btn.p || btn.preset || 'off';
|
||||
var patternSelect = document.getElementById('be-pattern');
|
||||
if (patternSelect) {
|
||||
patternSelect.value = pattern;
|
||||
}
|
||||
document.getElementById('be-delay').value = btn.d != null ? String(btn.d) : '';
|
||||
document.getElementById('be-brightness').value = btn.b != null ? String(btn.b) : '';
|
||||
var colors = btn.c;
|
||||
var colorsStr = '';
|
||||
if (Array.isArray(colors) && colors.length) {
|
||||
colorsStr = colors.map(function (rgb) {
|
||||
return (rgb[0] || 0) + ',' + (rgb[1] || 0) + ',' + (rgb[2] || 0);
|
||||
}).join('; ');
|
||||
}
|
||||
document.getElementById('be-colors').value = colorsStr;
|
||||
for (var i = 1; i <= 8; i++) {
|
||||
var key = 'n' + i;
|
||||
var el = document.getElementById('be-' + key);
|
||||
if (el) el.value = btn[key] != null ? String(btn[key]) : '';
|
||||
}
|
||||
}
|
||||
|
||||
function buildButtonFromEditor() {
|
||||
function toInt(val, fallback) {
|
||||
var n = parseInt(val, 10);
|
||||
return isNaN(n) ? fallback : n;
|
||||
}
|
||||
|
||||
var label = (document.getElementById('be-label').value || '').trim();
|
||||
var presetName = (document.getElementById('be-preset').value || '').trim() || label || 'preset';
|
||||
var patternEl = document.getElementById('be-pattern');
|
||||
var pattern = patternEl ? (patternEl.value || '').trim() : 'off';
|
||||
var delayVal = document.getElementById('be-delay').value;
|
||||
var brightVal = document.getElementById('be-brightness').value;
|
||||
var colorsRaw = (document.getElementById('be-colors').value || '').trim();
|
||||
|
||||
var d = toInt(delayVal, 0);
|
||||
var b = toInt(brightVal, 0);
|
||||
|
||||
var colors = [];
|
||||
if (colorsRaw) {
|
||||
colorsRaw.split(';').forEach(function (chunk) {
|
||||
var parts = chunk.split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
||||
if (parts.length === 3) {
|
||||
var r = toInt(parts[0], 0);
|
||||
var g = toInt(parts[1], 0);
|
||||
var bl = toInt(parts[2], 0);
|
||||
r = Math.max(0, Math.min(255, r));
|
||||
g = Math.max(0, Math.min(255, g));
|
||||
bl = Math.max(0, Math.min(255, bl));
|
||||
colors.push([r, g, bl]);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!colors.length) colors = [[0, 0, 0]];
|
||||
|
||||
var btn = {
|
||||
id: label || presetName,
|
||||
preset: presetName,
|
||||
p: pattern,
|
||||
d: d,
|
||||
b: b,
|
||||
c: colors
|
||||
};
|
||||
|
||||
for (var i = 1; i <= 8; i++) {
|
||||
var key = 'n' + i;
|
||||
var el = document.getElementById('be-' + key);
|
||||
if (!el) continue;
|
||||
var v = el.value;
|
||||
if (v !== '') {
|
||||
btn[key] = toInt(v, 0);
|
||||
}
|
||||
}
|
||||
|
||||
return btn;
|
||||
}
|
||||
|
||||
function saveButtonFromEditor() {
|
||||
var btn = buildButtonFromEditor();
|
||||
var buttons = getButtonsFromDom();
|
||||
if (currentEditIndex >= 0 && currentEditIndex < buttons.length) {
|
||||
buttons[currentEditIndex] = btn;
|
||||
} else {
|
||||
buttons.push(btn);
|
||||
}
|
||||
renderButtons(buttons);
|
||||
saveButtons(buttons);
|
||||
|
||||
// Also send this preset to the Pico and save it there
|
||||
if (ws && ws.readyState === WebSocket.OPEN && btn.preset) {
|
||||
var presetData = {
|
||||
p: btn.p,
|
||||
d: btn.d,
|
||||
b: btn.b,
|
||||
c: btn.c
|
||||
};
|
||||
for (var i = 1; i <= 8; i++) {
|
||||
var key = 'n' + i;
|
||||
if (btn[key] !== undefined) {
|
||||
presetData[key] = btn[key];
|
||||
}
|
||||
}
|
||||
ws.send(JSON.stringify({
|
||||
preset_edit: {
|
||||
name: btn.preset,
|
||||
data: presetData
|
||||
}
|
||||
}));
|
||||
ws.send(JSON.stringify({ preset_save: true }));
|
||||
}
|
||||
|
||||
closeButtonEditor();
|
||||
}
|
||||
|
||||
function showButtonContextMenu(evOrCoords, buttonEl) {
|
||||
hideContextMenu();
|
||||
var x = evOrCoords.clientX != null ? evOrCoords.clientX : evOrCoords.x;
|
||||
var y = evOrCoords.clientY != null ? evOrCoords.clientY : evOrCoords.y;
|
||||
var buttons = getButtonsFromDom();
|
||||
var idx = parseInt(buttonEl.getAttribute('data-index'), 10);
|
||||
var btn = buttons[idx];
|
||||
contextMenuEl = document.createElement('div');
|
||||
contextMenuEl.className = 'context-menu';
|
||||
contextMenuEl.style.left = x + 'px';
|
||||
contextMenuEl.style.top = y + 'px';
|
||||
contextMenuEl.innerHTML = '<button type="button" class="context-menu-item" data-action="edit">Edit</button><button type="button" class="context-menu-item" data-action="delete">Delete</button>';
|
||||
document.body.appendChild(contextMenuEl);
|
||||
document.addEventListener('click', hideContextMenuOnce);
|
||||
contextMenuEl.querySelector('[data-action="edit"]').onclick = function() {
|
||||
hideContextMenu();
|
||||
openExistingButtonEditor(idx);
|
||||
};
|
||||
contextMenuEl.querySelector('[data-action="delete"]').onclick = function() {
|
||||
hideContextMenu();
|
||||
buttons.splice(idx, 1);
|
||||
renderButtons(buttons);
|
||||
saveButtons(buttons);
|
||||
};
|
||||
}
|
||||
|
||||
function hideContextMenu() {
|
||||
if (contextMenuEl && contextMenuEl.parentNode) contextMenuEl.parentNode.removeChild(contextMenuEl);
|
||||
contextMenuEl = null;
|
||||
document.removeEventListener('click', hideContextMenuOnce);
|
||||
}
|
||||
|
||||
function hideContextMenuOnce() {
|
||||
hideContextMenu();
|
||||
}
|
||||
|
||||
function connect() {
|
||||
var proto = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
ws = new WebSocket(proto + "//" + location.host + "/ws");
|
||||
ws.onclose = function() { setTimeout(connect, 2000); };
|
||||
ws.onmessage = function(ev) {
|
||||
try {
|
||||
var msg = JSON.parse(ev.data);
|
||||
if (msg && msg.select != null) {
|
||||
var preset = typeof msg.select === 'string' ? msg.select : (Array.isArray(msg.select) ? msg.select[1] : null);
|
||||
if (preset != null) {
|
||||
document.querySelectorAll('.buttons .btn').forEach(function(b) { b.classList.remove('selected'); });
|
||||
if (preset !== 'off') {
|
||||
var el = document.querySelector('.buttons .btn[data-preset="' + preset + '"]');
|
||||
if (el) {
|
||||
el.classList.add('selected');
|
||||
scrollSelectedIntoView();
|
||||
updateSelectedObserver();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
};
|
||||
}
|
||||
|
||||
function sendSelect(preset, el) {
|
||||
var msg = JSON.stringify({ select: preset });
|
||||
if (ws && ws.readyState === WebSocket.OPEN) ws.send(msg);
|
||||
document.querySelectorAll('.buttons .btn').forEach(function(b) { b.classList.remove('selected'); });
|
||||
if (el) el.classList.add('selected');
|
||||
updateSelectedObserver();
|
||||
}
|
||||
|
||||
function togglePresetEditor() {
|
||||
var editor = document.getElementById('presetEditor');
|
||||
if (!editor) return;
|
||||
var isOpen = editor.classList.contains('open');
|
||||
if (isOpen) {
|
||||
editor.classList.remove('open');
|
||||
document.body.classList.remove('preset-editor-open');
|
||||
} else {
|
||||
editor.classList.add('open');
|
||||
document.body.classList.add('preset-editor-open');
|
||||
}
|
||||
}
|
||||
|
||||
function buildPresetPayloadFromForm() {
|
||||
var name = (document.getElementById('pe-name').value || '').trim();
|
||||
var patternEl = document.getElementById('pe-pattern');
|
||||
var pattern = patternEl ? (patternEl.value || '').trim() : 'off';
|
||||
var delayVal = document.getElementById('pe-delay').value;
|
||||
var brightVal = document.getElementById('pe-brightness').value;
|
||||
var colorsRaw = (document.getElementById('pe-colors').value || '').trim();
|
||||
|
||||
function toInt(val, fallback) {
|
||||
var n = parseInt(val, 10);
|
||||
return isNaN(n) ? fallback : n;
|
||||
}
|
||||
|
||||
var d = toInt(delayVal, 0);
|
||||
var b = toInt(brightVal, 0);
|
||||
|
||||
var colors = [];
|
||||
if (colorsRaw) {
|
||||
colorsRaw.split(';').forEach(function (chunk) {
|
||||
var parts = chunk.split(',').map(function (s) { return s.trim(); }).filter(Boolean);
|
||||
if (parts.length === 3) {
|
||||
var r = toInt(parts[0], 0);
|
||||
var g = toInt(parts[1], 0);
|
||||
var bl = toInt(parts[2], 0);
|
||||
r = Math.max(0, Math.min(255, r));
|
||||
g = Math.max(0, Math.min(255, g));
|
||||
bl = Math.max(0, Math.min(255, bl));
|
||||
colors.push([r, g, bl]);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!colors.length) colors = [[0, 0, 0]];
|
||||
|
||||
var data = { p: pattern, d: d, b: b, c: colors };
|
||||
|
||||
['n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8'].forEach(function (key) {
|
||||
var el = document.getElementById('pe-' + key);
|
||||
if (!el) return;
|
||||
var v = el.value;
|
||||
if (v !== '') {
|
||||
data[key] = toInt(v, 0);
|
||||
}
|
||||
});
|
||||
|
||||
return { name: name, data: data };
|
||||
}
|
||||
|
||||
function sendPresetToPico() {
|
||||
var payload = buildPresetPayloadFromForm();
|
||||
if (!payload.name) {
|
||||
showToast('Preset name is required');
|
||||
return;
|
||||
}
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ preset_edit: payload }));
|
||||
ensurePresetInList(payload.name);
|
||||
showToast('Preset sent (not yet saved)');
|
||||
} else {
|
||||
showToast('Not connected');
|
||||
}
|
||||
}
|
||||
|
||||
function savePresetsOnPico() {
|
||||
var payload = buildPresetPayloadFromForm();
|
||||
if (!payload.name) {
|
||||
showToast('Preset name is required');
|
||||
return;
|
||||
}
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ preset_edit: payload }));
|
||||
ws.send(JSON.stringify({ preset_save: true }));
|
||||
ensurePresetInList(payload.name);
|
||||
showToast('Preset saved to Pico');
|
||||
} else {
|
||||
showToast('Not connected');
|
||||
}
|
||||
}
|
||||
|
||||
function deletePresetOnPico() {
|
||||
var name = (document.getElementById('pe-name').value || '').trim();
|
||||
if (!name) {
|
||||
showToast('Preset name is required');
|
||||
return;
|
||||
}
|
||||
var msg = { preset_delete: name };
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify(msg));
|
||||
removePresetFromList(name);
|
||||
ws.send(JSON.stringify(msg));
|
||||
showToast('Delete command sent');
|
||||
} else {
|
||||
showToast('Not connected');
|
||||
}
|
||||
}
|
||||
|
||||
function toggleMenu() {
|
||||
var menu = document.getElementById('menu');
|
||||
menu.classList.toggle('open');
|
||||
}
|
||||
|
||||
function closeMenu() {
|
||||
document.getElementById('menu').classList.remove('open');
|
||||
}
|
||||
|
||||
document.addEventListener('click', function(ev) {
|
||||
var menu = document.getElementById('menu');
|
||||
var menuBtn = document.querySelector('.menu-btn');
|
||||
if (menu.classList.contains('open') && menuBtn && !menu.contains(ev.target) && !menuBtn.contains(ev.target)) {
|
||||
closeMenu();
|
||||
}
|
||||
});
|
||||
|
||||
function scrollSelectedIntoView() {
|
||||
var el = document.querySelector('.buttons .btn.selected');
|
||||
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
|
||||
}
|
||||
|
||||
var scrollObserver = null;
|
||||
var observedSelectedEl = null;
|
||||
|
||||
function setupScrollObserver() {
|
||||
var container = document.getElementById('buttonsContainer');
|
||||
if (!container || scrollObserver) return;
|
||||
scrollObserver = new IntersectionObserver(
|
||||
function (entries) {
|
||||
entries.forEach(function (entry) {
|
||||
if (entry.intersectionRatio < 0.5 && entry.target.classList.contains('selected')) {
|
||||
scrollSelectedIntoView();
|
||||
}
|
||||
});
|
||||
},
|
||||
{ root: container, rootMargin: '0px', threshold: [0, 0.25, 0.5, 0.75, 1] }
|
||||
);
|
||||
}
|
||||
|
||||
function updateSelectedObserver() {
|
||||
var el = document.querySelector('.buttons .btn.selected');
|
||||
if (el === observedSelectedEl) return;
|
||||
if (scrollObserver) {
|
||||
if (observedSelectedEl) scrollObserver.unobserve(observedSelectedEl);
|
||||
observedSelectedEl = el;
|
||||
if (el) {
|
||||
setupScrollObserver();
|
||||
scrollObserver.observe(el);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function nextPreset() {
|
||||
var btns = document.querySelectorAll('.buttons .btn');
|
||||
if (btns.length === 0) return;
|
||||
var idx = -1;
|
||||
for (var i = 0; i < btns.length; i++) {
|
||||
if (btns[i].classList.contains('selected')) { idx = i; break; }
|
||||
}
|
||||
idx = (idx + 1) % btns.length;
|
||||
var nextEl = btns[idx];
|
||||
sendSelect(nextEl.getAttribute('data-preset'), nextEl);
|
||||
scrollSelectedIntoView();
|
||||
}
|
||||
|
||||
setupScrollObserver();
|
||||
// Re-render buttons from server config (including per-button presets) once loaded.
|
||||
fetch('/api/buttons')
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (data) {
|
||||
var buttons = Array.isArray(data.buttons) ? data.buttons : getButtonsFromDom();
|
||||
renderButtons(buttons);
|
||||
})
|
||||
.catch(function () {
|
||||
// Fallback: use buttons rendered by the template
|
||||
renderButtons(getButtonsFromDom());
|
||||
});
|
||||
updateSelectedObserver();
|
||||
connect();
|
||||
@@ -0,0 +1,256 @@
|
||||
body { font-family: sans-serif; margin: 0; padding: 0 0 6.5rem 0; }
|
||||
|
||||
body.button-editor-open {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.header { position: relative; }
|
||||
|
||||
.menu-btn {
|
||||
width: 100%;
|
||||
padding: 0.75rem 1rem;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
border: 1px solid #555;
|
||||
border-radius: 0;
|
||||
background: #333;
|
||||
color: #fff;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.menu {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
flex-direction: column;
|
||||
border: 1px solid #555;
|
||||
border-top: none;
|
||||
background: #2a2a2a;
|
||||
box-shadow: 0 4px 8px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
.menu.open { display: flex; }
|
||||
|
||||
.menu-item {
|
||||
padding: 0.75rem 1rem;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-bottom: 1px solid #444;
|
||||
background: transparent;
|
||||
color: #fff;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.menu-item:last-child { border-bottom: none; }
|
||||
|
||||
.menu-item:hover { background: #444; }
|
||||
|
||||
.menu-item.off { background: #522; }
|
||||
|
||||
.buttons {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 1px;
|
||||
max-height: calc(100vh - 10rem);
|
||||
overflow-y: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.buttons {
|
||||
grid-template-columns: repeat(6, 1fr);
|
||||
}
|
||||
}
|
||||
.btn {
|
||||
padding: 0.5rem 0.25rem;
|
||||
border: 1px solid #555;
|
||||
border-radius: 0;
|
||||
background: #444;
|
||||
color: #fff;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
min-height: 4.15rem;
|
||||
}
|
||||
.btn.selected {
|
||||
background: #2a7;
|
||||
border-color: #3b8;
|
||||
}
|
||||
|
||||
.btn.dragging { opacity: 0.5; }
|
||||
|
||||
.btn.drop-target { outline: 2px solid #3b8; outline-offset: -2px; }
|
||||
|
||||
.context-menu {
|
||||
position: fixed;
|
||||
z-index: 100;
|
||||
background: #2a2a2a;
|
||||
border: 1px solid #555;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
|
||||
min-width: 8rem;
|
||||
}
|
||||
|
||||
.context-menu-item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0.5rem 1rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #fff;
|
||||
font-size: 1rem;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.context-menu-item:hover { background: #444; }
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
bottom: 5rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%) translateY(2rem);
|
||||
padding: 0.5rem 1rem;
|
||||
background: #333;
|
||||
color: #fff;
|
||||
border-radius: 4px;
|
||||
font-size: 0.9rem;
|
||||
z-index: 1000;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s, transform 0.2s;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast.toast-visible {
|
||||
opacity: 1;
|
||||
transform: translateX(-50%) translateY(0);
|
||||
}
|
||||
.next-btn {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
width: 100%;
|
||||
padding: 2rem 1rem;
|
||||
padding-bottom: max(2rem, env(safe-area-inset-bottom));
|
||||
font-size: 1.25rem;
|
||||
cursor: pointer;
|
||||
border: 2px solid #555;
|
||||
border-radius: 0;
|
||||
background: #333;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.preset-editor {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 200;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.preset-editor.open {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.preset-editor-inner {
|
||||
width: 100%;
|
||||
max-width: 28rem;
|
||||
max-height: calc(100vh - 4rem);
|
||||
overflow-y: auto;
|
||||
background: #222;
|
||||
border: 1px solid #555;
|
||||
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.6);
|
||||
border-radius: 6px;
|
||||
padding: 1rem 1.25rem 0.75rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.preset-editor-title {
|
||||
margin: 0 0 0.75rem;
|
||||
font-size: 1.25rem;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.preset-editor-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-bottom: 0.5rem;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.9rem;
|
||||
color: #ddd;
|
||||
}
|
||||
|
||||
.preset-editor-field span {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.preset-editor-field input {
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #555;
|
||||
background: #111;
|
||||
color: #fff;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.preset-editor-row {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.preset-editor-field.small {
|
||||
flex: 0 0 48%;
|
||||
}
|
||||
|
||||
.preset-editor-field.small input {
|
||||
padding: 0.25rem 0.4rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.preset-editor-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin: 0.75rem 0 0.5rem;
|
||||
}
|
||||
|
||||
.preset-editor-btn {
|
||||
flex: 1;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #555;
|
||||
background: #333;
|
||||
color: #fff;
|
||||
font-size: 0.95rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.preset-editor-btn.primary {
|
||||
background: #2a7;
|
||||
border-color: #3b8;
|
||||
}
|
||||
|
||||
.preset-editor-btn.danger {
|
||||
background: #722;
|
||||
border-color: #a33;
|
||||
}
|
||||
|
||||
.preset-editor-close {
|
||||
width: 100%;
|
||||
margin-top: 0.25rem;
|
||||
padding: 0.4rem 0.75rem;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #555;
|
||||
background: #111;
|
||||
color: #ccc;
|
||||
font-size: 0.9rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* preset-list removed with old preset editor */
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 44 KiB |
@@ -0,0 +1,243 @@
|
||||
// Pico enclosure that saddles a 25mm hoop bar (900mm hoop diameter).
|
||||
// OpenSCAD 2021+: F5 preview, F6 render, export STL.
|
||||
//
|
||||
// Prints as body + lid. Clip onto the bar, secure with zip-ties through the
|
||||
// saddle slots. Lid snaps into the bay rim.
|
||||
//
|
||||
// Frame: bar centre at origin, +Z away from hoop centre, +Y along hoop,
|
||||
// +X across the bar.
|
||||
|
||||
/* [Hoop] */
|
||||
// hoop_diameter kept for reference / future curved saddle (~0.9mm sag over 58mm)
|
||||
hoop_diameter = 900; // tube centerline diameter (mm)
|
||||
bar_diameter = 25; // bar / tube OD (mm)
|
||||
bar_clearance = 0.35; // radial slip around the bar
|
||||
|
||||
/* [Pico bay] */
|
||||
pico_length = 52.5; // clearance along hoop
|
||||
pico_width = 22.0; // clearance across bar
|
||||
pico_height = 12.0; // board + headers / wiring
|
||||
wall = 2.0;
|
||||
lid_thick = 2.0;
|
||||
lid_lip = 1.4;
|
||||
lid_clear = 0.3;
|
||||
|
||||
/* [Saddle / clamp] */
|
||||
saddle_wrap_deg = 230; // >180 so it snaps onto the bar
|
||||
saddle_wall = 2.6;
|
||||
saddle_length = 58; // along hoop (mm)
|
||||
ziptie_w = 3.8;
|
||||
ziptie_h = 2.0;
|
||||
ziptie_inset = 9; // from each saddle end toward centre
|
||||
ear_len = 7; // zip-tie ears sticking out each side
|
||||
ear_thick = 3;
|
||||
|
||||
/* [Ports / access] */
|
||||
// Pico USB end faces +Y. Board is centred on the bay; hole centres are
|
||||
// 2mm in from each short edge of the 51mm PCB.
|
||||
board_length = 51.0;
|
||||
board_width = 21.0;
|
||||
board_thick = 1.0;
|
||||
|
||||
// Micro-USB B cutout (plug clearance)
|
||||
usb_w = 9.0;
|
||||
usb_h = 4.2;
|
||||
usb_z_above_board = 0.2; // opening starts just above PCB top
|
||||
|
||||
// Power-out cable (opposite USB, -Y end) — LED / battery feed
|
||||
power_hole_d = 6.0;
|
||||
|
||||
// BOOTSEL through lid (from USB-end PCB edge / board centre)
|
||||
// Measured from Pico mechanical layout: ~5.7mm from USB edge, ~4.8mm left of centre.
|
||||
bootsel_from_usb_edge = 5.7;
|
||||
bootsel_x = -4.8; // -X when USB is at +Y
|
||||
bootsel_hole_d = 4.5;
|
||||
|
||||
/* [Pico mounting posts] */
|
||||
// Official Pico hole centres: 47.0 x 11.4 mm
|
||||
hole_span_l = 47.0;
|
||||
hole_span_w = 11.4;
|
||||
post_od = 4.2;
|
||||
post_id = 1.7; // M2 self-tap
|
||||
post_h = 3.0;
|
||||
|
||||
/* [Quality] */
|
||||
$fn = 80;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
bar_r = bar_diameter / 2;
|
||||
saddle_ir = bar_r + bar_clearance;
|
||||
saddle_or = saddle_ir + saddle_wall;
|
||||
|
||||
bay_inner_l = pico_length;
|
||||
bay_inner_w = pico_width;
|
||||
bay_inner_h = pico_height;
|
||||
bay_outer_l = bay_inner_l + 2 * wall;
|
||||
bay_outer_w = max(bay_inner_w + 2 * wall, 2 * saddle_or + 1);
|
||||
bay_outer_h = bay_inner_h + wall;
|
||||
bay_floor_z = saddle_or;
|
||||
|
||||
// 2D clip profile in the plane normal to the bar (X = across, Y = up).
|
||||
module saddle_profile() {
|
||||
wrap = saddle_wrap_deg;
|
||||
// Keep the top half solid (shoulders under the bay) and a partial ring below.
|
||||
difference() {
|
||||
union() {
|
||||
// outer disc, then cut to wrap angle from the bottom
|
||||
circle(r = saddle_or);
|
||||
// rectangular shoulders up to bay floor
|
||||
translate([-saddle_or, 0])
|
||||
square([2 * saddle_or, saddle_or + 0.01]);
|
||||
}
|
||||
circle(r = saddle_ir);
|
||||
// remove the open sector at the bottom (clip mouth)
|
||||
half_gap = (360 - wrap) / 2;
|
||||
rotate(-(90 + wrap / 2))
|
||||
pie_slice(saddle_or + 1, 360 - wrap);
|
||||
}
|
||||
}
|
||||
|
||||
module pie_slice(r, ang) {
|
||||
// Triangle fan covering `ang` degrees starting at +X, CCW.
|
||||
steps = max(3, ceil(ang / 4));
|
||||
polygon(concat([[0, 0]],
|
||||
[for (i = [0:steps]) [r * cos(i * ang / steps), r * sin(i * ang / steps)]]));
|
||||
}
|
||||
|
||||
module pico_posts() {
|
||||
for (x = [-hole_span_w / 2, hole_span_w / 2])
|
||||
for (y = [-hole_span_l / 2, hole_span_l / 2])
|
||||
translate([x, y, 0])
|
||||
difference() {
|
||||
cylinder(h = post_h, d = post_od);
|
||||
translate([0, 0, -0.05])
|
||||
cylinder(h = post_h + 0.1, d = post_id, $fn = 20);
|
||||
}
|
||||
}
|
||||
|
||||
module body() {
|
||||
// USB opening bottom (board sits on standoffs)
|
||||
usb_z = bay_floor_z + wall + post_h + board_thick + usb_z_above_board;
|
||||
|
||||
difference() {
|
||||
union() {
|
||||
// Saddle — extruded along the bar (+Y). Hoop curvature over 58mm is
|
||||
// ~0.9mm sag; ignored so the part prints and clips simply.
|
||||
translate([0, saddle_length / 2, 0])
|
||||
rotate([90, 0, 0])
|
||||
linear_extrude(height = saddle_length, convexity = 8)
|
||||
saddle_profile();
|
||||
|
||||
// Electronics bay on top of the saddle
|
||||
translate([-bay_outer_w / 2, -bay_outer_l / 2, bay_floor_z])
|
||||
cube([bay_outer_w, bay_outer_l, bay_outer_h]);
|
||||
}
|
||||
|
||||
// Bay cavity
|
||||
translate([-bay_inner_w / 2, -bay_inner_l / 2, bay_floor_z + wall])
|
||||
cube([bay_inner_w, bay_inner_l, bay_inner_h + 0.2]);
|
||||
|
||||
// Lid ledge
|
||||
translate([
|
||||
-(bay_inner_w + 2 * lid_lip) / 2,
|
||||
-(bay_inner_l + 2 * lid_lip) / 2,
|
||||
bay_floor_z + bay_outer_h - lid_thick
|
||||
])
|
||||
cube([
|
||||
bay_inner_w + 2 * lid_lip,
|
||||
bay_inner_l + 2 * lid_lip,
|
||||
lid_thick + 0.15
|
||||
]);
|
||||
|
||||
// USB cutout — +Y end, height matches board on standoffs
|
||||
translate([0, bay_outer_l / 2 - wall / 2, usb_z + usb_h / 2])
|
||||
cube([usb_w, wall + 2, usb_h], center = true);
|
||||
|
||||
// Power-out hole — −Y end (opposite USB), for LED / battery wires
|
||||
translate([
|
||||
0,
|
||||
-(bay_outer_l / 2 - wall / 2),
|
||||
bay_floor_z + wall + power_hole_d / 2 + 1
|
||||
])
|
||||
rotate([90, 0, 0])
|
||||
cylinder(h = wall + 2, d = power_hole_d, center = true);
|
||||
|
||||
// Ensure bar bore is clear through the whole saddle
|
||||
rotate([90, 0, 0])
|
||||
cylinder(h = saddle_length + 2, r = saddle_ir, center = true);
|
||||
}
|
||||
|
||||
// Zip-tie ears on both sides — strap goes around bar + saddle
|
||||
for (sx = [-1, 1])
|
||||
translate([sx * (saddle_or + ear_len / 2 - 1.2), 0, -ear_thick / 2])
|
||||
difference() {
|
||||
cube([ear_len + 2.4, saddle_length - 2 * ziptie_inset + ziptie_w, ear_thick], center = true);
|
||||
// don't fill the bar bore
|
||||
rotate([90, 0, 0])
|
||||
cylinder(h = saddle_length, r = saddle_ir, center = true);
|
||||
for (sy = [-1, 1])
|
||||
translate([0, sy * (saddle_length / 2 - ziptie_inset), 0])
|
||||
cube([ear_len + 4, ziptie_w, ziptie_h], center = true);
|
||||
}
|
||||
|
||||
// Board standoffs
|
||||
translate([0, 0, bay_floor_z + wall])
|
||||
pico_posts();
|
||||
|
||||
// Lid retention nubs
|
||||
nub_z = bay_floor_z + bay_outer_h - lid_thick - 1.0;
|
||||
for (x = [-1, 1])
|
||||
translate([x * (bay_inner_w / 2 - 0.25), 0, nub_z])
|
||||
rotate([90, 0, 0])
|
||||
cylinder(h = 8, d = 1.5, center = true, $fn = 16);
|
||||
}
|
||||
|
||||
module lid() {
|
||||
outer_l = bay_inner_l + 2 * lid_lip - lid_clear;
|
||||
outer_w = bay_inner_w + 2 * lid_lip - lid_clear;
|
||||
inner_l = bay_inner_l - lid_clear;
|
||||
inner_w = bay_inner_w - lid_clear;
|
||||
|
||||
// BOOTSEL in body frame: USB end at +Y. Lid shares the same XY origin.
|
||||
bootsel_y = board_length / 2 - bootsel_from_usb_edge;
|
||||
|
||||
difference() {
|
||||
union() {
|
||||
translate([-outer_w / 2, -outer_l / 2, 0])
|
||||
cube([outer_w, outer_l, lid_thick]);
|
||||
translate([-inner_w / 2, -inner_l / 2, -lid_lip])
|
||||
cube([inner_w, inner_l, lid_lip]);
|
||||
}
|
||||
// BOOTSEL access (finger / pen)
|
||||
translate([bootsel_x, bootsel_y, -lid_lip - 0.5])
|
||||
cylinder(h = lid_thick + lid_lip + 1, d = bootsel_hole_d, $fn = 32);
|
||||
// Nail notch on USB end
|
||||
translate([0, outer_l / 2 - 0.5, lid_thick / 2])
|
||||
rotate([0, 90, 0])
|
||||
cylinder(h = 14, d = 3.2, center = true, $fn = 24);
|
||||
// Snap recesses matching body nubs
|
||||
for (x = [-1, 1])
|
||||
translate([x * (inner_w / 2 - 0.15), 0, -0.6])
|
||||
rotate([90, 0, 0])
|
||||
cylinder(h = 9, d = 1.7, center = true, $fn = 16);
|
||||
}
|
||||
}
|
||||
|
||||
module print_layout() {
|
||||
body();
|
||||
translate([bay_outer_w + 14, 0, lid_thick])
|
||||
rotate([0, 180, 0])
|
||||
lid();
|
||||
}
|
||||
|
||||
module preview_on_bar() {
|
||||
body();
|
||||
translate([0, 0, bay_floor_z + bay_outer_h - lid_thick])
|
||||
color("steelblue", 0.7) lid();
|
||||
color("silver", 0.35)
|
||||
rotate([90, 0, 0])
|
||||
cylinder(h = 90, d = bar_diameter, center = true);
|
||||
}
|
||||
|
||||
print_layout();
|
||||
// preview_on_bar();
|
||||
+19014
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 41 KiB |
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"buttons": [
|
||||
{"id": "start", "preset": "off"},
|
||||
{"id": "grab", "preset": "grab"},
|
||||
{"id": "spin1", "preset": "spin1"},
|
||||
{"id": "lift", "preset": "lift"},
|
||||
{"id": "flare", "preset": "flare"},
|
||||
{"id": "hook", "preset": "hook"},
|
||||
{"id": "roll1", "preset": "roll1"},
|
||||
{"id": "invertsplit", "preset": "invertsplit"},
|
||||
{"id": "pose1", "preset": "pose1"},
|
||||
{"id": "pose1", "preset": "pose2"},
|
||||
{"id": "roll2", "preset": "roll2"},
|
||||
{"id": "backbalance1", "preset": "backbalance1"},
|
||||
{"id": "beat1", "preset": "beat1"},
|
||||
{"id": "pose3", "preset": "pose3"},
|
||||
{"id": "roll3", "preset": "roll3"},
|
||||
{"id": "crouch", "preset": "crouch"},
|
||||
{"id": "pose4", "preset": "pose4"},
|
||||
{"id": "roll4", "preset": "roll4"},
|
||||
{"id": "backbendsplit", "preset": "backbendsplit"},
|
||||
{"id": "backbalance2", "preset": "backbalance2"},
|
||||
{"id": "backbalance3", "preset": "backbalance3"},
|
||||
{"id": "beat2", "preset": "beat2"},
|
||||
{"id": "straddle", "preset": "straddle"},
|
||||
{"id": "beat3", "preset": "beat3"},
|
||||
{"id": "frontbalance1", "preset": "frontbalance1"},
|
||||
{"id": "pose5", "preset": "pose5"},
|
||||
{"id": "pose6", "preset": "pose6"},
|
||||
{"id": "elbowhang", "preset": "elbowhang"},
|
||||
{"id": "elbowhangspin", "preset": "elbowhangspin"},
|
||||
{"id": "spin2", "preset": "spin2"},
|
||||
{"id": "dismount", "preset": "dismount"},
|
||||
{"id": "spin3", "preset": "spin3"},
|
||||
{"id": "fluff", "preset": "fluff"},
|
||||
{"id": "spin4", "preset": "spin4"},
|
||||
{"id": "flare2", "preset": "flare2"},
|
||||
{"id": "elbowhang", "preset": "elbowhang"},
|
||||
{"id": "elbowhangsplit2", "preset": "elbowhangsplit2"},
|
||||
{"id": "invert", "preset": "invert"},
|
||||
{"id": "roll5", "preset": "roll5"},
|
||||
{"id": "backbend", "preset": "backbend"},
|
||||
{"id": "pose7", "preset": "pose7"},
|
||||
{"id": "roll6", "preset": "roll6"},
|
||||
{"id": "seat", "preset": "seat"},
|
||||
{"id": "kneehang", "preset": "kneehang"},
|
||||
{"id": "legswoop", "preset": "legswoop"},
|
||||
{"id": "split", "preset": "split"},
|
||||
{"id": "foothang", "preset": "foothang"},
|
||||
{"id": "end", "preset": "end"}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -65,9 +65,7 @@
|
||||
<option value="legswoop">legswoop</option>
|
||||
<option value="split">split</option>
|
||||
<option value="foothang">foothang</option>
|
||||
<option value="segments">segments</option>
|
||||
<option value="segments_transition">segments_transition</option>
|
||||
<option value="double_circle">double_circle</option>
|
||||
<option value="point">point</option>
|
||||
<option value="off">off</option>
|
||||
<option value="on">on</option>
|
||||
<option value="blink">blink</option>
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
from machine import Pin
|
||||
from neopixel import NeoPixel
|
||||
import time
|
||||
import json
|
||||
import os
|
||||
|
||||
BENCHMARK_FILE = "/benchmark.json"
|
||||
PIXEL_FILE = "/pixels.bin"
|
||||
|
||||
NUM_STRIPS = 8
|
||||
LEDS_PER_STRIP = 291
|
||||
BYTES_PER_PIXEL = 3
|
||||
PIXEL_BYTES = NUM_STRIPS * LEDS_PER_STRIP * BYTES_PER_PIXEL
|
||||
|
||||
|
||||
def load_pixels(strips):
|
||||
"""Load pixel buffer from flash into strips. Returns load time ms or None if no file."""
|
||||
try:
|
||||
start = time.ticks_ms()
|
||||
with open(PIXEL_FILE, "rb") as f:
|
||||
buf = f.read()
|
||||
if len(buf) != PIXEL_BYTES:
|
||||
return None
|
||||
ofs = 0
|
||||
for strip in strips:
|
||||
for i in range(LEDS_PER_STRIP):
|
||||
strip[i] = (buf[ofs], buf[ofs + 1], buf[ofs + 2])
|
||||
ofs += BYTES_PER_PIXEL
|
||||
return time.ticks_diff(time.ticks_ms(), start)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def save_pixels(strips):
|
||||
"""Write current strip pixel data to flash."""
|
||||
buf = bytearray(PIXEL_BYTES)
|
||||
ofs = 0
|
||||
for strip in strips:
|
||||
for i in range(LEDS_PER_STRIP):
|
||||
r, g, b = strip[i]
|
||||
buf[ofs] = r
|
||||
buf[ofs + 1] = g
|
||||
buf[ofs + 2] = b
|
||||
ofs += BYTES_PER_PIXEL
|
||||
with open(PIXEL_FILE, "wb") as f:
|
||||
f.write(buf)
|
||||
print(f"Saved {PIXEL_BYTES} bytes to {PIXEL_FILE}")
|
||||
|
||||
|
||||
def flash_stats(path="/"):
|
||||
"""Return (total_bytes, free_bytes, used_bytes) for the filesystem on flash, or None."""
|
||||
try:
|
||||
s = os.statvfs(path)
|
||||
# f_frsize = fragment size, f_blocks = total blocks, f_bfree = free blocks
|
||||
total = s[1] * s[2] # frsize * blocks
|
||||
free = s[1] * s[3] # frsize * bfree
|
||||
used = total - free
|
||||
return (total, free, used)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def print_flash():
|
||||
st = flash_stats()
|
||||
if st is None:
|
||||
print("Flash: (statvfs not available)")
|
||||
return
|
||||
total, free, used = st
|
||||
total_k = total // 1024
|
||||
free_k = free // 1024
|
||||
used_k = used // 1024
|
||||
print(f"Flash: {used_k} KB used, {free_k} KB free, {total_k} KB total")
|
||||
|
||||
|
||||
def load_benchmark():
|
||||
try:
|
||||
with open(BENCHMARK_FILE) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def save_benchmark(fill_ms, show_ms):
|
||||
try:
|
||||
with open(BENCHMARK_FILE, "w") as f:
|
||||
json.dump({"fill_ms": fill_ms, "show_ms": show_ms}, f)
|
||||
print(f"Saved to {BENCHMARK_FILE}")
|
||||
except OSError as e:
|
||||
print(f"Save failed: {e}")
|
||||
|
||||
|
||||
# set cpu frequency to 240MHz
|
||||
import machine
|
||||
machine.freq(240000000)
|
||||
|
||||
strips = [NeoPixel(Pin(i), 291) for i in range(8)]
|
||||
|
||||
print_flash()
|
||||
|
||||
# load and print previous run
|
||||
prev = load_benchmark()
|
||||
if prev:
|
||||
print(f"Previous: fill {prev['fill_ms']} ms, show {prev['show_ms']} ms")
|
||||
else:
|
||||
print("No previous benchmark stored")
|
||||
|
||||
# optional: time load from flash + show (if we have stored pixels)
|
||||
load_ms = load_pixels(strips)
|
||||
if load_ms is not None:
|
||||
print(f"Load pixels from flash: {load_ms} ms")
|
||||
start = time.ticks_ms()
|
||||
for strip in strips:
|
||||
strip.write()
|
||||
show_ms_loaded = time.ticks_diff(time.ticks_ms(), start)
|
||||
print(f"Show after load: {show_ms_loaded} ms")
|
||||
|
||||
print("Filling strips")
|
||||
start = time.ticks_ms()
|
||||
for i in range(1):
|
||||
for strip in strips:
|
||||
strip.fill((255, 0, 0))
|
||||
end = time.ticks_ms()
|
||||
fill_ms = time.ticks_diff(end, start)
|
||||
print(f"fill time: {fill_ms} ms")
|
||||
|
||||
print("Showing strips")
|
||||
start = time.ticks_ms()
|
||||
for strip in strips:
|
||||
strip.write()
|
||||
end = time.ticks_ms()
|
||||
show_ms = time.ticks_diff(end, start)
|
||||
print(f"show time: {show_ms} ms")
|
||||
|
||||
save_pixels(strips)
|
||||
save_benchmark(fill_ms, show_ms)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
ESP32-C6 test: send JSON messages to Pico over UART (GPIO17).
|
||||
Settings use strips = [[pin, num_leds], ...]. Run with Pico connected on RX.
|
||||
|
||||
Run with mpremote (from repo root):
|
||||
./esp32/run_test_uart_json.sh
|
||||
# or
|
||||
mpremote run esp32/test/test_uart_send_json.py
|
||||
# or with port
|
||||
mpremote connect /dev/ttyUSB0 run esp32/test/test_uart_send_json.py
|
||||
"""
|
||||
import machine
|
||||
import time
|
||||
import json
|
||||
|
||||
UART_TX_PIN = 17
|
||||
UART_BAUD = 921600
|
||||
LED_PIN = 15
|
||||
|
||||
|
||||
def send_json(uart, obj):
|
||||
line = json.dumps(obj) + "\n"
|
||||
uart.write(line)
|
||||
print("TX:", line.strip())
|
||||
|
||||
|
||||
def main():
|
||||
uart = machine.UART(1, baudrate=UART_BAUD, tx=UART_TX_PIN)
|
||||
led = machine.Pin(LED_PIN, machine.Pin.OUT)
|
||||
|
||||
# 1) Settings: one strip, pin 2, 10 LEDs (list of lists)
|
||||
send_json(uart, {
|
||||
"v": 1,
|
||||
"settings": {
|
||||
"strips": [[2, 10]],
|
||||
"brightness": 30,
|
||||
},
|
||||
})
|
||||
led.value(1)
|
||||
time.sleep(0.2)
|
||||
led.value(0)
|
||||
time.sleep(0.3)
|
||||
|
||||
# 2) led-controller format: light + settings.color (hex)
|
||||
send_json(uart, {"light": "strip1", "settings": {"color": "#FF0000"}, "save": False})
|
||||
time.sleep(0.5)
|
||||
|
||||
# 3) led-controller format: light + settings.r,g,b
|
||||
send_json(uart, {"light": "strip1", "settings": {"r": 0, "g": 255, "b": 0}, "save": False})
|
||||
time.sleep(0.5)
|
||||
|
||||
# 4) led-controller format: blue (hex)
|
||||
send_json(uart, {"light": "strip1", "settings": {"color": "#0000FF"}, "save": False})
|
||||
time.sleep(0.5)
|
||||
|
||||
# 5) Off (existing format)
|
||||
send_json(uart, {"v": 1, "off": True})
|
||||
time.sleep(0.3)
|
||||
|
||||
print("Done. Pico: settings -> red (hex) -> green (r,g,b) -> blue (hex) -> off.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
ESP32-C6 UART TX + LED test. Sends a few commands on GPIO17, blinks LED on GPIO15.
|
||||
Run on device: exec(open('test/test_uart_tx').read()) or import test.test_uart_tx
|
||||
Does not require Pico connected.
|
||||
"""
|
||||
import machine
|
||||
import time
|
||||
|
||||
UART_TX_PIN = 17
|
||||
LED_PIN = 15
|
||||
|
||||
def main():
|
||||
uart = machine.UART(1, baudrate=115200, tx=UART_TX_PIN)
|
||||
led = machine.Pin(LED_PIN, machine.Pin.OUT)
|
||||
|
||||
def send(cmd):
|
||||
uart.write(cmd + "\n")
|
||||
print("TX:", cmd)
|
||||
|
||||
# Blink and send a short command sequence
|
||||
commands = ["off", "fill 255 0 0", "fill 0 255 0", "fill 0 0 255", "off"]
|
||||
for i, cmd in enumerate(commands):
|
||||
led.value(1)
|
||||
send(cmd)
|
||||
time.sleep(0.3)
|
||||
led.value(0)
|
||||
time.sleep(0.2)
|
||||
|
||||
print("Done. Connect Pico to see strip follow commands.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+20
-3
@@ -93,8 +93,22 @@ class PIO_DMA_Transfer():
|
||||
self.dma_chan.CTRL_TRIG.INCR_WRITE = 0
|
||||
self.dma_chan.CTRL_TRIG.INCR_READ = 1
|
||||
|
||||
def _set_read_addr(self, buffer_or_address, offset=0):
|
||||
if isinstance(buffer_or_address, int):
|
||||
self.dma_chan.READ_ADDR_REG = buffer_or_address + offset
|
||||
else:
|
||||
self.dma_chan.READ_ADDR_REG = uctypes.addressof(buffer_or_address) + offset
|
||||
|
||||
def prepare_transfer(self, buffer_or_address, offset=0):
|
||||
"""Set read address only; do not start. Use with trigger() for parallel start."""
|
||||
self._set_read_addr(buffer_or_address, offset)
|
||||
|
||||
def start_transfer(self, buffer, offset=0):
|
||||
self.dma_chan.READ_ADDR_REG = uctypes.addressof(buffer) + offset
|
||||
self._set_read_addr(buffer, offset)
|
||||
self.dma_chan.CTRL_TRIG.EN = 1
|
||||
|
||||
def trigger(self):
|
||||
"""Start this channel (use after prepare_transfer for parallel start)."""
|
||||
self.dma_chan.CTRL_TRIG.EN = 1
|
||||
|
||||
def transfer_count(self):
|
||||
@@ -105,9 +119,12 @@ class PIO_DMA_Transfer():
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
def trigger_channels(dma_transfers):
|
||||
"""Start multiple DMA channels in quick succession (parallel drive)."""
|
||||
for t in dma_transfers:
|
||||
t.trigger()
|
||||
|
||||
|
||||
|
||||
|
||||
+10
-1
@@ -28,13 +28,22 @@ class WS2812B:
|
||||
self.brightness = brightness
|
||||
self.invert = invert
|
||||
self.pio_dma = dma.PIO_DMA_Transfer(state_machine+4, state_machine, 8, num_leds*3)
|
||||
self.dma.start_transfer(self.ar)
|
||||
|
||||
|
||||
def show(self, array=None, offset=0):
|
||||
if array is None:
|
||||
array = self.ar
|
||||
self.pio_dma.start_transfer(array, offset)
|
||||
|
||||
def prepare_show(self, buffer_or_address, offset=0):
|
||||
"""Set DMA read address only (buffer or int flash address). Use with trigger() for parallel start."""
|
||||
if buffer_or_address is None:
|
||||
buffer_or_address = self.ar
|
||||
self.pio_dma.prepare_transfer(buffer_or_address, offset)
|
||||
|
||||
def trigger(self):
|
||||
"""Start DMA for this strip (use after prepare_show on all strips for parallel drive)."""
|
||||
self.pio_dma.trigger()
|
||||
|
||||
def set(self, i, color):
|
||||
self.ar[i*3] = int(color[1]*self.brightness)
|
||||
|
||||
@@ -4,7 +4,6 @@ from .pulse import Pulse
|
||||
from .transition import Transition
|
||||
from .chase import Chase
|
||||
from .circle import Circle
|
||||
from .double_circle import DoubleCircle
|
||||
from .roll import Roll
|
||||
from .calibration import Calibration
|
||||
from .test import Test
|
||||
@@ -15,5 +14,4 @@ from .lift import Lift
|
||||
from .flare import Flare
|
||||
from .hook import Hook
|
||||
from .pose import Pose
|
||||
from .segments import Segments
|
||||
from .segments_transition import SegmentsTransition
|
||||
from .point import Point
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Calibration: strips 2 and 6 only. First 10 green, then alternating 10 blue / 10 red. 10% brightness."""
|
||||
|
||||
BRIGHTNESS = 1
|
||||
BRIGHTNESS = 0.10
|
||||
BLOCK = 10
|
||||
STRIPS_ON = (2, 6) # 0-based: 3rd and 7th strip only
|
||||
|
||||
@@ -22,7 +22,6 @@ class Calibration:
|
||||
green = _scale(GREEN, BRIGHTNESS)
|
||||
red = _scale(RED, BRIGHTNESS)
|
||||
blue = _scale(BLUE, BRIGHTNESS)
|
||||
blue = (0,0,0)
|
||||
on_set = set(STRIPS_ON)
|
||||
for strip_idx, strip in enumerate(strips):
|
||||
n = strip.num_leds
|
||||
|
||||
+86
-128
@@ -1,165 +1,123 @@
|
||||
import utime
|
||||
|
||||
|
||||
def _make_chase_double(num_leds, cumulative_leds, total_ring_leds, color0, color1, n1, n2):
|
||||
"""Pregenerate strip double buffer with repeating segments:
|
||||
color0 for n1 pixels, then color1 for n2 pixels, around the full ring. GRB order."""
|
||||
n = 2 * num_leds
|
||||
buf = bytearray(n * 3)
|
||||
pattern_len = n1 + n2
|
||||
for b in range(n):
|
||||
# Position of this pixel along the logical ring
|
||||
pos = (2 * cumulative_leds - b) % total_ring_leds
|
||||
seg_pos = pos % pattern_len
|
||||
if seg_pos < n1:
|
||||
r, g, b_ = color0
|
||||
else:
|
||||
r, g, b_ = color1
|
||||
o = b * 3
|
||||
buf[o] = g
|
||||
buf[o + 1] = r
|
||||
buf[o + 2] = b_
|
||||
strip_len_bytes = num_leds * 3
|
||||
return buf, strip_len_bytes
|
||||
|
||||
|
||||
def _ensure_chase_buffers(driver, color0, color1, n1, n2, cache):
|
||||
"""Build or refresh per-strip double buffers for the chase pattern."""
|
||||
strips = driver.strips
|
||||
key = (
|
||||
color0,
|
||||
color1,
|
||||
int(n1),
|
||||
int(n2),
|
||||
tuple(s.num_leds for s in strips),
|
||||
)
|
||||
if cache.get("key") == key and cache.get("data") is not None:
|
||||
return cache["data"], cache["cumulative_leds"], cache["total_ring_leds"]
|
||||
|
||||
if not strips:
|
||||
cache["key"] = key
|
||||
cache["data"] = []
|
||||
cache["cumulative_leds"] = []
|
||||
cache["total_ring_leds"] = 0
|
||||
return cache["data"], cache["cumulative_leds"], cache["total_ring_leds"]
|
||||
|
||||
cumulative_leds = [0]
|
||||
for s in strips[:-1]:
|
||||
cumulative_leds.append(cumulative_leds[-1] + s.num_leds)
|
||||
total_ring_leds = cumulative_leds[-1] + strips[-1].num_leds
|
||||
|
||||
chase_data = []
|
||||
for idx, s in enumerate(strips):
|
||||
buf, strip_len_bytes = _make_chase_double(
|
||||
s.num_leds,
|
||||
cumulative_leds[idx],
|
||||
total_ring_leds,
|
||||
color0,
|
||||
color1,
|
||||
n1,
|
||||
n2,
|
||||
)
|
||||
chase_data.append((buf, strip_len_bytes))
|
||||
|
||||
cache["key"] = key
|
||||
cache["data"] = chase_data
|
||||
cache["cumulative_leds"] = cumulative_leds
|
||||
cache["total_ring_leds"] = total_ring_leds
|
||||
return chase_data, cumulative_leds, total_ring_leds
|
||||
|
||||
|
||||
class Chase:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
self._buffers_cache = {}
|
||||
|
||||
def run(self, preset):
|
||||
"""Chase pattern: n1 LEDs of color0, n2 LEDs of color1, repeating around the full ring.
|
||||
Moves by n3 on even steps, n4 on odd steps (n3/n4 can be positive or negative)."""
|
||||
colors = preset.c or []
|
||||
if not colors:
|
||||
"""Chase pattern: n1 LEDs of color0, n2 LEDs of color1, repeating.
|
||||
Moves by n3 on even steps, n4 on odd steps (n3/n4 can be positive or negative)"""
|
||||
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:
|
||||
base0 = colors[0]
|
||||
base1 = colors[0]
|
||||
color0 = colors[0]
|
||||
color1 = colors[0]
|
||||
else:
|
||||
base0 = colors[0]
|
||||
base1 = colors[1]
|
||||
color0 = colors[0]
|
||||
color1 = colors[1]
|
||||
|
||||
# Apply preset/global brightness
|
||||
color0 = self.driver.apply_brightness(base0, preset.b)
|
||||
color1 = self.driver.apply_brightness(base1, preset.b)
|
||||
color0 = self.driver.apply_brightness(color0, preset.b)
|
||||
color1 = self.driver.apply_brightness(color1, preset.b)
|
||||
|
||||
n1 = max(1, int(getattr(preset, "n1", 1)) or 1) # LEDs of color 0
|
||||
n2 = max(1, int(getattr(preset, "n2", 1)) or 1) # LEDs of color 1
|
||||
n3 = int(getattr(preset, "n3", 0) or 0) # step on even steps
|
||||
n4 = int(getattr(preset, "n4", 0) or 0) # step on odd steps
|
||||
n1 = max(1, int(preset.n1)) # LEDs of color 0
|
||||
n2 = max(1, int(preset.n2)) # LEDs of color 1
|
||||
n3 = int(preset.n3) # Step movement on even steps (can be negative)
|
||||
n4 = int(preset.n4) # Step movement on odd steps (can be negative)
|
||||
|
||||
if n3 == 0 and n4 == 0:
|
||||
# Nothing to move; default to simple forward motion
|
||||
n3 = 1
|
||||
n4 = 1
|
||||
segment_length = n1 + n2
|
||||
|
||||
chase_data, cumulative_leds, total_ring_leds = _ensure_chase_buffers(
|
||||
self.driver, color0, color1, n1, n2, self._buffers_cache
|
||||
)
|
||||
# Calculate position from step_count
|
||||
step_count = self.driver.step
|
||||
# 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)
|
||||
|
||||
strips = self.driver.strips
|
||||
# Wrap position to keep it reasonable
|
||||
max_pos = self.driver.num_leds + segment_length
|
||||
position = position % max_pos
|
||||
if position < 0:
|
||||
position += max_pos
|
||||
|
||||
def show_frame(chase_pos):
|
||||
for i, (strip, (buf, strip_len_bytes)) in enumerate(zip(strips, chase_data)):
|
||||
# head in [0, strip_len_bytes) so DMA read head..head+strip_len_bytes stays in double buffer
|
||||
head = ((chase_pos + cumulative_leds[i]) * 3) % strip_len_bytes
|
||||
strip.show(buf, head)
|
||||
|
||||
# Helper to compute head position from current step_count
|
||||
def head_from_step(step_count):
|
||||
if step_count % 2 == 0:
|
||||
# Even steps: (step_count//2) pairs of (n3+n4) plus one extra n3
|
||||
pos = (step_count // 2) * (n3 + n4) + n3
|
||||
else:
|
||||
# Odd steps: ((step_count+1)//2) pairs of (n3+n4)
|
||||
pos = ((step_count + 1) // 2) * (n3 + n4)
|
||||
if total_ring_leds <= 0:
|
||||
return 0
|
||||
pos %= total_ring_leds
|
||||
if pos < 0:
|
||||
pos += total_ring_leds
|
||||
return pos
|
||||
|
||||
# Single-step mode: render one frame, then stop
|
||||
# If auto is False, run a single step and then stop
|
||||
if not preset.a:
|
||||
step_count = int(self.driver.step)
|
||||
chase_pos = head_from_step(step_count)
|
||||
# Clear all LEDs
|
||||
self.driver.n.fill((0, 0, 0))
|
||||
|
||||
show_frame(chase_pos)
|
||||
# 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
|
||||
|
||||
# Advance step for next trigger
|
||||
# Determine which color based on position in segment
|
||||
if relative_pos < n1:
|
||||
self.driver.n[i] = color0
|
||||
else:
|
||||
self.driver.n[i] = color1
|
||||
|
||||
self.driver.n.write()
|
||||
|
||||
# Increment step for next beat
|
||||
self.driver.step = step_count + 1
|
||||
|
||||
# Allow tick() to advance the generator once
|
||||
yield
|
||||
return
|
||||
|
||||
# Auto mode: continuous loop driven by delay d
|
||||
transition_duration = max(10, int(getattr(preset, "d", 50)) or 10)
|
||||
# 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:
|
||||
# Rebuild buffers if geometry/colors changed
|
||||
chase_data, cumulative_leds, total_ring_leds = _ensure_chase_buffers(
|
||||
self.driver, color0, color1, n1, n2, self._buffers_cache
|
||||
)
|
||||
# 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)
|
||||
|
||||
step_count = int(self.driver.step)
|
||||
chase_pos = head_from_step(step_count)
|
||||
# Wrap position
|
||||
max_pos = self.driver.num_leds + segment_length
|
||||
position = position % max_pos
|
||||
if position < 0:
|
||||
position += max_pos
|
||||
|
||||
show_frame(chase_pos)
|
||||
# Clear all LEDs
|
||||
self.driver.n.fill((0, 0, 0))
|
||||
|
||||
# Advance step for next frame
|
||||
self.driver.step = step_count + 1
|
||||
# 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[i] = color0
|
||||
else:
|
||||
self.driver.n[i] = color1
|
||||
|
||||
self.driver.n.write()
|
||||
|
||||
# Increment step
|
||||
step_count += 1
|
||||
self.driver.step = step_count
|
||||
last_update = current_time
|
||||
|
||||
# Yield once per tick so other logic can run
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
class DoubleCircle:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
"""
|
||||
DoubleCircle: symmetric band around a center index on the logical ring.
|
||||
|
||||
- n1: center index on the logical ring (0-based, on reference strip 0)
|
||||
- n2: radius of the band (max distance from center)
|
||||
- n3: direction mode
|
||||
0 → LEDs start ALL OFF and turn ON n4 LEDs at a time outward from n1 toward n1±n2
|
||||
1 → LEDs start ALL ON within radius n2 and turn OFF n4 LEDs at a time inward toward n1
|
||||
- n4: step size in LEDs per update
|
||||
- c[0]: base color used for the band
|
||||
"""
|
||||
num_leds = self.driver.num_leds
|
||||
if num_leds <= 0:
|
||||
while True:
|
||||
yield
|
||||
|
||||
colors = preset.c or []
|
||||
base1 = colors[0] if len(colors) >= 1 else (255, 255, 255)
|
||||
off = (0, 0, 0)
|
||||
|
||||
# Apply preset/global brightness
|
||||
color_on = self.driver.apply_brightness(base1, preset.b)
|
||||
color_off = off
|
||||
|
||||
# Center index and radius from preset; clamp center to ring length
|
||||
center = int(getattr(preset, "n1", 0)) % num_leds
|
||||
radius = max(1, int(getattr(preset, "n2", 0)) or 1)
|
||||
mode = int(getattr(preset, "n3", 0) or 0) # 0 = grow band outward, 1 = shrink band inward
|
||||
step_size = max(1, int(getattr(preset, "n4", 1)) or 1)
|
||||
|
||||
num_strips = len(self.driver.strips)
|
||||
|
||||
# Current "front" of the band, as a distance from center
|
||||
# mode 0: grow band outward (0 → radius)
|
||||
# mode 1: shrink band inward (radius → 0)
|
||||
if mode == 0:
|
||||
current = 0
|
||||
else:
|
||||
current = radius
|
||||
|
||||
while True:
|
||||
# Draw current frame based on current radius
|
||||
for i in range(num_leds):
|
||||
# Shortest circular distance from i to center
|
||||
forward = (i - center) % num_leds
|
||||
backward = (center - i) % num_leds
|
||||
dist = forward if forward < backward else backward
|
||||
|
||||
if dist > radius:
|
||||
c = color_off
|
||||
else:
|
||||
if mode == 0:
|
||||
# Grow outward: lit if within current radius
|
||||
c = color_on if dist <= current else color_off
|
||||
else:
|
||||
# Shrink inward: lit if within current radius (band contracts toward center)
|
||||
c = color_on if dist <= current else color_off
|
||||
|
||||
for strip_idx in range(num_strips):
|
||||
self.driver.set(strip_idx, i, c)
|
||||
|
||||
self.driver.show_all()
|
||||
|
||||
# Update current radius for next frame
|
||||
if mode == 0:
|
||||
if current >= radius:
|
||||
# Finished growing; hold final frame
|
||||
while True:
|
||||
yield
|
||||
current = min(radius, current + step_size)
|
||||
else:
|
||||
if current <= 0:
|
||||
# Finished shrinking; hold final frame
|
||||
while True:
|
||||
yield
|
||||
current = max(0, current - step_size)
|
||||
|
||||
yield
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
class Point:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
# Apply preset/global brightness once per color
|
||||
c1 = self.driver.apply_brightness(preset.c[0], preset.b)
|
||||
c2 = self.driver.apply_brightness(preset.c[1], preset.b)
|
||||
c3 = self.driver.apply_brightness(preset.c[2], preset.b)
|
||||
c4 = self.driver.apply_brightness(preset.c[3], preset.b)
|
||||
|
||||
# Helper to normalize and clamp a range
|
||||
self.driver.fill_n(c1, preset.n1, preset.n2)
|
||||
self.driver.fill_n(c2, preset.n3, preset.n4)
|
||||
self.driver.fill_n(c3, preset.n5, preset.n6)
|
||||
self.driver.fill_n(c4, preset.n7, preset.n8)
|
||||
self.driver.show_all()
|
||||
|
||||
+110
-67
@@ -1,5 +1,4 @@
|
||||
import utime
|
||||
import math
|
||||
|
||||
|
||||
class Roll:
|
||||
@@ -7,105 +6,149 @@ class Roll:
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
"""Roll: all strips show a shared color gradient palette, cycling out of phase.
|
||||
"""Roll: moving band with gradient from color1 to color2 over the strips.
|
||||
|
||||
- All strips participate; each frame shows N discrete colors
|
||||
(one per strip), from color1 to color2.
|
||||
- Over time, each strip cycles through all colors, out of phase with the
|
||||
others, creating a smooth rolling band around the hoop.
|
||||
- n1: offset from start of strip (effective start = start + n1)
|
||||
- n2: offset from end of strip (effective end = end - n2, inclusive)
|
||||
- n3: number of full rotations before stopping (0 = infinite)
|
||||
- n4: direction (0 = clockwise, 1 = anti-clockwise)
|
||||
- c[0]: head color (full intensity)
|
||||
- c[1]: tail color (usually darker or off)
|
||||
- c[0]: color1 at the head strip
|
||||
- c[1]: color2 at the tail strip
|
||||
"""
|
||||
colors = preset.c
|
||||
base1 = colors[0] if colors else (255, 255, 255)
|
||||
base2 = colors[1] if len(colors) > 1 else (0, 0, 0)
|
||||
color1 = self.driver.apply_brightness(base1, preset.b)
|
||||
color2 = self.driver.apply_brightness(base2, preset.b)
|
||||
color1_raw = colors[0] if colors else (255, 255, 255)
|
||||
color2_raw = colors[1] if len(colors) > 1 else (0, 0, 0)
|
||||
color1 = self.driver.apply_brightness(color1_raw, preset.b)
|
||||
color2 = self.driver.apply_brightness(color2_raw, preset.b)
|
||||
|
||||
n_segments = self.driver.n.num_strips if hasattr(self.driver.n, "num_strips") else 1
|
||||
# n3: number of full rotations before stopping (0 = continuous)
|
||||
max_rotations = int(getattr(preset, "n3", 0) or 0)
|
||||
# Margins from the start and end of each strip
|
||||
start_margin = max(0, int(getattr(preset, "n1", 0)))
|
||||
end_margin = max(0, int(getattr(preset, "n2", 0)))
|
||||
|
||||
# Debug info to see why roll might be black
|
||||
try:
|
||||
print(
|
||||
"ROLL preset",
|
||||
"p=", getattr(preset, "p", None),
|
||||
"b=", getattr(preset, "b", None),
|
||||
"colors_raw=", color1_raw, color2_raw,
|
||||
"colors_bright=", color1, color2,
|
||||
)
|
||||
print(
|
||||
"ROLL n1..n4",
|
||||
getattr(preset, "n1", None),
|
||||
getattr(preset, "n2", None),
|
||||
getattr(preset, "n3", None),
|
||||
getattr(preset, "n4", None),
|
||||
"n_segments=", n_segments,
|
||||
"start_margin=", start_margin,
|
||||
"end_margin=", end_margin,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# n3: number of rotations (0 = infinite)
|
||||
max_rotations = int(getattr(preset, "n3", 0)) or 0
|
||||
# n4: direction (0=cw, 1=ccw); default clockwise if missing
|
||||
clockwise = int(getattr(preset, "n4", 0)) == 0
|
||||
|
||||
step = self.driver.step
|
||||
delay_ms = max(1, int(preset.d) or 1)
|
||||
last_update = utime.ticks_ms()
|
||||
rotations_done = 0
|
||||
|
||||
# Precompute one shared buffer per brightness level (one per strip),
|
||||
# using the longest strip length so any strip can DMA from it safely.
|
||||
strips_list = self.driver.strips
|
||||
if not strips_list or n_segments <= 0:
|
||||
while True:
|
||||
yield
|
||||
def scale_color(c, f):
|
||||
return tuple(int(x * f) for x in c)
|
||||
|
||||
max_leds = max(s.num_leds for s in strips_list)
|
||||
def lerp_color(c1, c2, t):
|
||||
"""Linear gradient between two colors."""
|
||||
if t <= 0:
|
||||
return c1
|
||||
if t >= 1:
|
||||
return c2
|
||||
return (
|
||||
int(c1[0] + (c2[0] - c1[0]) * t),
|
||||
int(c1[1] + (c2[1] - c1[1]) * t),
|
||||
int(c1[2] + (c2[2] - c1[2]) * t),
|
||||
)
|
||||
|
||||
# Build N discrete color buffers forming a gradient from color1 to color2.
|
||||
buffers = []
|
||||
for j in range(n_segments):
|
||||
if n_segments > 1:
|
||||
t = j / (n_segments - 1)
|
||||
else:
|
||||
t = 0.0
|
||||
# Linear interpolation between color1 and color2
|
||||
r = int(color1[0] + (color2[0] - color1[0]) * t)
|
||||
g = int(color1[1] + (color2[1] - color1[1]) * t)
|
||||
b = int(color1[2] + (color2[2] - color1[2]) * t)
|
||||
|
||||
buf = bytearray(max_leds * 3)
|
||||
for i in range(max_leds):
|
||||
o = i * 3
|
||||
buf[o] = g & 0xFF
|
||||
buf[o + 1] = r & 0xFF
|
||||
buf[o + 2] = b & 0xFF
|
||||
buffers.append(buf)
|
||||
|
||||
def draw(step_index):
|
||||
# Each strip picks a buffer index offset by its strip index so that:
|
||||
# - all brightness levels are visible simultaneously (one per strip)
|
||||
# - over time, each strip cycles through all brightness levels
|
||||
def draw(head):
|
||||
# Remember head strip for flare
|
||||
try:
|
||||
self.driver.last_roll_head = step_index % n_segments
|
||||
self.driver.last_roll_head = head
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
strips_list = self.driver.strips
|
||||
|
||||
for strip_idx, strip in enumerate(strips_list):
|
||||
if strip_idx < 0 or strip_idx >= n_segments:
|
||||
continue
|
||||
|
||||
# Distance from head along direction, 0..n_segments-1
|
||||
if clockwise:
|
||||
buf_index = (step_index + strip_idx) % n_segments
|
||||
dist = (head - strip_idx) % n_segments
|
||||
else:
|
||||
buf_index = (step_index - strip_idx) % n_segments
|
||||
buf = buffers[buf_index]
|
||||
dist = (strip_idx - head) % n_segments
|
||||
|
||||
# Show the shared buffer; WS2812B will read num_leds*3 bytes.
|
||||
strip.show(buf, 0)
|
||||
# Color gradient from color1 at the head strip to color2 at the tail strip
|
||||
if n_segments > 1:
|
||||
t = dist / (n_segments - 1)
|
||||
else:
|
||||
t = 0.0
|
||||
c_strip = lerp_color(color1, color2, t)
|
||||
|
||||
n = strip.num_leds
|
||||
# Effective segment per strip:
|
||||
# start = 0 + start_margin
|
||||
# end = (n - 1) - end_margin (inclusive)
|
||||
width = n - start_margin - end_margin
|
||||
if width <= 0:
|
||||
# If margins are too large, fall back to full strip
|
||||
seg_s = 0
|
||||
seg_e = n
|
||||
else:
|
||||
seg_s = max(0, min(n, start_margin))
|
||||
seg_e = min(n, n - end_margin)
|
||||
|
||||
# Debug for first strip/head to see segment
|
||||
try:
|
||||
if strip_idx == 0 and head == 0:
|
||||
print("ROLL seg strip0 n=", n, "seg_s=", seg_s, "seg_e=", seg_e)
|
||||
except Exception:
|
||||
pass
|
||||
for i in range(n):
|
||||
if seg_s <= i < seg_e:
|
||||
strip.set(i, c_strip)
|
||||
else:
|
||||
strip.set(i, (0, 0, 0))
|
||||
strip.show()
|
||||
|
||||
if not preset.a:
|
||||
draw(step)
|
||||
head = step % n_segments if n_segments > 0 else 0
|
||||
draw(head)
|
||||
self.driver.step = step + 1
|
||||
yield
|
||||
return
|
||||
|
||||
# Auto mode: advance based on preset.d (ms) for smooth, controllable speed
|
||||
delay_ms = max(10, int(getattr(preset, "d", 60)) or 10)
|
||||
last_update = utime.ticks_ms() - delay_ms
|
||||
rotations_done = 0
|
||||
|
||||
while True:
|
||||
now = utime.ticks_ms()
|
||||
if utime.ticks_diff(now, last_update) >= delay_ms:
|
||||
draw(step)
|
||||
current_time = utime.ticks_ms()
|
||||
if utime.ticks_diff(current_time, last_update) >= delay_ms:
|
||||
head = step % n_segments if n_segments > 0 else 0
|
||||
if not clockwise and n_segments > 0:
|
||||
head = (n_segments - 1 - head)
|
||||
|
||||
draw(head)
|
||||
step += 1
|
||||
self.driver.step = step
|
||||
last_update = now
|
||||
# Count full rotations if requested: one rotation per n_segments steps
|
||||
|
||||
if max_rotations > 0 and n_segments > 0 and (step % n_segments) == 0:
|
||||
rotations_done += 1
|
||||
if rotations_done >= max_rotations:
|
||||
# Hold the final frame and stop advancing; keep yielding so
|
||||
# the generator stays alive without changing the LEDs.
|
||||
while True:
|
||||
yield
|
||||
self.driver.step = step
|
||||
last_update = current_time
|
||||
return
|
||||
|
||||
self.driver.step = step
|
||||
last_update = current_time
|
||||
yield
|
||||
@@ -1,18 +0,0 @@
|
||||
class Segments:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
# Apply preset/global brightness once per color
|
||||
ranges = [
|
||||
(preset.n1, preset.n2),
|
||||
(preset.n3, preset.n4),
|
||||
(preset.n5, preset.n6),
|
||||
(preset.n7, preset.n8),
|
||||
]
|
||||
|
||||
for n, color in enumerate(preset.c):
|
||||
self.driver.fill_n(color, ranges[n][0], ranges[n][1])
|
||||
|
||||
self.driver.show_all()
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
import utime
|
||||
|
||||
|
||||
class SegmentsTransition:
|
||||
def __init__(self, driver):
|
||||
self.driver = driver
|
||||
|
||||
def run(self, preset):
|
||||
"""
|
||||
SegmentsTransition: fade from whatever is currently on the strips
|
||||
to a new static Segments layout defined by n1–n8 and c[0..3].
|
||||
|
||||
- Uses the existing strip buffers as the starting state.
|
||||
- Target state matches the Segments pattern: up to 4 colored bands
|
||||
along the logical reference strip, mapped to all physical strips.
|
||||
- Transition duration is taken from preset.d (ms), minimum 50ms.
|
||||
"""
|
||||
strips = self.driver.strips
|
||||
if not strips:
|
||||
while True:
|
||||
yield
|
||||
|
||||
# Snapshot starting GRB buffers (already scaled by per-strip brightness)
|
||||
start_bufs = [bytes(strip.ar) for strip in strips]
|
||||
|
||||
# Prepare target buffers (same length as each strip's ar)
|
||||
target_bufs = [bytearray(len(strip.ar)) for strip in strips]
|
||||
|
||||
# Base colors (up to 4), missing ones default to black
|
||||
colors = list(preset.c) if getattr(preset, "c", None) else []
|
||||
while len(colors) < 4:
|
||||
colors.append((0, 0, 0))
|
||||
|
||||
# Apply preset/global brightness once per color
|
||||
bright_colors = [
|
||||
self.driver.apply_brightness(colors[0], preset.b),
|
||||
self.driver.apply_brightness(colors[1], preset.b),
|
||||
self.driver.apply_brightness(colors[2], preset.b),
|
||||
self.driver.apply_brightness(colors[3], preset.b),
|
||||
]
|
||||
|
||||
# Logical reference length for all strips (from scale_map[0])
|
||||
ref_len = len(self.driver.scale_map[0]) if self.driver.scale_map else 0
|
||||
if ref_len <= 0:
|
||||
# Fallback: nothing to do, just hold current state
|
||||
while True:
|
||||
yield
|
||||
|
||||
# Helper to clamp and normalize a logical range [a, b] (inclusive) over ref_len.
|
||||
# Returns (start, end_exclusive) suitable for range(start, end_exclusive).
|
||||
def norm_range(a, b):
|
||||
a = int(a)
|
||||
b = int(b)
|
||||
if a > b:
|
||||
a, b = b, a
|
||||
if b < 0 or a >= ref_len:
|
||||
return None
|
||||
a = max(0, a)
|
||||
b = min(ref_len - 1, b)
|
||||
if a > b:
|
||||
return None
|
||||
return a, b + 1
|
||||
|
||||
raw_ranges = [
|
||||
(getattr(preset, "n1", 0), getattr(preset, "n2", -1), bright_colors[0]),
|
||||
(getattr(preset, "n3", 0), getattr(preset, "n4", -1), bright_colors[1]),
|
||||
(getattr(preset, "n5", 0), getattr(preset, "n6", -1), bright_colors[2]),
|
||||
(getattr(preset, "n7", 0), getattr(preset, "n8", -1), bright_colors[3]),
|
||||
]
|
||||
|
||||
# Build target buffers using the same logical indexing idea as Segments
|
||||
for strip_idx, strip in enumerate(strips):
|
||||
bright = strip.brightness
|
||||
scale_map = self.driver.scale_map[strip_idx]
|
||||
buf = target_bufs[strip_idx]
|
||||
n_leds = strip.num_leds
|
||||
|
||||
# Start from black everywhere
|
||||
for i in range(len(buf)):
|
||||
buf[i] = 0
|
||||
|
||||
# Apply each logical range to this strip
|
||||
for a, b, color in raw_ranges:
|
||||
rng = norm_range(a, b)
|
||||
if not rng:
|
||||
continue
|
||||
start, end = rng
|
||||
r, g, bl = color
|
||||
for logical_idx in range(start, end):
|
||||
if logical_idx < 0 or logical_idx >= len(scale_map):
|
||||
continue
|
||||
phys_idx = scale_map[logical_idx]
|
||||
if phys_idx < 0 or phys_idx >= n_leds:
|
||||
continue
|
||||
base = phys_idx * 3
|
||||
if base + 2 >= len(buf):
|
||||
continue
|
||||
buf[base] = int(g * bright)
|
||||
buf[base + 1] = int(r * bright)
|
||||
buf[base + 2] = int(bl * bright)
|
||||
|
||||
# Duration in ms for the whole transition (slower by default)
|
||||
# If preset.d is provided, use it; otherwise default to a slow 3000ms fade.
|
||||
raw_d = int(getattr(preset, "d", 3000) or 3000)
|
||||
duration = max(1000, raw_d) # enforce at least 1s for a clearly visible transition
|
||||
start_time = utime.ticks_ms()
|
||||
|
||||
while True:
|
||||
now = utime.ticks_ms()
|
||||
elapsed = utime.ticks_diff(now, start_time)
|
||||
|
||||
if elapsed >= duration:
|
||||
# Final frame: commit target buffers and hold, then update all strips together
|
||||
for strip, target in zip(strips, target_bufs):
|
||||
ar = strip.ar
|
||||
for i in range(len(ar)):
|
||||
ar[i] = target[i]
|
||||
self.driver.show_all()
|
||||
while True:
|
||||
yield
|
||||
|
||||
# Interpolation factor in [0,1]
|
||||
factor = elapsed / duration
|
||||
inv = 1.0 - factor
|
||||
|
||||
# Blend from start to target in GRB space per byte
|
||||
for idx, strip in enumerate(strips):
|
||||
start_buf = start_bufs[idx]
|
||||
target_buf = target_bufs[idx]
|
||||
ar = strip.ar
|
||||
for i in range(len(ar)):
|
||||
ar[i] = int(start_buf[i] * inv + target_buf[i] * factor)
|
||||
self.driver.show_all()
|
||||
|
||||
yield
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import utime
|
||||
|
||||
SPAN = 0 # LEDs on each side of center (match Grab)
|
||||
SPAN = 10 # LEDs on each side of center (match Grab)
|
||||
LUT_SIZE = 256 # gradient lookup table entries
|
||||
|
||||
|
||||
@@ -12,9 +12,6 @@ class Spin:
|
||||
|
||||
def run(self, preset):
|
||||
strips = self.driver.strips
|
||||
|
||||
self.driver.fill((0, 0, 0))
|
||||
self.driver.show_all()
|
||||
active_indices = (0, 4)
|
||||
c0 = preset.c[0]
|
||||
c1 = preset.c[1]
|
||||
@@ -61,8 +58,8 @@ class Spin:
|
||||
n = strip.num_leds
|
||||
mid = midpoints[idx]
|
||||
|
||||
# Expand arms at the same rate on both sides
|
||||
step = max(1, rate)
|
||||
# Expand arms: inside (strip 1, idx 0) moves slower, outside (strip 5, idx 4) faster
|
||||
step = max(1, rate // 2) if idx == 0 else rate
|
||||
new_left = max(margin, left[idx] - step)
|
||||
new_right = min(n - margin, right[idx] + step)
|
||||
|
||||
|
||||
File renamed without changes.
+22
-60
@@ -1,58 +1,13 @@
|
||||
from machine import Pin
|
||||
from ws2812 import WS2812B
|
||||
import dma
|
||||
from preset import Preset
|
||||
from patterns import (
|
||||
Blink,
|
||||
Rainbow,
|
||||
Pulse,
|
||||
Transition,
|
||||
Chase,
|
||||
Circle,
|
||||
DoubleCircle,
|
||||
Roll,
|
||||
Calibration,
|
||||
Test,
|
||||
Grab,
|
||||
Spin,
|
||||
Lift,
|
||||
Flare,
|
||||
Hook,
|
||||
Pose,
|
||||
Segments,
|
||||
SegmentsTransition,
|
||||
Blink, Rainbow, Pulse, Transition, Chase, Circle, Roll, Calibration, Test,
|
||||
Grab, Spin, Lift, Flare, Hook, Pose, Point,
|
||||
)
|
||||
import json
|
||||
|
||||
|
||||
class _LogicalRing:
|
||||
"""
|
||||
Lightweight logical ring over all strips.
|
||||
Used by patterns that expect driver.n (e.g. Circle, Roll legacy API).
|
||||
"""
|
||||
|
||||
def __init__(self, driver):
|
||||
self._driver = driver
|
||||
self.num_strips = len(driver.strips)
|
||||
|
||||
def __len__(self):
|
||||
return self._driver.num_leds
|
||||
|
||||
def fill(self, color):
|
||||
# Apply color to all logical positions across all strips
|
||||
for i in range(self._driver.num_leds):
|
||||
for strip_idx in range(self.num_strips):
|
||||
self._driver.set(strip_idx, i, color)
|
||||
|
||||
def __setitem__(self, index, color):
|
||||
if index < 0 or index >= self._driver.num_leds:
|
||||
return
|
||||
for strip_idx in range(self.num_strips):
|
||||
self._driver.set(strip_idx, index, color)
|
||||
|
||||
def write(self):
|
||||
self._driver.show_all()
|
||||
|
||||
|
||||
# Order: strips[0]=physical 1 … strips[7]=physical 8. (pin, num_leds, midpoint_index).
|
||||
STRIP_CONFIG = (
|
||||
(6, 291, 291 // 2), # 1
|
||||
@@ -80,12 +35,8 @@ class Presets:
|
||||
state_machine += 1
|
||||
self.scale_map.append(self.create_scale_map(num_leds))
|
||||
|
||||
# Single logical strip using strip 0 as reference for patterns (n[i], .fill(), .write())
|
||||
# Single logical strip over all 8 strips for patterns (n[i], .fill(), .write())
|
||||
# WS2812B with brightness=1.0 so Presets.apply_brightness() does all scaling (NeoPixel drop-in)
|
||||
# Reference logical length for patterns that use driver.num_leds (Rainbow/Chase/Circle, etc.)
|
||||
self.num_leds = self.strips[0].num_leds if self.strips else 0
|
||||
# Legacy logical ring interface for patterns expecting driver.n
|
||||
self.n = _LogicalRing(self)
|
||||
self.step = 0
|
||||
# Remember which strip was last used as the roll head (for flare, etc.)
|
||||
self.last_roll_head = 0
|
||||
@@ -106,7 +57,6 @@ class Presets:
|
||||
"transition": Transition(self).run,
|
||||
"chase": Chase(self).run,
|
||||
"circle": Circle(self).run,
|
||||
"double_circle": DoubleCircle(self).run,
|
||||
"roll": Roll(self).run,
|
||||
"calibration": Calibration(self).run,
|
||||
"test": Test(self).run,
|
||||
@@ -116,9 +66,7 @@ class Presets:
|
||||
"flare": Flare(self).run,
|
||||
"hook": Hook(self).run,
|
||||
"pose": Pose(self).run,
|
||||
"segments": Segments(self).run,
|
||||
"segments_transition": SegmentsTransition(self).run,
|
||||
"point": Segments(self).run, # backwards-compatible alias
|
||||
"point": Point(self).run,
|
||||
}
|
||||
|
||||
# --- Strip geometry utilities -------------------------------------------------
|
||||
@@ -212,13 +160,11 @@ class Presets:
|
||||
|
||||
def off(self, preset=None):
|
||||
self.fill((0, 0, 0))
|
||||
self.show_all()
|
||||
|
||||
def on(self, preset):
|
||||
colors = preset.c
|
||||
color = colors[0] if colors else (255, 255, 255)
|
||||
self.fill(self.apply_brightness(color, preset.b))
|
||||
self.show_all()
|
||||
|
||||
def fill(self, color):
|
||||
for strip in self.strips:
|
||||
@@ -242,4 +188,20 @@ class Presets:
|
||||
|
||||
def show_all(self):
|
||||
for strip in self.strips:
|
||||
strip.show()
|
||||
strip.show()
|
||||
|
||||
def show_all_parallel(self):
|
||||
"""Drive all 8 strips at once: PIO+DMA, trigger all channels in quick succession."""
|
||||
for strip in self.strips:
|
||||
strip.prepare_show(None, 0) # use strip's own buffer
|
||||
dma.trigger_channels([s.pio_dma for s in self.strips])
|
||||
|
||||
def show_all_parallel_from_flash(self, flash_base_address):
|
||||
"""Drive all 8 strips from flash at once. flash_base_address = start of contiguous pixel data.
|
||||
Layout in flash: strip0 pixels (n0*3 bytes), strip1 (n1*3), ... in order.
|
||||
In MicroPython you can use uctypes.addressof(bytes_obj) if the bytes live in flash (e.g. const)."""
|
||||
offset = 0
|
||||
for strip in self.strips:
|
||||
strip.prepare_show(flash_base_address, offset)
|
||||
offset += strip.num_leds * 3
|
||||
dma.trigger_channels([s.pio_dma for s in self.strips])
|
||||
+18
-19
@@ -33,28 +33,27 @@ for ws in strips[:-1]:
|
||||
cumulative_leds.append(cumulative_leds[-1] + ws.num_leds)
|
||||
total_ring_leds = cumulative_leds[-1] + strips[-1].num_leds
|
||||
|
||||
# Chase: color1 n1 long, then color2 n2 long, stepping n3 pixels
|
||||
COLOR1 = (255, 0, 0) # red
|
||||
COLOR2 = (0, 0, 255) # blue
|
||||
N1 = 24 # length of color1 segment
|
||||
N2 = 24 # length of color2 segment
|
||||
STEP = 1 # step size in pixels per frame
|
||||
# Chase: trail length (0 = single LED), color (R,G,B)
|
||||
TRAIL_LEN = 8
|
||||
CHASE_COLOR = (0, 255, 100) # cyan-green
|
||||
|
||||
|
||||
def make_chase_double(num_leds, cumulative_leds, total_ring_leds, color1, color2, n1, n2):
|
||||
"""Pregenerate strip double buffer with repeating segments:
|
||||
color1 for n1 pixels, then color2 for n2 pixels, around the full ring. GRB order."""
|
||||
def make_chase_double(num_leds, cumulative_leds, total_ring_leds, color, trail_len=0):
|
||||
"""Pregenerate strip double buffer: when head shows index b first, that pixel is at
|
||||
distance (2*cumulative_leds - b) % total_ring_leds from chase head. GRB order."""
|
||||
n = 2 * num_leds
|
||||
buf = bytearray(n * 3)
|
||||
pattern_len = n1 + n2
|
||||
for b in range(n):
|
||||
# Position of this pixel along the logical ring
|
||||
pos = (2 * cumulative_leds - b) % total_ring_leds
|
||||
seg_pos = pos % pattern_len
|
||||
if seg_pos < n1:
|
||||
r, grn, b_ = color1[0], color1[1], color1[2]
|
||||
dist = (2 * cumulative_leds - b) % total_ring_leds
|
||||
if dist == 0:
|
||||
r, grn, b_ = color[0], color[1], color[2]
|
||||
elif trail_len and 0 < dist <= trail_len:
|
||||
fade = 1.0 - (dist / (trail_len + 1))
|
||||
r = int(color[0] * fade)
|
||||
grn = int(color[1] * fade)
|
||||
b_ = int(color[2] * fade)
|
||||
else:
|
||||
r, grn, b_ = color2[0], color2[1], color2[2]
|
||||
r = grn = b_ = 0
|
||||
o = b * 3
|
||||
buf[o] = grn
|
||||
buf[o + 1] = r
|
||||
@@ -64,7 +63,7 @@ def make_chase_double(num_leds, cumulative_leds, total_ring_leds, color1, color2
|
||||
|
||||
# Pregenerate one double buffer per strip
|
||||
chase_buffers = [
|
||||
make_chase_double(ws.num_leds, cumulative_leds[i], total_ring_leds, COLOR1, COLOR2, N1, N2)
|
||||
make_chase_double(ws.num_leds, cumulative_leds[i], total_ring_leds, CHASE_COLOR, TRAIL_LEN)
|
||||
for i, ws in enumerate(strips)
|
||||
]
|
||||
|
||||
@@ -75,5 +74,5 @@ while True:
|
||||
strip_len = strip.num_leds * 3
|
||||
head = (chase_pos + cumulative_leds[i]) * 3 % strip_len
|
||||
strip.show(chase_buffers[i], head)
|
||||
chase_pos = (chase_pos + STEP) % total_ring_leds
|
||||
time.sleep_ms(40)
|
||||
chase_pos = (chase_pos + 1) % total_ring_leds
|
||||
time.sleep_ms(20)
|
||||
@@ -1,114 +0,0 @@
|
||||
"""
|
||||
On-device visual test for the Roll pattern via Presets.
|
||||
|
||||
This exercises src/patterns/roll.py (gradient from color1 to color2 across strips),
|
||||
not the low-level WS2812 driver.
|
||||
|
||||
Usage (from pico/ dir or project root with adjusted paths):
|
||||
|
||||
mpremote connect <device> cp src/*.py :
|
||||
mpremote connect <device> cp src/patterns/*.py :patterns
|
||||
mpremote connect <device> cp lib/*.py :
|
||||
mpremote connect <device> cp test/roll.py :
|
||||
mpremote connect <device> run roll.py
|
||||
"""
|
||||
|
||||
import utime
|
||||
|
||||
from presets import Presets, Preset
|
||||
|
||||
|
||||
def make_roll_preset(name, color1, color2, delay_ms=60, brightness=255, direction=0):
|
||||
"""
|
||||
Helper to build a Preset for the 'roll' pattern.
|
||||
|
||||
- color1: head color (full intensity)
|
||||
- color2: tail color (end of gradient)
|
||||
- direction: 0 = clockwise, 1 = anti-clockwise
|
||||
"""
|
||||
data = {
|
||||
"p": "roll",
|
||||
"c": [color1, color2],
|
||||
"b": brightness,
|
||||
"d": delay_ms,
|
||||
"n4": direction,
|
||||
"a": True, # animated
|
||||
}
|
||||
return name, Preset(data)
|
||||
|
||||
|
||||
def run_for(presets, duration_ms):
|
||||
"""Tick the current pattern for duration_ms."""
|
||||
start = utime.ticks_ms()
|
||||
while utime.ticks_diff(utime.ticks_ms(), start) < duration_ms:
|
||||
presets.tick()
|
||||
utime.sleep_ms(10)
|
||||
|
||||
|
||||
def main():
|
||||
presets = Presets()
|
||||
presets.load()
|
||||
|
||||
num_leds = presets.strip_length(0)
|
||||
if num_leds <= 0:
|
||||
print("No strips; aborting roll test.")
|
||||
return
|
||||
|
||||
print("Starting roll pattern gradient tests via Presets...")
|
||||
|
||||
# A few different roll presets to compare:
|
||||
roll_presets = []
|
||||
|
||||
# 1. White → off, clockwise (50% brightness, faster)
|
||||
roll_presets.append(
|
||||
make_roll_preset(
|
||||
"roll_white_off_cw",
|
||||
color1=(255, 255, 255),
|
||||
color2=(0, 0, 0),
|
||||
delay_ms=120,
|
||||
brightness=128,
|
||||
direction=0,
|
||||
)
|
||||
)
|
||||
|
||||
# 2. Warm white → cool blue, clockwise (50% brightness, faster)
|
||||
roll_presets.append(
|
||||
make_roll_preset(
|
||||
"roll_warm_cool_cw",
|
||||
color1=(255, 200, 100),
|
||||
color2=(0, 0, 255),
|
||||
delay_ms=130,
|
||||
brightness=128,
|
||||
direction=0,
|
||||
)
|
||||
)
|
||||
|
||||
# 3. Red → green, counter-clockwise (50% brightness, faster)
|
||||
roll_presets.append(
|
||||
make_roll_preset(
|
||||
"roll_red_green_ccw",
|
||||
color1=(255, 0, 0),
|
||||
color2=(0, 255, 0),
|
||||
delay_ms=110,
|
||||
brightness=128,
|
||||
direction=1,
|
||||
)
|
||||
)
|
||||
|
||||
# Register presets and run them one after another
|
||||
for name, preset_obj in roll_presets:
|
||||
presets.presets[name] = preset_obj
|
||||
|
||||
for name, _preset in roll_presets:
|
||||
print("Running roll preset:", name)
|
||||
presets.select(name)
|
||||
run_for(presets, duration_ms=8000)
|
||||
|
||||
print("Roll pattern Presets test finished. Turning off LEDs.")
|
||||
presets.select("off")
|
||||
presets.tick()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import math
|
||||
import sys
|
||||
if "lib" not in sys.path:
|
||||
sys.path.insert(0, "lib")
|
||||
if "../lib" not in sys.path:
|
||||
sys.path.insert(0, "../lib")
|
||||
from ws2812 import WS2812B
|
||||
import time
|
||||
|
||||
# --- Roll: N buffers (length = max strip), gradient full -> off; sequence through strips ---
|
||||
N_BUFFERS = 32 # more buffers = smoother transition
|
||||
|
||||
STRIP_CONFIG = (
|
||||
(2, 291),
|
||||
(3, 290),
|
||||
(4, 283),
|
||||
(7, 278),
|
||||
(0, 275),
|
||||
(28, 278),
|
||||
(29, 283),
|
||||
(6, 290),
|
||||
)
|
||||
|
||||
strips = []
|
||||
sm = 0
|
||||
for pin, num_leds in STRIP_CONFIG:
|
||||
print(pin, num_leds)
|
||||
ws = WS2812B(num_leds, pin, sm, brightness=1.0)
|
||||
strips.append(ws)
|
||||
sm += 1
|
||||
|
||||
num_strips = len(strips)
|
||||
max_leds = max(ws.num_leds for ws in strips)
|
||||
# Color when "on" (R, G, B); GRB order in buffer
|
||||
ROLL_COLOR = (0, 255, 120) # cyan-green
|
||||
|
||||
|
||||
def make_gradient_buffers(n_buffers, max_leds, color):
|
||||
"""Create n_buffers buffers, each max_leds long. Buffer 0 = full brightness, last = off.
|
||||
Gradient is logarithmic (perceptually smoother: more steps near full, fewer near off). GRB order."""
|
||||
out = []
|
||||
for j in range(n_buffers):
|
||||
# log gradient: scale = 255 * log(1 + (n - 1 - j)) / log(n) so 255 at j=0, 0 at j=n-1
|
||||
if n_buffers <= 1:
|
||||
scale = 255
|
||||
elif j >= n_buffers - 1:
|
||||
scale = 0
|
||||
else:
|
||||
# 1 + (n_buffers - 1 - j) runs from n_buffers down to 1
|
||||
scale = int(255 * math.log(1 + (n_buffers - 1 - j)) / math.log(n_buffers))
|
||||
scale = min(255, scale)
|
||||
buf = bytearray(max_leds * 3)
|
||||
r = (color[0] * scale) // 255
|
||||
g = (color[1] * scale) // 255
|
||||
b = (color[2] * scale) // 255
|
||||
for i in range(max_leds):
|
||||
o = i * 3
|
||||
buf[o] = g & 0xFF
|
||||
buf[o + 1] = r & 0xFF
|
||||
buf[o + 2] = b & 0xFF
|
||||
out.append(buf)
|
||||
return out
|
||||
|
||||
|
||||
# N buffers: first full, last off, gradient between
|
||||
buffers = make_gradient_buffers(N_BUFFERS, max_leds, ROLL_COLOR)
|
||||
|
||||
step = 0
|
||||
delay_ms = 50
|
||||
# Deadline-based loop: no extra pause at rotation wrap, smooth continuous roll
|
||||
next_ms = time.ticks_ms()
|
||||
|
||||
while True:
|
||||
for i, strip in enumerate(strips):
|
||||
buf_index = (step + i) % N_BUFFERS
|
||||
strip.show(buffers[buf_index], 0)
|
||||
step += 1 # unbounded; wrap only in index so no hitch at cycle end
|
||||
next_ms += delay_ms
|
||||
# Sleep until next frame time (handles drift, no pause at wrap)
|
||||
while time.ticks_diff(next_ms, time.ticks_ms()) > 0:
|
||||
time.sleep_ms(1)
|
||||
@@ -1,6 +0,0 @@
|
||||
from neopixel import NeoPixel
|
||||
from machine import Pin
|
||||
|
||||
p = NeoPixel(Pin(6), 291)
|
||||
p.fill((255, 255, 255))
|
||||
p.write()
|
||||
@@ -1,71 +0,0 @@
|
||||
"""
|
||||
On-device test that turns all LEDs on via Presets and verifies strip 0 (pin 6).
|
||||
|
||||
Usage (from pico/ dir or project root with adjusted paths):
|
||||
|
||||
mpremote connect <device> cp src/*.py :
|
||||
mpremote connect <device> cp src/patterns/*.py :patterns
|
||||
mpremote connect <device> cp lib/*.py :
|
||||
mpremote connect <device> cp test/test_all_on_presets.py :
|
||||
mpremote connect <device> run test_all_on_presets.py
|
||||
"""
|
||||
|
||||
from presets import Presets, Preset
|
||||
|
||||
|
||||
def verify_strip0_on(presets, expected_color):
|
||||
"""Check that every LED on strip 0 matches expected_color."""
|
||||
if not presets.strips:
|
||||
print("No strips; skipping strip-0 on test.")
|
||||
return
|
||||
|
||||
strip = presets.strips[0]
|
||||
r_exp, g_exp, b_exp = expected_color
|
||||
|
||||
for i in range(strip.num_leds):
|
||||
o = i * 3
|
||||
g = strip.ar[o]
|
||||
r = strip.ar[o + 1]
|
||||
b = strip.ar[o + 2]
|
||||
if (r, g, b) != (r_exp, g_exp, b_exp):
|
||||
raise AssertionError(
|
||||
"Strip 0 LED %d: got (%d,%d,%d), expected (%d,%d,%d)"
|
||||
% (i, r, g, b, r_exp, g_exp, b_exp)
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
presets = Presets()
|
||||
|
||||
if not presets.strips:
|
||||
print("No strips; skipping all-on-presets test.")
|
||||
return
|
||||
|
||||
# Full-brightness white via the built-in 'on' pattern.
|
||||
base_color = (255, 255, 255)
|
||||
brightness = 255
|
||||
|
||||
data = {
|
||||
"p": "on",
|
||||
"c": [base_color],
|
||||
"b": brightness,
|
||||
}
|
||||
|
||||
name = "test_all_on_presets"
|
||||
preset = Preset(data)
|
||||
presets.presets[name] = preset
|
||||
|
||||
presets.select(name)
|
||||
presets.tick()
|
||||
|
||||
# Compute the color actually written by the pattern after brightness scaling.
|
||||
expected_color = presets.apply_brightness(base_color, brightness)
|
||||
|
||||
verify_strip0_on(presets, expected_color)
|
||||
|
||||
print("test_all_on_presets: OK")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
"""
|
||||
On-device test that exercises the Chase pattern via Presets.
|
||||
|
||||
Usage (from pico/ dir or project root with adjusted paths):
|
||||
|
||||
mpremote connect <device> cp src/*.py :
|
||||
mpremote connect <device> cp src/patterns/*.py :patterns
|
||||
mpremote connect <device> cp lib/*.py :
|
||||
mpremote connect <device> cp test/test_chase_via_presets.py :
|
||||
mpremote connect <device> run test_chase_via_presets.py
|
||||
"""
|
||||
|
||||
import utime
|
||||
|
||||
from presets import Presets, Preset
|
||||
|
||||
|
||||
def snapshot_strip_colors(presets, strip_idx=0, max_leds=32):
|
||||
"""Return a list of (r,g,b) tuples for the first max_leds of the given strip."""
|
||||
strip = presets.strips[strip_idx]
|
||||
num = min(strip.num_leds, max_leds)
|
||||
out = []
|
||||
for i in range(num):
|
||||
o = i * 3
|
||||
g = strip.ar[o]
|
||||
r = strip.ar[o + 1]
|
||||
b = strip.ar[o + 2]
|
||||
out.append((r, g, b))
|
||||
return out
|
||||
|
||||
|
||||
def expected_chase_color(i, num_leds, step_count, color0, color1, n1, n2, n3, n4):
|
||||
"""Mirror the position logic from patterns/chase.py for a single logical LED."""
|
||||
segment_length = n1 + n2
|
||||
|
||||
if step_count % 2 == 0:
|
||||
position = (step_count // 2) * (n3 + n4) + n3
|
||||
else:
|
||||
position = ((step_count + 1) // 2) * (n3 + n4)
|
||||
|
||||
max_pos = num_leds + segment_length
|
||||
position = position % max_pos
|
||||
if position < 0:
|
||||
position += max_pos
|
||||
|
||||
relative_pos = (i - position) % segment_length
|
||||
if relative_pos < 0:
|
||||
relative_pos = (relative_pos + segment_length) % segment_length
|
||||
|
||||
return color0 if relative_pos < n1 else color1
|
||||
|
||||
|
||||
def test_chase_single_step_via_presets():
|
||||
presets = Presets()
|
||||
|
||||
num_leds = presets.num_leds
|
||||
if num_leds <= 0:
|
||||
print("No strips; skipping chase test.")
|
||||
return
|
||||
|
||||
# Simple alternating colors with known lengths.
|
||||
base_color0 = (10, 0, 0)
|
||||
base_color1 = (0, 0, 20)
|
||||
|
||||
# Use full brightness so apply_brightness is identity.
|
||||
brightness = 255
|
||||
|
||||
n1 = 2
|
||||
n2 = 3
|
||||
# Same step size on even/odd for easier reasoning.
|
||||
n3 = 1
|
||||
n4 = 1
|
||||
|
||||
data = {
|
||||
"p": "chase",
|
||||
"c": [base_color0, base_color1],
|
||||
"b": brightness,
|
||||
"d": 0,
|
||||
"a": False, # single-step mode
|
||||
"n1": n1,
|
||||
"n2": n2,
|
||||
"n3": n3,
|
||||
"n4": n4,
|
||||
}
|
||||
|
||||
name = "test_chase_pattern"
|
||||
preset = Preset(data)
|
||||
presets.presets[name] = preset
|
||||
|
||||
# Select and run one tick; this should render exactly one chase frame for step 0.
|
||||
presets.select(name, step=0)
|
||||
presets.tick()
|
||||
|
||||
# Colors after brightness scaling (driver.apply_brightness is used in the pattern).
|
||||
color0 = presets.apply_brightness(base_color0, brightness)
|
||||
color1 = presets.apply_brightness(base_color1, brightness)
|
||||
|
||||
# Snapshot first few LEDs of strip 0 and compare against expected pattern for step 0.
|
||||
colors = snapshot_strip_colors(presets, strip_idx=0, max_leds=16)
|
||||
step_count = 0
|
||||
|
||||
for i, actual in enumerate(colors):
|
||||
expected = expected_chase_color(
|
||||
i, num_leds, step_count, color0, color1, n1, n2, n3, n4
|
||||
)
|
||||
assert (
|
||||
actual == expected
|
||||
), "LED %d: got %r, expected %r" % (i, actual, expected)
|
||||
|
||||
print("test_chase_single_step_via_presets: OK")
|
||||
|
||||
|
||||
def test_chase_multiple_steps_via_presets():
|
||||
"""Render several steps and verify pattern advances correctly."""
|
||||
presets = Presets()
|
||||
|
||||
num_leds = presets.num_leds
|
||||
if num_leds <= 0:
|
||||
print("No strips; skipping chase multi-step test.")
|
||||
return
|
||||
|
||||
base_color0 = (10, 0, 0)
|
||||
base_color1 = (0, 0, 20)
|
||||
brightness = 255
|
||||
|
||||
n1 = 2
|
||||
n2 = 3
|
||||
n3 = 1
|
||||
n4 = 1
|
||||
|
||||
data = {
|
||||
"p": "chase",
|
||||
"c": [base_color0, base_color1],
|
||||
"b": brightness,
|
||||
"d": 0,
|
||||
"a": False,
|
||||
"n1": n1,
|
||||
"n2": n2,
|
||||
"n3": n3,
|
||||
"n4": n4,
|
||||
}
|
||||
|
||||
name = "test_chase_pattern_multi"
|
||||
preset = Preset(data)
|
||||
presets.presets[name] = preset
|
||||
|
||||
color0 = presets.apply_brightness(base_color0, brightness)
|
||||
color1 = presets.apply_brightness(base_color1, brightness)
|
||||
|
||||
# In non-auto mode (a=False), the Chase pattern advances one step per
|
||||
# invocation of the generator, and Presets is expected to call select()
|
||||
# again for each beat. Emulate that here by re-selecting with an
|
||||
# explicit step value for each frame we want to test.
|
||||
for step_count in range(4):
|
||||
presets.select(name, step=step_count)
|
||||
presets.tick()
|
||||
colors = snapshot_strip_colors(presets, strip_idx=0, max_leds=16)
|
||||
|
||||
for i, actual in enumerate(colors):
|
||||
expected = expected_chase_color(
|
||||
i, num_leds, step_count, color0, color1, n1, n2, n3, n4
|
||||
)
|
||||
assert (
|
||||
actual == expected
|
||||
), "step %d, LED %d: got %r, expected %r" % (
|
||||
step_count,
|
||||
i,
|
||||
actual,
|
||||
expected,
|
||||
)
|
||||
|
||||
print("test_chase_multiple_steps_via_presets: OK")
|
||||
|
||||
|
||||
def main():
|
||||
test_chase_single_step_via_presets()
|
||||
test_chase_multiple_steps_via_presets()
|
||||
# Give a brief pause so message is visible if run interactively.
|
||||
utime.sleep_ms(100)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
"""
|
||||
On-device test for the double_circle pattern using mpremote.
|
||||
|
||||
Usage (from pico/ dir or project root with adjusted paths):
|
||||
|
||||
mpremote connect <device> cp src/*.py :
|
||||
mpremote connect <device> cp src/patterns/*.py :patterns
|
||||
mpremote connect <device> cp lib/*.py :
|
||||
mpremote connect <device> cp test/test_double_circle.py :
|
||||
mpremote connect <device> run test_double_circle.py
|
||||
|
||||
This script:
|
||||
- Instantiates Presets
|
||||
- Creates a few in-memory 'double_circle' presets with different centers, widths, and colors
|
||||
- Selects each one so you can visually confirm the symmetric bands and color gradients
|
||||
"""
|
||||
|
||||
from presets import Presets, Preset
|
||||
|
||||
|
||||
def make_double_circle_preset(
|
||||
name, center, half_width, colors, direction=0, step_size=1, brightness=255
|
||||
):
|
||||
"""
|
||||
Helper to build a Preset for the 'double_circle' pattern.
|
||||
|
||||
center: logical index (0-based, on reference strip 0)
|
||||
half_width: number of LEDs each side of center
|
||||
colors: [color1, color2] where each color is (r,g,b)
|
||||
"""
|
||||
cs = list(colors)[:2]
|
||||
while len(cs) < 2:
|
||||
cs.append((0, 0, 0))
|
||||
|
||||
data = {
|
||||
"p": "double_circle",
|
||||
"c": cs,
|
||||
"b": brightness,
|
||||
"n1": center,
|
||||
"n2": half_width,
|
||||
"n3": direction,
|
||||
"n4": step_size,
|
||||
}
|
||||
return name, Preset(data)
|
||||
|
||||
|
||||
def show_and_wait(presets, name, preset_obj, wait_ms):
|
||||
"""Select a static double_circle preset and hold it for wait_ms."""
|
||||
presets.presets[name] = preset_obj
|
||||
presets.select(name)
|
||||
# DoubleCircle draws immediately in run(), then just yields; one tick is enough.
|
||||
presets.tick()
|
||||
|
||||
import utime
|
||||
|
||||
start = utime.ticks_ms()
|
||||
while utime.ticks_diff(utime.ticks_ms(), start) < wait_ms:
|
||||
presets.tick()
|
||||
|
||||
|
||||
def main():
|
||||
presets = Presets()
|
||||
presets.load()
|
||||
|
||||
num_leds = presets.strip_length(0)
|
||||
if num_leds <= 0:
|
||||
print("No strips; aborting double_circle test.")
|
||||
return
|
||||
|
||||
print("Starting double_circle pattern test...")
|
||||
|
||||
quarter = num_leds // 4
|
||||
half = num_leds // 2
|
||||
|
||||
dc_presets = []
|
||||
|
||||
# 1. Center at top (0), moderate width, color1 at center (n3=0)
|
||||
dc_presets.append(
|
||||
make_double_circle_preset(
|
||||
"dc_top_red_to_blue",
|
||||
center=0,
|
||||
half_width=quarter,
|
||||
colors=[(255, 0, 0), (0, 0, 255)],
|
||||
direction=0,
|
||||
)
|
||||
)
|
||||
|
||||
# 2. Center at bottom (half), narrow band, color1 at endpoints (n3=1)
|
||||
dc_presets.append(
|
||||
make_double_circle_preset(
|
||||
"dc_bottom_green_to_purple",
|
||||
center=half,
|
||||
half_width=quarter // 2,
|
||||
colors=[(0, 255, 0), (128, 0, 128)],
|
||||
direction=1,
|
||||
)
|
||||
)
|
||||
|
||||
# 3. Center at quarter, wide band, both directions for comparison
|
||||
dc_presets.append(
|
||||
make_double_circle_preset(
|
||||
"dc_quarter_white_to_cyan_inward",
|
||||
center=quarter,
|
||||
half_width=half,
|
||||
colors=[(255, 255, 255), (0, 255, 255)],
|
||||
direction=0,
|
||||
)
|
||||
)
|
||||
|
||||
dc_presets.append(
|
||||
make_double_circle_preset(
|
||||
"dc_quarter_white_to_cyan_outward",
|
||||
center=quarter,
|
||||
half_width=half,
|
||||
colors=[(255, 255, 255), (0, 255, 255)],
|
||||
direction=1,
|
||||
)
|
||||
)
|
||||
|
||||
# 4. Explicit test: n1 = 50, n2 = 40 (half of 80) inward
|
||||
dc_presets.append(
|
||||
make_double_circle_preset(
|
||||
"dc_n1_50_n2_40_inward",
|
||||
center=50,
|
||||
half_width=40,
|
||||
colors=[(255, 100, 0), (0, 0, 0)],
|
||||
direction=0,
|
||||
)
|
||||
)
|
||||
|
||||
# 5. Explicit test: n1 = num_leds//2, n2 = num_leds//4 outward, stepping as fast as possible
|
||||
center_half = num_leds // 2
|
||||
radius_quarter = max(1, num_leds // 4)
|
||||
dc_presets.append(
|
||||
make_double_circle_preset(
|
||||
"dc_n1_half_n2_quarter_outward",
|
||||
center=center_half,
|
||||
half_width=radius_quarter,
|
||||
colors=[(0, 150, 255), (0, 0, 0)],
|
||||
direction=1,
|
||||
step_size=radius_quarter, # jump to full radius in one step
|
||||
)
|
||||
)
|
||||
|
||||
# Show each for ~4 seconds
|
||||
for name, preset_obj in dc_presets:
|
||||
print("Showing double_circle preset:", name)
|
||||
show_and_wait(presets, name, preset_obj, wait_ms=4000)
|
||||
|
||||
print("Double_circle pattern test finished. Turning off LEDs.")
|
||||
presets.select("off")
|
||||
presets.tick()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,264 +0,0 @@
|
||||
"""
|
||||
On-device test that exercises Segments and multiple SegmentsTransition presets via Presets.
|
||||
|
||||
Usage (from pico/ dir or project root with adjusted paths):
|
||||
|
||||
mpremote connect <device> cp src/*.py :
|
||||
mpremote connect <device> cp src/patterns/*.py :patterns
|
||||
mpremote connect <device> cp lib/*.py :
|
||||
mpremote connect <device> cp test/test_multi_patterns.py :
|
||||
mpremote connect <device> run test_multi_patterns.py
|
||||
"""
|
||||
|
||||
import utime
|
||||
|
||||
from presets import Presets, Preset
|
||||
|
||||
|
||||
def run_for(presets, duration_ms):
|
||||
"""Tick the current pattern for duration_ms."""
|
||||
start = utime.ticks_ms()
|
||||
while utime.ticks_diff(utime.ticks_ms(), start) < duration_ms:
|
||||
presets.tick()
|
||||
utime.sleep_ms(10)
|
||||
|
||||
|
||||
def make_segments_preset(name, colors, n_values, brightness=255):
|
||||
"""
|
||||
Helper to build a Preset for the 'segments' pattern.
|
||||
|
||||
colors: list of up to 4 (r,g,b) tuples
|
||||
n_values: list/tuple of 8 ints [n1..n8]
|
||||
"""
|
||||
cs = list(colors)[:4]
|
||||
while len(cs) < 4:
|
||||
cs.append((0, 0, 0))
|
||||
|
||||
n1, n2, n3, n4, n5, n6, n7, n8 = n_values
|
||||
data = {
|
||||
"p": "segments",
|
||||
"c": cs,
|
||||
"b": brightness,
|
||||
"n1": n1,
|
||||
"n2": n2,
|
||||
"n3": n3,
|
||||
"n4": n4,
|
||||
"n5": n5,
|
||||
"n6": n6,
|
||||
"n7": n7,
|
||||
"n8": n8,
|
||||
}
|
||||
return name, Preset(data)
|
||||
|
||||
|
||||
def make_segments_transition_preset(name, colors, n_values, duration_ms=1000, brightness=255):
|
||||
"""
|
||||
Helper to build a Preset for the 'segments_transition' pattern.
|
||||
|
||||
Starts from whatever is currently displayed and fades to the
|
||||
new segments layout over duration_ms.
|
||||
"""
|
||||
cs = list(colors)[:4]
|
||||
while len(cs) < 4:
|
||||
cs.append((0, 0, 0))
|
||||
|
||||
n1, n2, n3, n4, n5, n6, n7, n8 = n_values
|
||||
data = {
|
||||
"p": "segments_transition",
|
||||
"c": cs,
|
||||
"b": brightness,
|
||||
"d": duration_ms,
|
||||
"n1": n1,
|
||||
"n2": n2,
|
||||
"n3": n3,
|
||||
"n4": n4,
|
||||
"n5": n5,
|
||||
"n6": n6,
|
||||
"n7": n7,
|
||||
"n8": n8,
|
||||
}
|
||||
return name, Preset(data)
|
||||
|
||||
|
||||
def main():
|
||||
presets = Presets()
|
||||
presets.load()
|
||||
|
||||
num_leds = presets.strip_length(0)
|
||||
if num_leds <= 0:
|
||||
print("No strips; aborting multi-pattern test.")
|
||||
return
|
||||
|
||||
print("Starting multi-pattern test with Presets...")
|
||||
|
||||
quarter = num_leds // 4
|
||||
half = num_leds // 2
|
||||
|
||||
# 1. Static segments: simple R/G/B bands
|
||||
name_static, preset_static = make_segments_preset(
|
||||
"mp_segments_static",
|
||||
colors=[(255, 0, 0), (0, 255, 0), (0, 0, 255)],
|
||||
n_values=[
|
||||
0,
|
||||
quarter - 1, # red
|
||||
quarter,
|
||||
2 * quarter - 1, # green
|
||||
2 * quarter,
|
||||
3 * quarter - 1, # blue
|
||||
0,
|
||||
-1,
|
||||
],
|
||||
)
|
||||
|
||||
# 2a. Segments transition: fade from previous buffer to new colors (slow)
|
||||
name_trans1, preset_trans1 = make_segments_transition_preset(
|
||||
"mp_segments_transition_1",
|
||||
colors=[(255, 255, 255), (255, 0, 255), (0, 255, 255)],
|
||||
n_values=[
|
||||
0,
|
||||
half - 1, # white on first half
|
||||
half,
|
||||
num_leds - 1, # magenta on second half
|
||||
0,
|
||||
-1, # cyan unused in this example
|
||||
0,
|
||||
-1,
|
||||
],
|
||||
duration_ms=3000,
|
||||
)
|
||||
|
||||
# 2b. Segments transition: fade between two different segment layouts
|
||||
name_trans2, preset_trans2 = make_segments_transition_preset(
|
||||
"mp_segments_transition_2",
|
||||
colors=[(255, 0, 0), (0, 0, 255)],
|
||||
n_values=[
|
||||
0,
|
||||
quarter - 1, # red first quarter
|
||||
quarter,
|
||||
2 * quarter - 1, # blue second quarter
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
-1,
|
||||
],
|
||||
duration_ms=4000,
|
||||
)
|
||||
|
||||
# 2c. Segments transition: thin moving band (center quarter only)
|
||||
band_start = quarter // 2
|
||||
band_end = band_start + quarter
|
||||
name_trans3, preset_trans3 = make_segments_transition_preset(
|
||||
"mp_segments_transition_3",
|
||||
colors=[(0, 255, 0)],
|
||||
n_values=[
|
||||
band_start,
|
||||
band_end - 1, # green band in the middle
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
-1,
|
||||
],
|
||||
duration_ms=5000,
|
||||
)
|
||||
|
||||
# 2d. Segments transition: full-ring warm white fade
|
||||
name_trans4, preset_trans4 = make_segments_transition_preset(
|
||||
"mp_segments_transition_4",
|
||||
colors=[(255, 200, 100)],
|
||||
n_values=[
|
||||
0,
|
||||
num_leds - 1, # entire strip
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
-1,
|
||||
],
|
||||
duration_ms=6000,
|
||||
)
|
||||
|
||||
# 2e. Segments transition: alternating warm/cool halves
|
||||
name_trans5, preset_trans5 = make_segments_transition_preset(
|
||||
"mp_segments_transition_5",
|
||||
colors=[(255, 180, 100), (100, 180, 255)],
|
||||
n_values=[
|
||||
0,
|
||||
half - 1, # warm first half
|
||||
half,
|
||||
num_leds - 1, # cool second half
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
-1,
|
||||
],
|
||||
duration_ms=5000,
|
||||
)
|
||||
|
||||
# 2f. Segments transition: narrow red band near start
|
||||
narrow_start = num_leds // 16
|
||||
narrow_end = narrow_start + max(4, num_leds // 32)
|
||||
name_trans6, preset_trans6 = make_segments_transition_preset(
|
||||
"mp_segments_transition_6",
|
||||
colors=[(255, 0, 0)],
|
||||
n_values=[
|
||||
narrow_start,
|
||||
narrow_end - 1,
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
-1,
|
||||
0,
|
||||
-1,
|
||||
],
|
||||
duration_ms=4000,
|
||||
)
|
||||
|
||||
# Register presets in Presets and run them in sequence
|
||||
presets.presets[name_static] = preset_static
|
||||
presets.presets[name_trans1] = preset_trans1
|
||||
presets.presets[name_trans2] = preset_trans2
|
||||
presets.presets[name_trans3] = preset_trans3
|
||||
presets.presets[name_trans4] = preset_trans4
|
||||
presets.presets[name_trans5] = preset_trans5
|
||||
presets.presets[name_trans6] = preset_trans6
|
||||
|
||||
print("Showing static segments...")
|
||||
presets.select(name_static)
|
||||
presets.tick() # draw once
|
||||
run_for(presets, 3000)
|
||||
|
||||
print("Running segments transition 1 (fading to new half/half layout)...")
|
||||
presets.select(name_trans1)
|
||||
run_for(presets, 3500)
|
||||
|
||||
print("Running segments transition 2 (fading to quarter-band layout)...")
|
||||
presets.select(name_trans2)
|
||||
run_for(presets, 4500)
|
||||
|
||||
print("Running segments transition 3 (fading to center green band)...")
|
||||
presets.select(name_trans3)
|
||||
run_for(presets, 5500)
|
||||
|
||||
print("Running segments transition 4 (fading to full warm white ring)...")
|
||||
presets.select(name_trans4)
|
||||
run_for(presets, 6500)
|
||||
|
||||
print("Running segments transition 5 (fading to warm/cool halves)...")
|
||||
presets.select(name_trans5)
|
||||
run_for(presets, 5500)
|
||||
|
||||
print("Running segments transition 6 (fading to narrow red band)...")
|
||||
presets.select(name_trans6)
|
||||
run_for(presets, 4500)
|
||||
|
||||
print("Multi-pattern test finished. Turning off LEDs.")
|
||||
presets.select("off")
|
||||
presets.tick()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
"""
|
||||
On-device test for the Segments pattern using mpremote.
|
||||
On-device test for the Point pattern using mpremote.
|
||||
|
||||
Usage (from pico/ dir or project root with adjusted paths):
|
||||
|
||||
mpremote connect <device> cp src/*.py :
|
||||
mpremote connect <device> cp src/patterns/*.py :patterns
|
||||
mpremote connect <device> cp lib/*.py :
|
||||
mpremote connect <device> cp test/test_segments.py :
|
||||
mpremote connect <device> run test_segments.py
|
||||
mpremote connect <device> cp test/test_point.py :
|
||||
mpremote connect <device> run test_point.py
|
||||
|
||||
This script:
|
||||
- Instantiates Presets
|
||||
- Creates a few in-memory 'point' (Segments) presets with different ranges/colors
|
||||
- Creates a few in-memory 'point' presets with different ranges/colors
|
||||
- Selects each one so you can visually confirm the segments
|
||||
"""
|
||||
|
||||
from presets import Presets, Preset
|
||||
|
||||
|
||||
def make_segments_preset(name, colors, n_values, brightness=255):
|
||||
def make_point_preset(name, colors, n_values, brightness=255):
|
||||
"""
|
||||
Helper to build a Preset for the 'segments' pattern (key 'point').
|
||||
Helper to build a Preset for the 'point' pattern.
|
||||
|
||||
colors: list of up to 4 (r,g,b) tuples
|
||||
n_values: list/tuple of 8 ints [n1..n8]
|
||||
@@ -32,7 +32,7 @@ def make_segments_preset(name, colors, n_values, brightness=255):
|
||||
|
||||
n1, n2, n3, n4, n5, n6, n7, n8 = n_values
|
||||
data = {
|
||||
"p": "segments", # pattern key for Segments
|
||||
"p": "point",
|
||||
"c": cs,
|
||||
"b": brightness,
|
||||
"n1": n1,
|
||||
@@ -43,16 +43,16 @@ def make_segments_preset(name, colors, n_values, brightness=255):
|
||||
"n6": n6,
|
||||
"n7": n7,
|
||||
"n8": n8,
|
||||
# 'a' is not used by segments; it's static
|
||||
# 'a' is not used by point; it's static
|
||||
}
|
||||
return name, Preset(data)
|
||||
|
||||
|
||||
def show_and_wait(presets, name, preset_obj, wait_ms):
|
||||
"""Select a static segments preset and hold it for wait_ms."""
|
||||
"""Select a static 'point' preset and hold it for wait_ms."""
|
||||
presets.presets[name] = preset_obj
|
||||
presets.select(name)
|
||||
# Segments draws immediately in run(), then just yields; one tick is enough.
|
||||
# Point draws immediately in run(), then just yields; one tick is enough.
|
||||
presets.tick()
|
||||
|
||||
import utime
|
||||
@@ -69,46 +69,46 @@ def main():
|
||||
|
||||
num_leds = presets.strip_length(0)
|
||||
if num_leds <= 0:
|
||||
print("No strips; aborting segments test.")
|
||||
print("No strips; aborting point test.")
|
||||
return
|
||||
|
||||
print("Starting segments pattern test...")
|
||||
print("Starting point pattern test...")
|
||||
|
||||
quarter = num_leds // 4
|
||||
half = num_leds // 2
|
||||
|
||||
segments_presets = []
|
||||
point_presets = []
|
||||
|
||||
# 1. Single band: first quarter, red
|
||||
segments_presets.append(
|
||||
make_segments_preset(
|
||||
"segments_red_q1",
|
||||
point_presets.append(
|
||||
make_point_preset(
|
||||
"point_red_q1",
|
||||
colors=[(255, 0, 0)],
|
||||
n_values=[0, quarter - 1, 0, -1, 0, -1, 0, -1],
|
||||
)
|
||||
)
|
||||
|
||||
# 2. Two bands: red first half, green second half
|
||||
segments_presets.append(
|
||||
make_segments_preset(
|
||||
"segments_red_green_halves",
|
||||
point_presets.append(
|
||||
make_point_preset(
|
||||
"point_red_green_halves",
|
||||
colors=[(255, 0, 0), (0, 255, 0)],
|
||||
n_values=[0, half - 1, half, num_leds - 1, 0, -1, 0, -1],
|
||||
)
|
||||
)
|
||||
|
||||
# 3. Three bands: R, G, B quarters
|
||||
segments_presets.append(
|
||||
make_segments_preset(
|
||||
"segments_rgb_quarters",
|
||||
point_presets.append(
|
||||
make_point_preset(
|
||||
"point_rgb_quarters",
|
||||
colors=[(255, 0, 0), (0, 255, 0), (0, 0, 255)],
|
||||
n_values=[
|
||||
0,
|
||||
quarter - 1, # red
|
||||
quarter - 1, # red
|
||||
quarter,
|
||||
2 * quarter - 1, # green
|
||||
2 * quarter - 1, # green
|
||||
2 * quarter,
|
||||
3 * quarter - 1, # blue
|
||||
3 * quarter - 1, # blue
|
||||
0,
|
||||
-1,
|
||||
],
|
||||
@@ -116,11 +116,11 @@ def main():
|
||||
)
|
||||
|
||||
# Show each for ~4 seconds
|
||||
for name, preset_obj in segments_presets:
|
||||
print("Showing segments preset:", name)
|
||||
for name, preset_obj in point_presets:
|
||||
print("Showing point preset:", name)
|
||||
show_and_wait(presets, name, preset_obj, wait_ms=4000)
|
||||
|
||||
print("Segments pattern test finished. Turning off LEDs.")
|
||||
print("Point pattern test finished. Turning off LEDs.")
|
||||
presets.select("off")
|
||||
presets.tick()
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
On-device test for the Roll pattern using mpremote.
|
||||
|
||||
Usage (from pico/ dir or project root with adjusted paths):
|
||||
|
||||
mpremote connect <device> cp src/*.py :
|
||||
mpremote connect <device> cp src/patterns/*.py :patterns
|
||||
mpremote connect <device> cp lib/*.py :
|
||||
mpremote connect <device> cp test/test_roll.py :
|
||||
mpremote connect <device> run test_roll.py
|
||||
|
||||
This script:
|
||||
- Instantiates Presets
|
||||
- Creates a few in-memory roll presets with different parameters
|
||||
- Runs each one for a short time so you can visually compare behaviour
|
||||
"""
|
||||
|
||||
import utime
|
||||
from presets import Presets, Preset
|
||||
|
||||
|
||||
def make_roll_preset(name, color1, color2, n1=0, n2=0, n3=0, n4=0, delay_ms=50, brightness=255):
|
||||
"""Helper to build a Preset dict for the roll pattern."""
|
||||
data = {
|
||||
"p": "roll",
|
||||
"c": [color1, color2],
|
||||
"b": brightness,
|
||||
"d": delay_ms,
|
||||
"n1": n1,
|
||||
"n2": n2,
|
||||
"n3": n3,
|
||||
"n4": n4,
|
||||
"a": True, # animated
|
||||
}
|
||||
return name, Preset(data)
|
||||
|
||||
|
||||
def run_preset(presets, name, preset_obj, duration_ms):
|
||||
"""Run a given roll preset for duration_ms using the existing tick loop."""
|
||||
presets.presets[name] = preset_obj
|
||||
presets.select(name)
|
||||
|
||||
start = utime.ticks_ms()
|
||||
while utime.ticks_diff(utime.ticks_ms(), start) < duration_ms:
|
||||
presets.tick()
|
||||
|
||||
|
||||
def main():
|
||||
presets = Presets()
|
||||
presets.load()
|
||||
|
||||
print("Starting roll pattern test...")
|
||||
|
||||
ref_len = presets.strip_length(0)
|
||||
# Use some margins based on strip length to show different bands.
|
||||
quarter = ref_len // 4
|
||||
|
||||
# Define a few different roll presets:
|
||||
roll_presets = []
|
||||
|
||||
# 1. Full-strip, white -> off, clockwise, medium speed
|
||||
roll_presets.append(
|
||||
make_roll_preset(
|
||||
"roll_full_cw",
|
||||
color1=(255, 255, 255),
|
||||
color2=(0, 0, 0),
|
||||
n1=0,
|
||||
n2=0,
|
||||
n3=2, # 2 rotations then stop
|
||||
n4=0, # clockwise
|
||||
delay_ms=40,
|
||||
brightness=255,
|
||||
)
|
||||
)
|
||||
|
||||
# 2. Inner band only, red -> blue, clockwise, slower
|
||||
roll_presets.append(
|
||||
make_roll_preset(
|
||||
"roll_inner_band",
|
||||
color1=(255, 0, 0),
|
||||
color2=(0, 0, 255),
|
||||
n1=quarter, # start margin
|
||||
n2=quarter, # end margin
|
||||
n3=2,
|
||||
n4=0,
|
||||
delay_ms=60,
|
||||
brightness=255,
|
||||
)
|
||||
)
|
||||
|
||||
# 3. Full-strip, green -> off, counter-clockwise, faster
|
||||
roll_presets.append(
|
||||
make_roll_preset(
|
||||
"roll_full_ccw",
|
||||
color1=(0, 255, 0),
|
||||
color2=(0, 0, 0),
|
||||
n1=0,
|
||||
n2=0,
|
||||
n3=2,
|
||||
n4=1, # counter-clockwise
|
||||
delay_ms=30,
|
||||
brightness=255,
|
||||
)
|
||||
)
|
||||
|
||||
# Run each roll preset for about 5 seconds
|
||||
for name, preset_obj in roll_presets:
|
||||
print("Running roll preset:", name)
|
||||
run_preset(presets, name, preset_obj, duration_ms=5000)
|
||||
|
||||
print("Roll pattern test finished. Turning off LEDs.")
|
||||
presets.select("off")
|
||||
presets.tick()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
"""
|
||||
On-device test for the Spin pattern using mpremote and Presets.
|
||||
|
||||
Usage (from pico/ dir or project root with adjusted paths):
|
||||
|
||||
mpremote connect <device> cp src/*.py :
|
||||
mpremote connect <device> cp src/patterns/*.py :patterns
|
||||
mpremote connect <device> cp lib/*.py :
|
||||
mpremote connect <device> cp presets.json :
|
||||
mpremote connect <device> cp test/test_spin.py :
|
||||
mpremote connect <device> run test_spin.py
|
||||
|
||||
This script:
|
||||
- Instantiates Presets
|
||||
- Creates a few in-memory spin presets with different parameters
|
||||
- Runs each one for a short time so you can visually compare behaviour
|
||||
"""
|
||||
|
||||
import utime
|
||||
from presets import Presets, Preset
|
||||
|
||||
|
||||
def make_spin_preset(
|
||||
name,
|
||||
color_inner,
|
||||
color_outer,
|
||||
rate=4,
|
||||
delay_ms=30,
|
||||
margin=0,
|
||||
brightness=255,
|
||||
):
|
||||
"""Helper to build a Preset dict for the spin pattern."""
|
||||
data = {
|
||||
"p": "spin",
|
||||
"c": [color_inner, color_outer],
|
||||
"b": brightness,
|
||||
"d": delay_ms,
|
||||
"n1": rate, # expansion step per tick
|
||||
"n2": margin, # margin from strip ends
|
||||
"a": True,
|
||||
}
|
||||
return name, Preset(data)
|
||||
|
||||
|
||||
def run_preset(presets, name, preset_obj, duration_ms):
|
||||
"""Run a given spin preset for duration_ms using the existing tick loop."""
|
||||
# Start each preset from a blank frame so both sides are balanced.
|
||||
presets.select("off")
|
||||
presets.tick()
|
||||
|
||||
presets.presets[name] = preset_obj
|
||||
presets.select(name)
|
||||
|
||||
start = utime.ticks_ms()
|
||||
while utime.ticks_diff(utime.ticks_ms(), start) < duration_ms:
|
||||
presets.tick()
|
||||
utime.sleep_ms(10)
|
||||
|
||||
|
||||
def main():
|
||||
presets = Presets()
|
||||
presets.load()
|
||||
|
||||
# Ensure we start from a blank frame.
|
||||
presets.select("off")
|
||||
presets.tick()
|
||||
|
||||
print("Starting spin pattern test...")
|
||||
|
||||
# Use strip 0 length to derive a reasonable margin.
|
||||
ref_len = presets.strip_length(0)
|
||||
margin_small = ref_len // 16 if ref_len > 0 else 0
|
||||
margin_large = ref_len // 8 if ref_len > 0 else 0
|
||||
|
||||
spin_presets = []
|
||||
|
||||
# 1. Slow spin, warm white to orange, small margin
|
||||
spin_presets.append(
|
||||
make_spin_preset(
|
||||
"spin_slow_warm",
|
||||
color_inner=(255, 200, 120),
|
||||
color_outer=(255, 100, 0),
|
||||
rate=2,
|
||||
delay_ms=40,
|
||||
margin=margin_small,
|
||||
brightness=255,
|
||||
)
|
||||
)
|
||||
|
||||
# 2. Medium spin, cyan to magenta, larger margin
|
||||
spin_presets.append(
|
||||
make_spin_preset(
|
||||
"spin_medium_cyan_magenta",
|
||||
color_inner=(0, 255, 180),
|
||||
color_outer=(255, 0, 180),
|
||||
rate=4,
|
||||
delay_ms=30,
|
||||
margin=margin_large,
|
||||
brightness=255,
|
||||
)
|
||||
)
|
||||
|
||||
# 3. Fast spin, white to off (fade outwards), no margin
|
||||
spin_presets.append(
|
||||
make_spin_preset(
|
||||
"spin_fast_white",
|
||||
color_inner=(255, 255, 255),
|
||||
color_outer=(0, 0, 0),
|
||||
rate=6,
|
||||
delay_ms=20,
|
||||
margin=0,
|
||||
brightness=255,
|
||||
)
|
||||
)
|
||||
|
||||
# Run each spin preset for about 6 seconds
|
||||
for name, preset_obj in spin_presets:
|
||||
print("Running spin preset:", name)
|
||||
run_preset(presets, name, preset_obj, duration_ms=6000)
|
||||
|
||||
print("Spin pattern test finished. Turning off LEDs.")
|
||||
presets.select("off")
|
||||
presets.tick()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in new issue
Block a user