Compare commits
2
Commits
4cd3bc7973
...
995b05f538
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
995b05f538 | ||
|
|
762ec338bc |
No files matched your search
@@ -75,6 +75,26 @@ JSON API (port 80):
|
|||||||
| POST | `/api/wifi` | `{"ssid","password"}`: save and connect |
|
| POST | `/api/wifi` | `{"ssid","password"}`: save and connect |
|
||||||
| GET | `/api/wifi/scan` | Visible networks |
|
| GET | `/api/wifi/scan` | Visible networks |
|
||||||
|
|
||||||
|
### USB configuration (led-tool)
|
||||||
|
|
||||||
|
The JSON API above is also served on the USB serial port (`/dev/ttyACM0`, `main/usb_cfg.cpp`), so a driver can be set up without Wi-Fi. One line per request and per reply; every other line is log output:
|
||||||
|
|
||||||
|
```
|
||||||
|
@api {"id":1,"method":"GET","path":"/api/status"}
|
||||||
|
@api {"id":1,"status":200,"body":"{...}"}
|
||||||
|
@api {"id":2,"method":"POST","path":"/api/hardware","body":{"num_leds":60}}
|
||||||
|
@reboot
|
||||||
|
```
|
||||||
|
|
||||||
|
Requests run on the web server's task, with the same checks as the web UI. `led-tool` uses this automatically:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python cli.py -s
|
||||||
|
python cli.py -l 60 -o rgb --pin 10 -b 128 -n bar1
|
||||||
|
```
|
||||||
|
|
||||||
|
Open the port with DTR high and RTS low (RTS high with DTR low resets the chip).
|
||||||
|
|
||||||
Build and flash for the ESP32-C3:
|
Build and flash for the ESP32-C3:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" "presets.cpp"
|
idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" "presets.cpp"
|
||||||
"effects_util.cpp" "ws_client.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp"
|
"effects_util.cpp" "ws_client.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp" "usb_cfg.cpp"
|
||||||
PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event
|
PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event
|
||||||
esp_timer nvs_flash esp_http_server esp_http_client cjson mdns esp_hw_support app_update esp_app_format lwip
|
esp_timer nvs_flash esp_http_server esp_http_client cjson mdns esp_hw_support app_update esp_app_format lwip esp_driver_usb_serial_jtag
|
||||||
INCLUDE_DIRS "."
|
INCLUDE_DIRS "."
|
||||||
EMBED_TXTFILES "../web/index.html" "../web/app.js" "../web/style.css")
|
EMBED_TXTFILES "../web/index.html" "../web/app.js" "../web/style.css")
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
#include "ota.h"
|
#include "ota.h"
|
||||||
#include "patterns.h"
|
#include "patterns.h"
|
||||||
#include "presets.h"
|
#include "presets.h"
|
||||||
|
#include "usb_cfg.h"
|
||||||
#include "web.h"
|
#include "web.h"
|
||||||
|
|
||||||
static const char *TAG = "example";
|
static const char *TAG = "example";
|
||||||
@@ -30,6 +31,7 @@ extern "C" void app_main(void)
|
|||||||
presets_apply_startup();
|
presets_apply_startup();
|
||||||
ESP_ERROR_CHECK(net_start());
|
ESP_ERROR_CHECK(net_start());
|
||||||
ESP_ERROR_CHECK(web_start());
|
ESP_ERROR_CHECK(web_start());
|
||||||
|
usb_cfg_start(); // led-tool over USB; the LEDs and Wi-Fi work without it
|
||||||
ESP_ERROR_CHECK(ddp_start());
|
ESP_ERROR_CHECK(ddp_start());
|
||||||
ota_confirm_later();
|
ota_confirm_later();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include <cstdarg>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
#include "driver/usb_serial_jtag.h"
|
||||||
|
#include "driver/usb_serial_jtag_vfs.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_system.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
#include "usb_cfg.h"
|
||||||
|
#include "web.h"
|
||||||
|
|
||||||
|
static const char *TAG = "usb_cfg";
|
||||||
|
|
||||||
|
static const char API_PREFIX[] = "@api ";
|
||||||
|
static const char REBOOT[] = "@reboot";
|
||||||
|
|
||||||
|
// The driver's TX buffer takes a write whole or not at all, so a long reply goes out in chunks.
|
||||||
|
// Log output takes the same lock (log_vprintf), so no log line can land inside a reply.
|
||||||
|
static SemaphoreHandle_t s_tx_lock;
|
||||||
|
static vprintf_like_t s_log_vprintf;
|
||||||
|
|
||||||
|
static int log_vprintf(const char *fmt, va_list args)
|
||||||
|
{
|
||||||
|
// A log from inside a reply write (none today) would deadlock, so only wait if we don't hold it
|
||||||
|
const bool locked = s_tx_lock && xSemaphoreGetMutexHolder(s_tx_lock) != xTaskGetCurrentTaskHandle()
|
||||||
|
&& xSemaphoreTake(s_tx_lock, portMAX_DELAY) == pdTRUE;
|
||||||
|
int r = s_log_vprintf(fmt, args);
|
||||||
|
if (locked) {
|
||||||
|
fflush(stdout);
|
||||||
|
xSemaphoreGive(s_tx_lock);
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void write_line(const char *s)
|
||||||
|
{
|
||||||
|
static const size_t CHUNK = 256;
|
||||||
|
xSemaphoreTake(s_tx_lock, portMAX_DELAY);
|
||||||
|
fflush(stdout); // finish any log text already in stdio's buffer first
|
||||||
|
for (size_t n = strlen(s); n > 0;) {
|
||||||
|
size_t k = n < CHUNK ? n : CHUNK;
|
||||||
|
if (usb_serial_jtag_write_bytes(s, k, pdMS_TO_TICKS(500)) != (int)k) {
|
||||||
|
break; // no host reading: drop the rest rather than hold up the logs
|
||||||
|
}
|
||||||
|
s += k;
|
||||||
|
n -= k;
|
||||||
|
}
|
||||||
|
xSemaphoreGive(s_tx_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
// An "@api" line: run it and send back the envelope, with the request's id added
|
||||||
|
static void handle_api(const char *json, char *reply, size_t cap)
|
||||||
|
{
|
||||||
|
web_api_call(json, reply, cap);
|
||||||
|
|
||||||
|
cJSON *req = cJSON_Parse(json);
|
||||||
|
const cJSON *id = req ? cJSON_GetObjectItem(req, "id") : NULL;
|
||||||
|
cJSON *env = cJSON_Parse(reply);
|
||||||
|
if (!env) {
|
||||||
|
env = cJSON_CreateObject();
|
||||||
|
cJSON_AddNumberToObject(env, "status", 500);
|
||||||
|
cJSON_AddStringToObject(env, "body", "{\"error\":\"reply too large\"}");
|
||||||
|
}
|
||||||
|
if (cJSON_IsNumber(id)) {
|
||||||
|
cJSON_AddNumberToObject(env, "id", id->valuedouble);
|
||||||
|
}
|
||||||
|
char *s = cJSON_PrintUnformatted(env);
|
||||||
|
cJSON_Delete(env);
|
||||||
|
cJSON_Delete(req);
|
||||||
|
if (!s) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
size_t n = strlen(s);
|
||||||
|
// A leading newline ends any log line that was half written, so the reply starts its own line
|
||||||
|
const size_t pre = sizeof(API_PREFIX) - 1;
|
||||||
|
char *line = (char *)malloc(1 + pre + n + 2);
|
||||||
|
if (line) {
|
||||||
|
line[0] = '\n';
|
||||||
|
memcpy(line + 1, API_PREFIX, pre);
|
||||||
|
memcpy(line + 1 + pre, s, n);
|
||||||
|
line[1 + pre + n] = '\n';
|
||||||
|
line[2 + pre + n] = '\0';
|
||||||
|
write_line(line);
|
||||||
|
free(line);
|
||||||
|
}
|
||||||
|
cJSON_free(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handle_line(char *line, char *reply, size_t cap)
|
||||||
|
{
|
||||||
|
size_t n = strlen(line);
|
||||||
|
while (n && (line[n - 1] == '\r' || line[n - 1] == ' ')) {
|
||||||
|
line[--n] = '\0';
|
||||||
|
}
|
||||||
|
if (strncmp(line, API_PREFIX, sizeof(API_PREFIX) - 1) == 0) {
|
||||||
|
handle_api(line + sizeof(API_PREFIX) - 1, reply, cap);
|
||||||
|
} else if (strcmp(line, REBOOT) == 0) {
|
||||||
|
write_line("\n@ok\n");
|
||||||
|
usb_serial_jtag_wait_tx_done(pdMS_TO_TICKS(200));
|
||||||
|
vTaskDelay(pdMS_TO_TICKS(100));
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
// Anything else (a stray keypress in a monitor) is ignored
|
||||||
|
}
|
||||||
|
|
||||||
|
static void usb_cfg_task(void *)
|
||||||
|
{
|
||||||
|
char *line = (char *)malloc(WEB_API_MSG_MAX + 1);
|
||||||
|
char *reply = (char *)malloc(WEB_API_REPLY_MAX);
|
||||||
|
if (!line || !reply) {
|
||||||
|
ESP_LOGE(TAG, "out of memory");
|
||||||
|
vTaskDelete(NULL);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
size_t len = 0;
|
||||||
|
bool overflow = false; // the current line is too long: drop it up to its newline
|
||||||
|
uint8_t buf[64];
|
||||||
|
for (;;) {
|
||||||
|
int got = usb_serial_jtag_read_bytes(buf, sizeof(buf), portMAX_DELAY);
|
||||||
|
for (int i = 0; i < got; i++) {
|
||||||
|
char c = (char)buf[i];
|
||||||
|
if (c == '\n') {
|
||||||
|
if (!overflow) {
|
||||||
|
line[len] = '\0';
|
||||||
|
handle_line(line, reply, WEB_API_REPLY_MAX);
|
||||||
|
}
|
||||||
|
len = 0;
|
||||||
|
overflow = false;
|
||||||
|
} else if (!overflow) {
|
||||||
|
if (len < WEB_API_MSG_MAX) {
|
||||||
|
line[len++] = c;
|
||||||
|
} else {
|
||||||
|
overflow = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
esp_err_t usb_cfg_start(void)
|
||||||
|
{
|
||||||
|
usb_serial_jtag_driver_config_t cfg = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT();
|
||||||
|
cfg.rx_buffer_size = 1024;
|
||||||
|
cfg.tx_buffer_size = 2048;
|
||||||
|
esp_err_t err = usb_serial_jtag_driver_install(&cfg);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
ESP_LOGE(TAG, "USB serial driver install failed: %s", esp_err_to_name(err));
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
// Logs go through the driver too, so they and the replies share one queue
|
||||||
|
usb_serial_jtag_vfs_use_driver();
|
||||||
|
s_tx_lock = xSemaphoreCreateMutex();
|
||||||
|
if (!s_tx_lock) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_log_vprintf = esp_log_set_vprintf(log_vprintf);
|
||||||
|
if (xTaskCreate(usb_cfg_task, "usb_cfg", 6144, NULL, 4, NULL) != pdPASS) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "Config API on the USB serial port");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Serve the JSON API on the USB serial port (USB-Serial-JTAG), for led-tool.
|
||||||
|
*
|
||||||
|
* One request per line, one reply per line; every other line on the port is log output:
|
||||||
|
* @api {"id": n, "method": "GET" or "POST", "path": "/api/...", "body": ..., "host": optional}
|
||||||
|
* -> @api {"id": n, "status": 200, "body": "<JSON text>"}
|
||||||
|
* @reboot -> @ok, then the device restarts
|
||||||
|
*/
|
||||||
|
esp_err_t usb_cfg_start(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
+35
-2
@@ -12,6 +12,8 @@
|
|||||||
#include "esp_log.h"
|
#include "esp_log.h"
|
||||||
#include "esp_netif.h"
|
#include "esp_netif.h"
|
||||||
#include "esp_timer.h"
|
#include "esp_timer.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/semphr.h"
|
||||||
#include <netinet/tcp.h>
|
#include <netinet/tcp.h>
|
||||||
#include <sys/socket.h>
|
#include <sys/socket.h>
|
||||||
#include "esp_wifi.h"
|
#include "esp_wifi.h"
|
||||||
@@ -1160,8 +1162,8 @@ static esp_err_t api_http_entry(httpd_req_t *req)
|
|||||||
return reinterpret_cast<api_fn_t>(req->user_ctx)(&a);
|
return reinterpret_cast<api_fn_t>(req->user_ctx)(&a);
|
||||||
}
|
}
|
||||||
|
|
||||||
#define WS_MSG_MAX 2048 // a request message
|
#define WS_MSG_MAX WEB_API_MSG_MAX
|
||||||
#define WS_REPLY_MAX 8192 // a reply envelope
|
#define WS_REPLY_MAX WEB_API_REPLY_MAX
|
||||||
|
|
||||||
// Run an API route on this driver: target is the path, optionally with a query string.
|
// Run an API route on this driver: target is the path, optionally with a query string.
|
||||||
static void ws_local(const char *method, const char *target, const char *body, char *out, size_t cap)
|
static void ws_local(const char *method, const char *target, const char *body, char *out, size_t cap)
|
||||||
@@ -1234,6 +1236,37 @@ static void ws_dispatch(const char *msg, char *out, size_t cap)
|
|||||||
cJSON_Delete(top);
|
cJSON_Delete(top);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A call from outside the HTTP server (the USB config port). It runs on the server's own task, so it
|
||||||
|
// never races an HTTP or WebSocket handler (the preset list has no lock of its own).
|
||||||
|
struct api_call_t {
|
||||||
|
const char *msg;
|
||||||
|
char *out;
|
||||||
|
size_t cap;
|
||||||
|
SemaphoreHandle_t done;
|
||||||
|
};
|
||||||
|
|
||||||
|
static void api_call_work(void *arg)
|
||||||
|
{
|
||||||
|
api_call_t *c = static_cast<api_call_t *>(arg);
|
||||||
|
ws_dispatch(c->msg, c->out, c->cap);
|
||||||
|
xSemaphoreGive(c->done);
|
||||||
|
}
|
||||||
|
|
||||||
|
void web_api_call(const char *msg, char *out, size_t cap)
|
||||||
|
{
|
||||||
|
api_call_t c = { msg, out, cap, xSemaphoreCreateBinary() };
|
||||||
|
if (!s_server || !c.done) {
|
||||||
|
envelope(out, cap, 503, "{\"error\":\"web server not running\"}");
|
||||||
|
} else if (httpd_queue_work(s_server, api_call_work, &c) != ESP_OK) {
|
||||||
|
envelope(out, cap, 503, "{\"error\":\"server busy\"}");
|
||||||
|
} else {
|
||||||
|
xSemaphoreTake(c.done, portMAX_DELAY);
|
||||||
|
}
|
||||||
|
if (c.done) {
|
||||||
|
vSemaphoreDelete(c.done);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// WebSocket handler: one text frame in, one text frame out
|
// WebSocket handler: one text frame in, one text frame out
|
||||||
// Another site's page must not drive this driver. A browser sends its Origin with the WebSocket
|
// Another site's page must not drive this driver. A browser sends its Origin with the WebSocket
|
||||||
// handshake, and only a page from the LAN (or this device) may open the socket. ESP-IDF has no hook
|
// handshake, and only a page from the LAN (or this device) may open the socket. ESP-IDF has no hook
|
||||||
|
|||||||
+10
@@ -10,6 +10,9 @@
|
|||||||
extern "C" {
|
extern "C" {
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#define WEB_API_MSG_MAX 2048 // a request message: {"method","path","body","host"}
|
||||||
|
#define WEB_API_REPLY_MAX 8192 // a reply envelope: {"status","body"}
|
||||||
|
|
||||||
/** @brief Start the HTTP server on port 80 (UI and JSON API). */
|
/** @brief Start the HTTP server on port 80 (UI and JSON API). */
|
||||||
esp_err_t web_start(void);
|
esp_err_t web_start(void);
|
||||||
|
|
||||||
@@ -19,6 +22,13 @@ esp_err_t web_start(void);
|
|||||||
*/
|
*/
|
||||||
void web_allow_lan_origin(httpd_req_t *req);
|
void web_allow_lan_origin(httpd_req_t *req);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Run one API request without HTTP, as the WebSocket does: msg is
|
||||||
|
* {"method": "GET" or "POST", "path": "/api/...", "body": ..., "host": optional relay target}.
|
||||||
|
* out gets the envelope {"status": n, "body": "<JSON text>"}. Used by the USB config port.
|
||||||
|
*/
|
||||||
|
void web_api_call(const char *msg, char *out, size_t cap);
|
||||||
|
|
||||||
#ifdef __cplusplus
|
#ifdef __cplusplus
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -9,3 +9,5 @@ CONFIG_PARTITION_TABLE_CUSTOM=y
|
|||||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||||
# mDNS opens sockets on both the AP and client interfaces, plus HTTP and DDP. The default 10 runs out and httpd stops accepting.
|
# mDNS opens sockets on both the AP and client interfaces, plus HTTP and DDP. The default 10 runs out and httpd stops accepting.
|
||||||
CONFIG_LWIP_MAX_SOCKETS=16
|
CONFIG_LWIP_MAX_SOCKETS=16
|
||||||
|
# Primary console on the C3's built-in USB (/dev/ttyACM0): logs and the led-tool config API (usb_cfg.cpp) share it
|
||||||
|
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
|
||||||
+557
-41
@@ -2,19 +2,26 @@
|
|||||||
"""
|
"""
|
||||||
Test the LED driver's DDP receiver (UDP port 4048) and its frame sync (UDP broadcast port 4049).
|
Test the LED driver's DDP receiver (UDP port 4048) and its frame sync (UDP broadcast port 4049).
|
||||||
|
|
||||||
Every frame goes to each device as unicast DDP: a version 1 header, the pixel data split across two
|
Every frame goes to each device as unicast DDP: a version 1 header and the whole frame in one
|
||||||
packets, and the PUSH flag on the last packet. After each tick, one broadcast sync ("LSY1" + seq) tells
|
packet, with the PUSH flag set (the one-off checks in the full test still send two packets). After each tick one broadcast
|
||||||
all devices to show the frame they hold. The devices are driven together, from one sender. Through the
|
("LSY1" + seq) tells all devices to show the frame they hold. The interactive and soak modes send it a tick after the frames
|
||||||
|
(so even a slow device has its frame by then) and do not wait for acks; the full test (no flags) waits for each device's ack first. The devices are driven together, from one sender. Through the
|
||||||
driver's HTTP API the test checks that the pixels were shown, that a frame waits for a sync, runs a few
|
driver's HTTP API the test checks that the pixels were shown, that a frame waits for a sync, runs a few
|
||||||
test animations, and that the pattern comes back once the pixels stop.
|
test animations, and that the last frame stays up once the pixels stop.
|
||||||
|
|
||||||
python3 tools/ddp_test.py # finds every device on this machine's subnet (/24)
|
python3 tools/ddp_test.py # finds every device on this machine's subnet (/24)
|
||||||
python3 tools/ddp_test.py --subnet=192.168.4 # or pick the subnet
|
python3 tools/ddp_test.py --subnet=192.168.4 # pick the network: devices are found on it and the sync goes to its broadcast address (192.168.4.255)
|
||||||
|
python3 tools/ddp_test.py --fps=30 # frames per second (default 60)
|
||||||
|
python3 tools/ddp_test.py --brightness=20 # send the colours at 20% (default and maximum 25)
|
||||||
|
python3 tools/ddp_test.py --interactive # pick patterns from a menu and watch them on the rig
|
||||||
|
python3 tools/ddp_test.py --soak=600 # long run: cycle the soak patterns for 600 s, sampling LEDs as it goes
|
||||||
python3 tools/ddp_test.py led1.local led2.local # or name hosts explicitly
|
python3 tools/ddp_test.py led1.local led2.local # or name hosts explicitly
|
||||||
python3 tools/ddp_test.py led1.local --serial=/dev/ttyACM0 # also check the serial log (one host only)
|
python3 tools/ddp_test.py led1.local --serial=/dev/ttyACM0 # also check the serial log (one host only)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
import colorsys
|
import colorsys
|
||||||
|
import random
|
||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import re
|
import re
|
||||||
@@ -32,12 +39,24 @@ LEDS = 119
|
|||||||
PUSH = 0x01
|
PUSH = 0x01
|
||||||
VER1 = 0x40
|
VER1 = 0x40
|
||||||
RGB = 0x01
|
RGB = 0x01
|
||||||
TICK = 0.025 # seconds between ticks (40 fps)
|
FPS = 60 # frames per second (--fps=N)
|
||||||
ACK_WAIT = 0.02 # seconds to wait for each device's ack before the sync goes out anyway
|
TICK = 1 / FPS # seconds between ticks
|
||||||
ANIM_FRAMES = 40 # about 1 s
|
ACK_WAIT = TICK * 0.6 # seconds to wait for each device's ack before the sync goes out anyway
|
||||||
|
ANIM_FRAMES = 40 # frames of each test animation
|
||||||
|
|
||||||
|
|
||||||
|
def set_fps(fps):
|
||||||
|
global FPS, TICK, ACK_WAIT
|
||||||
|
FPS = fps
|
||||||
|
TICK = 1 / fps
|
||||||
|
ACK_WAIT = TICK * 0.6
|
||||||
|
|
||||||
|
|
||||||
def packet(seq, offset, data, push):
|
def packet(seq, offset, data, push):
|
||||||
|
"""Every DDP packet is built here, so this is the hard limit: no byte leaves above the brightness cap,
|
||||||
|
whatever the pattern, the test or a bug upstream put in it."""
|
||||||
|
top = 255 * MAX_BRIGHTNESS // 100
|
||||||
|
data = data.translate(bytes(min(i, top) for i in range(256)))
|
||||||
flags = VER1 | (PUSH if push else 0)
|
flags = VER1 | (PUSH if push else 0)
|
||||||
header = struct.pack(">BBBBIH", flags, seq & 0x0F, RGB, 1, offset, len(data))
|
header = struct.pack(">BBBBIH", flags, seq & 0x0F, RGB, 1, offset, len(data))
|
||||||
return header + data
|
return header + data
|
||||||
@@ -51,9 +70,9 @@ def send_frame(sock, host, pixels, seq):
|
|||||||
sock.sendto(packet(seq, split, raw[split:], True), (host, PORT))
|
sock.sendto(packet(seq, split, raw[split:], True), (host, PORT))
|
||||||
|
|
||||||
|
|
||||||
def send_sync(sock, seq):
|
def send_sync(sock, seq, broadcast):
|
||||||
"""Broadcast a sync: every device shows the frame it holds."""
|
"""Broadcast a sync to the network's broadcast address: every device shows the frame it holds."""
|
||||||
sock.sendto(b"LSY1" + struct.pack(">I", seq & 0xFFFFFFFF), ("255.255.255.255", SYNC_PORT))
|
sock.sendto(b"LSY1" + struct.pack(">I", seq & 0xFFFFFFFF), (broadcast, SYNC_PORT))
|
||||||
|
|
||||||
|
|
||||||
def frame_sum(pixels):
|
def frame_sum(pixels):
|
||||||
@@ -122,9 +141,17 @@ def anim_breathe(i, k):
|
|||||||
ANIMATIONS = {"chase": anim_chase, "rainbow": anim_rainbow, "breathe": anim_breathe}
|
ANIMATIONS = {"chase": anim_chase, "rainbow": anim_rainbow, "breathe": anim_breathe}
|
||||||
|
|
||||||
|
|
||||||
|
MAX_BRIGHTNESS = 25 # percent: the test never sends brighter than this, whatever --brightness asks for (the PSU trips above it)
|
||||||
|
BRIGHTNESS = MAX_BRIGHTNESS # percent: the colours the test sends are scaled to this (--brightness=20)
|
||||||
|
|
||||||
|
|
||||||
|
def dim(px):
|
||||||
|
return tuple(c * min(BRIGHTNESS, MAX_BRIGHTNESS) // 100 for c in px)
|
||||||
|
|
||||||
|
|
||||||
def frame(k):
|
def frame(k):
|
||||||
"""A frame: LED i is a colour that depends on i, so every LED is distinguishable."""
|
"""A frame: LED i is a colour that depends on i, so every LED is distinguishable."""
|
||||||
return [((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256) for i in range(LEDS)]
|
return [dim(((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256)) for i in range(LEDS)]
|
||||||
|
|
||||||
|
|
||||||
def output_scale(host):
|
def output_scale(host):
|
||||||
@@ -148,17 +175,24 @@ class Sender:
|
|||||||
"""Drives every device from one thread. Each tick sends each device its current frame (unicast),
|
"""Drives every device from one thread. Each tick sends each device its current frame (unicast),
|
||||||
then one sync broadcast that all devices show their frame on."""
|
then one sync broadcast that all devices show their frame on."""
|
||||||
|
|
||||||
def __init__(self, sock, hosts):
|
def __init__(self, sock, hosts, broadcast, sync=True, acks=False):
|
||||||
|
self.sync = sync # broadcast a sync after each frame, so every device shows it together (else: on its PUSH)
|
||||||
|
self.acks = acks # also wait for each device's ack before the sync (the full test; costs a wait per tick)
|
||||||
self.sock = sock
|
self.sock = sock
|
||||||
self.hosts = hosts
|
self.hosts = hosts
|
||||||
|
self.broadcast = broadcast
|
||||||
self.ip_of = {h: socket.gethostbyname(h) for h in hosts}
|
self.ip_of = {h: socket.gethostbyname(h) for h in hosts}
|
||||||
self.host_of = {ip: h for h, ip in self.ip_of.items()}
|
self.host_of = {ip: h for h, ip in self.ip_of.items()}
|
||||||
self.missed = {h: 0 for h in hosts} # frames a device did not ack in time
|
self.missed = {h: 0 for h in hosts} # frames a device did not ack in time
|
||||||
self.sock.settimeout(ACK_WAIT)
|
self.sock.setblocking(False) # asyncio drives the socket
|
||||||
self.frames = {h: None for h in hosts}
|
self.frames = {h: None for h in hosts}
|
||||||
|
self.pending_sync = None # seq of the last frames sent, whose sync goes out at the start of the next tick
|
||||||
|
self.late = set() # devices that did not ack the last frame: skipped once, so their queue can drain
|
||||||
|
self.skipped = {h: 0 for h in hosts}
|
||||||
self.seq = 0
|
self.seq = 0
|
||||||
self.paused = False
|
self.paused = False
|
||||||
self.lock = threading.Lock()
|
self.lock = threading.Lock()
|
||||||
|
self.tick_event = threading.Event() # set at the start of every tick: the pattern thread paces on it
|
||||||
self.stop_event = threading.Event()
|
self.stop_event = threading.Event()
|
||||||
self.thread = threading.Thread(target=self._run, daemon=True)
|
self.thread = threading.Thread(target=self._run, daemon=True)
|
||||||
|
|
||||||
@@ -166,44 +200,83 @@ class Sender:
|
|||||||
with self.lock:
|
with self.lock:
|
||||||
self.frames.update(pixels_by_host)
|
self.frames.update(pixels_by_host)
|
||||||
|
|
||||||
def tick(self):
|
async def send_host(self, loop, h, pixels, seq):
|
||||||
|
"""Send one device its whole frame in one packet, with PUSH set; each device is sent to on its own."""
|
||||||
|
raw = bytes(c for px in pixels for c in px)
|
||||||
|
await loop.sock_sendto(self.sock, packet(seq, 0, raw, True), (h, PORT))
|
||||||
|
|
||||||
|
def wait_tick(self):
|
||||||
|
"""Block until the next tick starts. Pattern threads call this instead of sleeping, so exactly one new
|
||||||
|
frame is made per tick: two separate 60 Hz clocks drift against each other and beat, which shows as
|
||||||
|
repeated and skipped frames (judder)."""
|
||||||
|
self.tick_event.wait(1.0)
|
||||||
|
self.tick_event.clear()
|
||||||
|
|
||||||
|
async def tick(self, loop):
|
||||||
|
t0 = time.monotonic()
|
||||||
with self.lock:
|
with self.lock:
|
||||||
frames = dict(self.frames)
|
frames = dict(self.frames)
|
||||||
|
self.tick_event.set() # the frame just taken goes out now; the pattern thread makes the next one
|
||||||
self.seq = (self.seq + 1) & 0xFFFFFFFF
|
self.seq = (self.seq + 1) & 0xFFFFFFFF
|
||||||
sent = [h for h in self.hosts if frames[h] is not None]
|
due = [h for h in self.hosts if frames[h] is not None]
|
||||||
for h in sent:
|
if not self.acks:
|
||||||
send_frame(self.sock, h, frames[h], self.seq)
|
# Without acks the sender can't tell when a frame has landed, and a broadcast goes out at once
|
||||||
self.wait_acks(self.seq & 0x0F, sent)
|
# while unicast frames queue behind each other and the air, so a sync straight after the frames
|
||||||
send_sync(self.sock, self.seq)
|
# can beat the slowest device's frame (it then shows a frame late and falls out of line). So the
|
||||||
|
# sync for the last tick's frames goes out at the start of this tick, a whole tick after them.
|
||||||
|
if self.sync and self.pending_sync is not None:
|
||||||
|
send_sync(self.sock, self.pending_sync, self.broadcast)
|
||||||
|
await asyncio.gather(*(self.send_host(loop, h, frames[h], self.seq) for h in due))
|
||||||
|
self.pending_sync = self.seq
|
||||||
|
return
|
||||||
|
sent = [h for h in due if h not in self.late]
|
||||||
|
for h in due:
|
||||||
|
if h in self.late:
|
||||||
|
self.skipped[h] += 1 # still catching up: send it nothing this tick rather than queue more
|
||||||
|
self.late = set()
|
||||||
|
await asyncio.gather(*(self.send_host(loop, h, frames[h], self.seq) for h in sent))
|
||||||
|
self.late = await self.wait_acks(loop, self.seq & 0x0F, sent)
|
||||||
|
rest = t0 + ACK_WAIT - time.monotonic()
|
||||||
|
if rest > 0:
|
||||||
|
await asyncio.sleep(rest) # sync at a fixed point in the tick, so quick or slow acks don't move it
|
||||||
|
send_sync(self.sock, self.seq, self.broadcast)
|
||||||
|
|
||||||
def wait_acks(self, nibble, hosts):
|
async def wait_acks(self, loop, nibble, hosts):
|
||||||
"""Wait until each device acks this frame (the driver acks a completed frame with "LAK1" and its
|
"""Wait until each device acks this frame (the driver acks a completed frame with "LAK1" and its
|
||||||
DDP seq), up to ACK_WAIT. Devices that do not ack in time are counted as missed."""
|
DDP seq), up to ACK_WAIT. Devices that do not ack in time are counted as missed."""
|
||||||
waiting = {self.ip_of[h] for h in hosts}
|
waiting = {self.ip_of[h] for h in hosts}
|
||||||
deadline = time.time() + ACK_WAIT
|
|
||||||
while waiting and time.time() < deadline:
|
async def collect():
|
||||||
try:
|
while waiting:
|
||||||
data, addr = self.sock.recvfrom(64)
|
data, addr = await loop.sock_recvfrom(self.sock, 64)
|
||||||
except OSError:
|
if data[:4] == b"LAK1" and len(data) >= 5 and (data[4] & 0x0F) == nibble:
|
||||||
continue
|
waiting.discard(addr[0])
|
||||||
if data[:4] == b"LAK1" and len(data) >= 5 and (data[4] & 0x0F) == nibble:
|
|
||||||
waiting.discard(addr[0])
|
try:
|
||||||
|
await asyncio.wait_for(collect(), ACK_WAIT)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
pass
|
||||||
for ip in waiting:
|
for ip in waiting:
|
||||||
self.missed[self.host_of[ip]] += 1
|
self.missed[self.host_of[ip]] += 1
|
||||||
|
return {self.host_of[ip] for ip in waiting}
|
||||||
|
|
||||||
def _run(self):
|
async def _loop(self):
|
||||||
# Fixed rate: ticks start every TICK seconds on a schedule, so the ack waits don't stretch the rate
|
# Fixed rate: ticks start every TICK seconds on a schedule, so the ack waits don't stretch the rate
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
next_tick = time.monotonic()
|
next_tick = time.monotonic()
|
||||||
while not self.stop_event.is_set():
|
while not self.stop_event.is_set():
|
||||||
if not self.paused:
|
if not self.paused:
|
||||||
self.tick()
|
await self.tick(loop)
|
||||||
next_tick += TICK
|
next_tick += TICK
|
||||||
delay = next_tick - time.monotonic()
|
delay = next_tick - time.monotonic()
|
||||||
if delay > 0:
|
if delay > 0:
|
||||||
time.sleep(delay)
|
await asyncio.sleep(delay)
|
||||||
else:
|
else:
|
||||||
next_tick = time.monotonic() # fell behind: start the schedule again from now
|
next_tick = time.monotonic() # fell behind: start the schedule again from now
|
||||||
|
|
||||||
|
def _run(self):
|
||||||
|
asyncio.run(self._loop())
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
self.thread.start()
|
self.thread.start()
|
||||||
|
|
||||||
@@ -212,7 +285,438 @@ class Sender:
|
|||||||
self.thread.join()
|
self.thread.join()
|
||||||
|
|
||||||
|
|
||||||
def run_all(hosts, serial_port):
|
# Long-running patterns for --soak. Each maps (position, frame number, total) to an RGB colour, where
|
||||||
|
# position runs along the whole rig: the bars are laid end to end in host order, `total` LEDs long, so a
|
||||||
|
# pattern travels across the bars and not just along each one. Each is smooth enough that a frame is near
|
||||||
|
# the one before it.
|
||||||
|
def soak_rainbow_scroll(i, k, n):
|
||||||
|
r, g, b = colorsys.hsv_to_rgb((i / n + k / 400) % 1.0, 1, 1)
|
||||||
|
return (int(r * 255), int(g * 255), int(b * 255))
|
||||||
|
|
||||||
|
|
||||||
|
def soak_plasma(i, k, n):
|
||||||
|
v = math.sin(i / 23 + k / 17) + math.sin(i / 9 - k / 11) + math.sin((i + k / 3) / 41)
|
||||||
|
r, g, b = colorsys.hsv_to_rgb((v / 6 + 0.5 + k / 900) % 1.0, 1, 1)
|
||||||
|
return (int(r * 255), int(g * 255), int(b * 255))
|
||||||
|
|
||||||
|
|
||||||
|
def soak_comet(i, k, n):
|
||||||
|
head = (k // 2) % (n * 2)
|
||||||
|
head = head if head < n else 2 * n - 1 - head # bounces from the first bar to the last and back
|
||||||
|
v = max(0, 255 - abs(i - head) * 25)
|
||||||
|
return (v, v // 2, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_color_wipe(i, k, n):
|
||||||
|
m = (k // 2) % (n * 2)
|
||||||
|
on = i < m if m <= n else i >= m - n
|
||||||
|
r, g, b = colorsys.hsv_to_rgb(((k // (n * 4)) * 0.17) % 1.0, 1, 1)
|
||||||
|
return (int(r * 255), int(g * 255), int(b * 255)) if on else (0, 0, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_sparkle(i, k, n):
|
||||||
|
rng = random.Random(i * 7919 + k // 4)
|
||||||
|
return (255, 255, 255) if rng.random() < 0.06 else (0, 0, 20)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_gradient_sweep(i, k, n):
|
||||||
|
t = (i / n * 2 + k / 120) % 1.0
|
||||||
|
return (int(255 * t), int(255 * (1 - t)), 128)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_slow_breathe(i, k, n):
|
||||||
|
v = int(127.5 * (1 - math.cos(k / 40 + i / (n / 6)))) # a slow wave over the rig
|
||||||
|
return (v, v // 3, 255 - v)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_bar_chase(i, k, n):
|
||||||
|
bar = (k // 30) % max(1, n // LEDS) # one whole bar lit at a time, 0.75 s each, in order
|
||||||
|
return (0, 200, 255) if i // LEDS == bar else (0, 0, 10)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_ripple(i, k, n):
|
||||||
|
d = abs(i - n / 2) # rings out from the middle of the rig, so the two ends mirror each other
|
||||||
|
v = int(127.5 * (1 + math.sin(d / 6 - k / 5)))
|
||||||
|
return (v, 0, 255 - v)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_strobe(i, k, n):
|
||||||
|
return (255, 255, 255) if (k // 20) % 2 else (0, 0, 0) # a flash every 0.5 s: a hard test for dropped frames
|
||||||
|
|
||||||
|
# Rig-shaped patterns. The bars are 2 columns x 8 rows. In host order the left column comes first (hosts
|
||||||
|
# 101-108, top row to bottom), then the right column (109-116): bar b is in column b // rows, row b % rows.
|
||||||
|
# The data-in heads are in the middle, so LED 0 of each bar is at the centre and LED 118 at the outer end:
|
||||||
|
# left bars run out to the left, right bars out to the right. With fewer hosts the rows just run out
|
||||||
|
# sooner (one host is one left bar).
|
||||||
|
ROW_GAP = 10 # LEDs of distance between neighbouring rows, so a diagonal looks about right
|
||||||
|
|
||||||
|
|
||||||
|
def rig_rows(n):
|
||||||
|
return max(1, (n // LEDS + 1) // 2)
|
||||||
|
|
||||||
|
|
||||||
|
def rig_xy(i, n):
|
||||||
|
"""(x, y, rows) of LED i of n: x is LEDs from the centre (negative on the left), y is the row in LEDs."""
|
||||||
|
rows = rig_rows(n)
|
||||||
|
bar, led = divmod(i, LEDS)
|
||||||
|
x = led + 0.5
|
||||||
|
return (x if bar // rows else -x), (bar % rows) * ROW_GAP, rows
|
||||||
|
|
||||||
|
|
||||||
|
def hsv(h, s=1.0, v=1.0):
|
||||||
|
r, g, b = colorsys.hsv_to_rgb(h % 1.0, s, v)
|
||||||
|
return (int(r * 255), int(g * 255), int(b * 255))
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_sweep(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a vertical band sweeping from the left end to the right end and back
|
||||||
|
pos = (math.sin(k / 40) * 0.5 + 0.5) * 2 * LEDS - LEDS
|
||||||
|
v = max(0, 255 - int(abs(x - pos) * 12))
|
||||||
|
return (0, v, v // 3)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_row_scan(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a horizontal band scanning down the rows and back up
|
||||||
|
span = max(1, rows - 1) * ROW_GAP
|
||||||
|
pos = (math.sin(k / 50) * 0.5 + 0.5) * span
|
||||||
|
v = max(0, 255 - int(abs(y - pos) * 25))
|
||||||
|
return (v, v // 4, v)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_ripple(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # rings out from the middle of the rig, through the rows
|
||||||
|
d = math.hypot(x, y - (rows - 1) * ROW_GAP / 2)
|
||||||
|
return hsv(0.6 + 0.2 * math.sin(d / 20 - k / 30), 1, 0.5 + 0.5 * math.sin(d / 5 - k / 4))
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_converge(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # pulses run in from both outer ends to the heads, then back out
|
||||||
|
ph = (k // 3) % (LEDS * 2)
|
||||||
|
pos = LEDS - ph if ph < LEDS else ph - LEDS
|
||||||
|
v = max(0, 255 - int(abs(abs(x) - pos) * 20))
|
||||||
|
return (v, v // 2, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_rows_chase(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # one row lit at a time, 0.5 s each, a different hue per lap
|
||||||
|
row = int(y // ROW_GAP)
|
||||||
|
cur = (k // 20) % rows
|
||||||
|
lap = (k // 20) // rows
|
||||||
|
return hsv(lap * 0.13, 1, 1) if row == cur else (0, 0, 8)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_columns(i, k, n):
|
||||||
|
right = (i // LEDS) // rig_rows(n) # left and right columns take turns, 0.5 s each
|
||||||
|
return (255, 40, 0) if right == (k // 20) % 2 else (0, 40, 255)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_checker(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a checkerboard of 20 LED cells that flips every 0.75 s
|
||||||
|
cell = int(abs(x) // 20) + int(x < 0) + int(y // ROW_GAP)
|
||||||
|
return (255, 255, 255) if (cell + k // 30) % 2 else (0, 0, 30)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_diagonal(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a rainbow whose bands slant across the rows and both columns
|
||||||
|
return hsv((x + y * 2) / 300 - k / 200)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_scanner(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a bar across every row that bounces between the outer ends, with a tail
|
||||||
|
ph = (k // 2) % (4 * LEDS)
|
||||||
|
going_right = ph < 2 * LEDS
|
||||||
|
pos = ph - LEDS if going_right else 3 * LEDS - ph
|
||||||
|
behind = (pos - x) if going_right else (x - pos) # positive: this LED is in the tail
|
||||||
|
v = max(0, 255 - int(abs(behind) * (6 if behind > 0 else 40)))
|
||||||
|
return (v, 0, v // 5)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_row_rainbow(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # each row its own hue, the hues turning, brightest at the heads
|
||||||
|
return hsv(y / (ROW_GAP * max(1, rows)) + k / 300, 1, 1 - abs(x) / (LEDS * 1.5))
|
||||||
|
|
||||||
|
|
||||||
|
# 2D patterns: they treat the rig as a flat picture (x across, y down the rows) rather than as separate bars.
|
||||||
|
SLANT = 3 # LEDs of x per row for the diagonals, so a band crosses the rig at roughly 45 degrees on screen
|
||||||
|
|
||||||
|
|
||||||
|
def rig_mid(rows):
|
||||||
|
return (rows - 1) * ROW_GAP / 2
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_diag_sweep(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a slanted band that sweeps from the top-left corner to the bottom-right and wraps
|
||||||
|
lo, hi = -LEDS, LEDS + (rows - 1) * ROW_GAP * SLANT
|
||||||
|
d = x + y * SLANT
|
||||||
|
pos = lo + (k * 1.5) % (hi - lo + 60)
|
||||||
|
v = max(0, 255 - int(abs(d - pos) * 10))
|
||||||
|
return (v, v // 3, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_diag_bounce(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # the other slant, bouncing back and forth with a soft fade-out behind it
|
||||||
|
lo, hi = -LEDS - (rows - 1) * ROW_GAP * SLANT, LEDS
|
||||||
|
d = x - y * SLANT
|
||||||
|
t = (k * 1.5) % (2 * (hi - lo))
|
||||||
|
pos = lo + (t if t < hi - lo else 2 * (hi - lo) - t)
|
||||||
|
v = max(0, 255 - int(abs(d - pos) * 9))
|
||||||
|
return (0, v // 3, v)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_radar(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a line turning round the middle of the rig like a radar, with a fading tail
|
||||||
|
ang = math.atan2((y - rig_mid(rows)) * 3, x) # y is stretched so the turn looks round
|
||||||
|
sweep = (k / 40) % (2 * math.pi)
|
||||||
|
behind = (sweep - ang) % (2 * math.pi)
|
||||||
|
v = max(0, 255 - int(behind * 70))
|
||||||
|
return (0, v, v // 6)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_spiral(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # colour arms that wind out from the middle and turn
|
||||||
|
dy = (y - rig_mid(rows)) * 3
|
||||||
|
ang = math.atan2(dy, x)
|
||||||
|
r = math.hypot(x, dy)
|
||||||
|
return hsv(ang / (2 * math.pi) * 2 + r / 150 - k / 120, 1, 0.5 + 0.5 * math.sin(ang * 3 + r / 10 - k / 8))
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_diamond(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # diamond outlines (taxicab distance) that grow out of the middle
|
||||||
|
d = abs(x) + abs(y - rig_mid(rows)) * 2
|
||||||
|
behind = (k * 1.2 - d) % 50 # distance behind the nearest ring front
|
||||||
|
v = max(0, 255 - int(behind * 8))
|
||||||
|
return (v, 0, v // 2)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_corners(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a spot that runs round the four corners of the rig, one after another
|
||||||
|
corners = [(-LEDS, 0), (LEDS, 0), (LEDS, (rows - 1) * ROW_GAP), (-LEDS, (rows - 1) * ROW_GAP)]
|
||||||
|
t = k / 60
|
||||||
|
a, b = corners[int(t) % 4], corners[(int(t) + 1) % 4]
|
||||||
|
f = t - int(t)
|
||||||
|
cx, cy = a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f
|
||||||
|
d = math.hypot(x - cx, (y - cy) * 3)
|
||||||
|
v = max(0, 255 - int(d * 9))
|
||||||
|
return (v, v, v // 4)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_plasma2d(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a slow plasma that really varies in both directions
|
||||||
|
v = math.sin(x / 25 + k / 50) + math.sin(y / 6 - k / 70) + math.sin((x + y * 2) / 30 + k / 90)
|
||||||
|
return hsv(0.5 + v / 6, 1, 0.5 + 0.5 * math.sin(v * 1.5))
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_bounce(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # a ball bouncing round the rig, off the edges, with a hue that changes at each bounce
|
||||||
|
w, h = 2 * LEDS, max(1, (rows - 1) * ROW_GAP)
|
||||||
|
|
||||||
|
def tri(t, size): # triangle wave 0..size..0
|
||||||
|
t %= 2 * size
|
||||||
|
return t if t < size else 2 * size - t
|
||||||
|
|
||||||
|
bx = tri(k * 1.7, w) - LEDS
|
||||||
|
by = tri(k * 0.55 + 20, h)
|
||||||
|
hue = int(k * 1.7 / w) * 0.17 + int((k * 0.55 + 20) / h) * 0.31
|
||||||
|
v = max(0, 255 - int(math.hypot(x - bx, (y - by) * 2.5) * 12))
|
||||||
|
return hsv(hue, 1, v / 255)
|
||||||
|
|
||||||
|
|
||||||
|
def soak_rig_rain(i, k, n):
|
||||||
|
x, y, rows = rig_xy(i, n) # drops falling down the rows at different speeds, one lane per 8 LEDs of x
|
||||||
|
lane = int(x // 8)
|
||||||
|
speed = 0.04 + (lane * 7 % 5) * 0.015 # rows per frame
|
||||||
|
span = rows + 4
|
||||||
|
head = (k * speed + lane * 3.7) % span - 2
|
||||||
|
fall = head - y / ROW_GAP # positive: the LED is in the tail above the drop
|
||||||
|
v = max(0, 255 - int(abs(fall) * 160)) if fall >= 0 else 0
|
||||||
|
return (v // 4, v // 2, v)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
SOAK = {
|
||||||
|
"rainbow scroll": soak_rainbow_scroll,
|
||||||
|
"plasma": soak_plasma,
|
||||||
|
"comet": soak_comet,
|
||||||
|
"color wipe": soak_color_wipe,
|
||||||
|
"sparkle": soak_sparkle,
|
||||||
|
"gradient sweep": soak_gradient_sweep,
|
||||||
|
"slow breathe": soak_slow_breathe,
|
||||||
|
"bar chase": soak_bar_chase,
|
||||||
|
"ripple": soak_ripple,
|
||||||
|
"strobe": soak_strobe,
|
||||||
|
"rig sweep": soak_rig_sweep,
|
||||||
|
"rig row scan": soak_rig_row_scan,
|
||||||
|
"rig ripple": soak_rig_ripple,
|
||||||
|
"rig converge": soak_rig_converge,
|
||||||
|
"rig rows chase": soak_rig_rows_chase,
|
||||||
|
"rig columns": soak_rig_columns,
|
||||||
|
"rig checker": soak_rig_checker,
|
||||||
|
"rig diagonal": soak_rig_diagonal,
|
||||||
|
"rig scanner": soak_rig_scanner,
|
||||||
|
"rig row rainbow": soak_rig_row_rainbow,
|
||||||
|
"2d diagonal sweep": soak_rig_diag_sweep,
|
||||||
|
"2d diagonal bounce": soak_rig_diag_bounce,
|
||||||
|
"2d radar": soak_rig_radar,
|
||||||
|
"2d spiral": soak_rig_spiral,
|
||||||
|
"2d diamonds": soak_rig_diamond,
|
||||||
|
"2d corners": soak_rig_corners,
|
||||||
|
"2d plasma": soak_rig_plasma2d,
|
||||||
|
"2d bounce": soak_rig_bounce,
|
||||||
|
"2d rain": soak_rig_rain,
|
||||||
|
}
|
||||||
|
SOAK_EACH = 30 # seconds per pattern
|
||||||
|
SOAK_SAMPLE = 0.4 # seconds between LED samples
|
||||||
|
SOAK_HISTORY = 12 # recent frames a sample may match (the sample is read a little after it was sent)
|
||||||
|
|
||||||
|
|
||||||
|
def run_soak(hosts, broadcast, seconds):
|
||||||
|
"""Stream the soak patterns to every device for `seconds`, sampling one random LED per device now and
|
||||||
|
then. A sample is good if it equals that LED in any recent frame; a sample of the idle pattern while
|
||||||
|
streaming is the flicker this test hunts. Ends with a per-device summary."""
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||||
|
sender = Sender(sock, hosts, broadcast)
|
||||||
|
before = {h: get(h, "/api/ddp") for h in hosts}
|
||||||
|
stats = {h: {"samples": 0, "bad": 0, "idle": 0, "examples": []} for h in hosts}
|
||||||
|
names = list(SOAK)
|
||||||
|
sender.start()
|
||||||
|
start = time.time()
|
||||||
|
k = 0
|
||||||
|
history = {h: [] for h in hosts}
|
||||||
|
next_sample = start + 1.0 # warm-up: the first frames are still reaching the devices
|
||||||
|
pool = ThreadPoolExecutor(len(hosts))
|
||||||
|
cur = None
|
||||||
|
print(f"soak: {seconds} s, {len(SOAK)} patterns of {SOAK_EACH} s each across {len(hosts)} bars in this order: {', '.join(hosts)}, brightness {BRIGHTNESS}%\n")
|
||||||
|
while time.time() - start < seconds:
|
||||||
|
idx = int((time.time() - start) // SOAK_EACH) % len(names)
|
||||||
|
if names[idx] != cur:
|
||||||
|
cur = names[idx]
|
||||||
|
print(f"[{int(time.time() - start):5d}s] {cur}")
|
||||||
|
fn = SOAK[cur]
|
||||||
|
total = LEDS * len(hosts)
|
||||||
|
frames = {h: [dim(fn(n * LEDS + i, k, total)) for i in range(LEDS)] for n, h in enumerate(hosts)}
|
||||||
|
for h in hosts:
|
||||||
|
history[h] = (history[h] + [frames[h]])[-SOAK_HISTORY:]
|
||||||
|
sender.set_frames(frames)
|
||||||
|
k += 1
|
||||||
|
if time.time() >= next_sample:
|
||||||
|
next_sample = time.time() + SOAK_SAMPLE
|
||||||
|
led = random.randrange(LEDS)
|
||||||
|
wants = {h: {tuple(f[led]) for f in history[h]} for h in hosts}
|
||||||
|
|
||||||
|
def sample(h, led=led):
|
||||||
|
r = get(h, f"/api/ddp?led={led}")
|
||||||
|
return h, led, tuple(r["rgb"]), r["active"], wants[h]
|
||||||
|
|
||||||
|
for h, l, got, active, w in pool.map(sample, hosts):
|
||||||
|
st = stats[h]
|
||||||
|
st["samples"] += 1
|
||||||
|
if got not in w:
|
||||||
|
st["bad"] += 1
|
||||||
|
if got == (16, 16, 16) and (16, 16, 16) not in w:
|
||||||
|
st["idle"] += 1
|
||||||
|
if len(st["examples"]) < 3:
|
||||||
|
st["examples"].append(f"[{int(time.time() - start)}s {cur}] LED {l} got {list(got)} active={active}")
|
||||||
|
sender.wait_tick()
|
||||||
|
sender.stop()
|
||||||
|
pool.shutdown()
|
||||||
|
time.sleep(0.3)
|
||||||
|
elapsed = time.time() - start
|
||||||
|
print(f"\nsoak finished: {elapsed:.0f} s, {k} frames sent, {sender.seq} ticks\n")
|
||||||
|
failures = 0
|
||||||
|
for h in hosts:
|
||||||
|
a = get(h, "/api/ddp")
|
||||||
|
sy, sb = a["sync"], before[h]["sync"]
|
||||||
|
st = stats[h]
|
||||||
|
print(f"== {h}: frames +{sy['frames'] - sb['frames']}, shown +{sy['shown'] - sb['shown']}, "
|
||||||
|
f"samples {st['samples']}, "
|
||||||
|
f"mismatches {st['bad']}, idle-pattern flickers {st['idle']}")
|
||||||
|
for e in st["examples"]:
|
||||||
|
print(" " + e)
|
||||||
|
if st["idle"]:
|
||||||
|
failures += 1
|
||||||
|
print("\nRESULT:", "no flicker seen" if not failures else f"{failures} device(s) flickered")
|
||||||
|
return failures
|
||||||
|
|
||||||
|
|
||||||
|
def run_interactive(hosts, broadcast):
|
||||||
|
"""Stream one pattern at a time to every device, and switch by typing at the prompt: a number or the
|
||||||
|
start of a name picks a pattern, n / p step to the next or previous, b <0-25> sets the brightness,
|
||||||
|
l lists the patterns, q quits. Per-bar animations (chase, rainbow, breathe) are in the menu too."""
|
||||||
|
global BRIGHTNESS
|
||||||
|
menu = dict(SOAK)
|
||||||
|
for name, fn in ANIMATIONS.items():
|
||||||
|
menu[name] = lambda i, k, n, fn=fn: fn(i % LEDS, k)
|
||||||
|
names = list(menu)
|
||||||
|
|
||||||
|
def show_menu():
|
||||||
|
for num, name in enumerate(names, 1):
|
||||||
|
print(f" {num:2d} {name}")
|
||||||
|
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||||
|
sender = Sender(sock, hosts, broadcast)
|
||||||
|
state = {"cur": 0, "quit": False}
|
||||||
|
cmds = []
|
||||||
|
|
||||||
|
def read_stdin():
|
||||||
|
for line in sys.stdin:
|
||||||
|
cmds.append(line.strip())
|
||||||
|
cmds.append("q") # end of input
|
||||||
|
|
||||||
|
threading.Thread(target=read_stdin, daemon=True).start()
|
||||||
|
|
||||||
|
def handle(cmd):
|
||||||
|
global BRIGHTNESS
|
||||||
|
if not cmd:
|
||||||
|
return
|
||||||
|
low = cmd.lower()
|
||||||
|
if low == "q":
|
||||||
|
state["quit"] = True
|
||||||
|
elif low == "l":
|
||||||
|
show_menu()
|
||||||
|
elif low == "n":
|
||||||
|
state["cur"] = (state["cur"] + 1) % len(names)
|
||||||
|
elif low == "p":
|
||||||
|
state["cur"] = (state["cur"] - 1) % len(names)
|
||||||
|
elif low.startswith("b ") and low[2:].strip().isdigit():
|
||||||
|
BRIGHTNESS = max(0, min(MAX_BRIGHTNESS, int(low[2:])))
|
||||||
|
print(f"brightness {BRIGHTNESS}%")
|
||||||
|
elif low.isdigit() and 1 <= int(low) <= len(names):
|
||||||
|
state["cur"] = int(low) - 1
|
||||||
|
else:
|
||||||
|
hit = [i for i, nm in enumerate(names) if nm.startswith(low)] or [i for i, nm in enumerate(names) if low in nm]
|
||||||
|
if not hit:
|
||||||
|
print(f"no pattern '{cmd}' (l lists them)")
|
||||||
|
return
|
||||||
|
state["cur"] = hit[0]
|
||||||
|
if not state["quit"]:
|
||||||
|
print(f"-> {names[state['cur']]}")
|
||||||
|
|
||||||
|
print(f"{len(hosts)} bars in this order: {', '.join(hosts)}\n")
|
||||||
|
show_menu()
|
||||||
|
print("\ntype a number or name, n/p next/previous, b <0-25> brightness, l list, q quit\n")
|
||||||
|
print(f"-> {names[state['cur']]}")
|
||||||
|
sender.start()
|
||||||
|
k = 0
|
||||||
|
total = LEDS * len(hosts)
|
||||||
|
try:
|
||||||
|
while not state["quit"]:
|
||||||
|
while cmds:
|
||||||
|
handle(cmds.pop(0))
|
||||||
|
fn = menu[names[state["cur"]]]
|
||||||
|
sender.set_frames({h: [dim(fn(n * LEDS + i, k, total)) for i in range(LEDS)] for n, h in enumerate(hosts)})
|
||||||
|
k += 1
|
||||||
|
sender.wait_tick()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
sender.stop()
|
||||||
|
sock.close()
|
||||||
|
for h in hosts:
|
||||||
|
print(f"{h}: {sender.seq} frames sent")
|
||||||
|
|
||||||
|
|
||||||
|
def run_all(hosts, serial_port, broadcast):
|
||||||
"""Run every check against every device together. Returns (output lines, failures) per host."""
|
"""Run every check against every device together. Returns (output lines, failures) per host."""
|
||||||
out = {h: [] for h in hosts}
|
out = {h: [] for h in hosts}
|
||||||
fails = {h: 0 for h in hosts}
|
fails = {h: 0 for h in hosts}
|
||||||
@@ -232,7 +736,7 @@ def run_all(hosts, serial_port):
|
|||||||
out[h].append(f"before: active={before[h]['active']} packets={before[h]['packets']}")
|
out[h].append(f"before: active={before[h]['active']} packets={before[h]['packets']}")
|
||||||
out[h].append(f"output scale: {scale[h]}/255")
|
out[h].append(f"output scale: {scale[h]}/255")
|
||||||
|
|
||||||
sender = Sender(sock, hosts)
|
sender = Sender(sock, hosts, broadcast, acks=True)
|
||||||
sent = {} # frame checksum -> pixels, for the serial log check
|
sent = {} # frame checksum -> pixels, for the serial log check
|
||||||
stop_serial = threading.Event()
|
stop_serial = threading.Event()
|
||||||
serial_lines = []
|
serial_lines = []
|
||||||
@@ -262,7 +766,7 @@ def run_all(hosts, serial_port):
|
|||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
waiting = frame(200)
|
waiting = frame(200)
|
||||||
sent[frame_sum(waiting)] = waiting
|
sent[frame_sum(waiting)] = waiting
|
||||||
send_sync(sock, sender.seq + 1) # sync mode is on: a sync was sent a moment ago
|
send_sync(sock, sender.seq + 1, broadcast) # sync mode is on: a sync was sent a moment ago
|
||||||
time.sleep(0.06) # later than the devices' 30 ms sync window, so the frame is held
|
time.sleep(0.06) # later than the devices' 30 ms sync window, so the frame is held
|
||||||
for h in hosts:
|
for h in hosts:
|
||||||
send_frame(sock, h, waiting, sender.seq + 1)
|
send_frame(sock, h, waiting, sender.seq + 1)
|
||||||
@@ -271,7 +775,7 @@ def run_all(hosts, serial_port):
|
|||||||
got = get(h, "/api/ddp?led=0")["rgb"]
|
got = get(h, "/api/ddp?led=0")["rgb"]
|
||||||
check(h, "frame waits for a sync", got != expected([waiting[0]], scale[h])[0],
|
check(h, "frame waits for a sync", got != expected([waiting[0]], scale[h])[0],
|
||||||
f"LED 0 shows {got} before the sync")
|
f"LED 0 shows {got} before the sync")
|
||||||
send_sync(sock, sender.seq + 2)
|
send_sync(sock, sender.seq + 2, broadcast)
|
||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
for h in hosts:
|
for h in hosts:
|
||||||
got = get(h, "/api/ddp?led=0")["rgb"]
|
got = get(h, "/api/ddp?led=0")["rgb"]
|
||||||
@@ -326,7 +830,7 @@ def run_all(hosts, serial_port):
|
|||||||
|
|
||||||
for name, fn in ANIMATIONS.items():
|
for name, fn in ANIMATIONS.items():
|
||||||
for k in range(ANIM_FRAMES):
|
for k in range(ANIM_FRAMES):
|
||||||
px = [fn(i, k) for i in range(LEDS)]
|
px = [dim(fn(i, k)) for i in range(LEDS)]
|
||||||
sender.set_frames({h: px for h in hosts})
|
sender.set_frames({h: px for h in hosts})
|
||||||
time.sleep(TICK)
|
time.sleep(TICK)
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
@@ -348,20 +852,24 @@ def run_all(hosts, serial_port):
|
|||||||
after = get(h, "/api/ddp")
|
after = get(h, "/api/ddp")
|
||||||
check(h, "inactive after pixels stop", not after["active"])
|
check(h, "inactive after pixels stop", not after["active"])
|
||||||
now0 = get(h, "/api/ddp?led=0")["rgb"]
|
now0 = get(h, "/api/ddp?led=0")["rgb"]
|
||||||
check(h, "pattern is shown again", now0 != expected([shown[0]], scale[h])[0], f"LED 0 now {now0}")
|
check(h, "last frame stays up", now0 == expected([shown[0]], scale[h])[0], f"LED 0 now {now0}")
|
||||||
|
|
||||||
sock.close()
|
sock.close()
|
||||||
return out, fails
|
return out, fails
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
args = [a for a in sys.argv[1:] if not a.startswith("-")]
|
||||||
serial_port = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--serial=")), None)
|
serial_port = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--serial=")), None)
|
||||||
subnet = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--subnet=")), None)
|
subnet = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--subnet=")), None)
|
||||||
|
global BRIGHTNESS
|
||||||
|
BRIGHTNESS = min(MAX_BRIGHTNESS, int(next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--brightness=")), MAX_BRIGHTNESS)))
|
||||||
|
set_fps(int(next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--fps=")), FPS)))
|
||||||
|
prefix = subnet or local_prefix()
|
||||||
|
broadcast = f"{prefix}.255" # the sync is broadcast to this network's broadcast address
|
||||||
if args:
|
if args:
|
||||||
hosts = args
|
hosts = args
|
||||||
else:
|
else:
|
||||||
prefix = subnet or local_prefix()
|
|
||||||
hosts = find_devices(prefix)
|
hosts = find_devices(prefix)
|
||||||
print(f"found {len(hosts)} device(s) on {prefix}.0/24: {', '.join(hosts) or 'none'}\n")
|
print(f"found {len(hosts)} device(s) on {prefix}.0/24: {', '.join(hosts) or 'none'}\n")
|
||||||
if not hosts:
|
if not hosts:
|
||||||
@@ -370,7 +878,15 @@ def main():
|
|||||||
print("note: --serial is only used when testing one device\n")
|
print("note: --serial is only used when testing one device\n")
|
||||||
serial_port = None
|
serial_port = None
|
||||||
|
|
||||||
out, fails = run_all(hosts, serial_port)
|
if "--interactive" in sys.argv[1:] or "-i" in sys.argv[1:]:
|
||||||
|
run_interactive(hosts, broadcast)
|
||||||
|
return
|
||||||
|
|
||||||
|
soak = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--soak=")), None)
|
||||||
|
if soak:
|
||||||
|
sys.exit(1 if run_soak(hosts, broadcast, float(soak)) else 0)
|
||||||
|
|
||||||
|
out, fails = run_all(hosts, serial_port, broadcast)
|
||||||
failures = 0
|
failures = 0
|
||||||
for h in hosts:
|
for h in hosts:
|
||||||
print(f"== {h}")
|
print(f"== {h}")
|
||||||
|
|||||||
Reference in new issue
Block a user