Compare commits
6
Commits
4cd3bc7973
...
cpp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24dd5ffb15 | ||
|
|
94e300f6ad | ||
|
|
59eb37cad5 | ||
|
|
af82cb4c4a | ||
|
|
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
|
||||||
@@ -82,3 +102,26 @@ Build and flash for the ESP32-C3:
|
|||||||
idf.py set-target esp32c3
|
idf.py set-target esp32c3
|
||||||
idf.py build flash monitor
|
idf.py build flash monitor
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### ESP-NOW (led-controller)
|
||||||
|
|
||||||
|
The driver takes part in an ESP-NOW rig run by `led-controller` (the same 0x4C wire protocol as the
|
||||||
|
MicroPython drivers). It announces itself at boot, so the controller lists it with its name and LED count
|
||||||
|
(`transport: espnow`), and then takes:
|
||||||
|
|
||||||
|
- presets and selects, the brightness, device settings (`device_config`), the zones (group commands) and
|
||||||
|
the startup preset, from v2/v3 envelopes and v1 JSON;
|
||||||
|
- the controller's reliable messages: acknowledged, reassembled, duplicates dropped, state resynced by digest;
|
||||||
|
- pings, and the beat for beat-timed presets (`tb`), which take their quarter-beat length from the
|
||||||
|
controller's tempo.
|
||||||
|
|
||||||
|
Settings (`GET`/`POST /api/espnow`): `enabled`, and `channel` (1-13). ESP-NOW uses the radio's channel:
|
||||||
|
the access point's, or the router's when the client is joined. Put the controller's bridge on the same
|
||||||
|
channel. A client that is searching for a network that is not in range keeps the radio hopping channels,
|
||||||
|
which breaks ESP-NOW; the access point gives it a fixed channel.
|
||||||
|
|
||||||
|
Saving Wi-Fi credentials (`POST /api/wifi`, or the Settings tab) switches to Wi-Fi mode: ESP-NOW is turned
|
||||||
|
off and the driver restarts, then joins the saved network. Turn ESP-NOW back on with `POST /api/espnow` and
|
||||||
|
a restart.
|
||||||
|
|
||||||
|
Not supported yet: OTA over ESP-NOW, the reverse (`reversed`) setting, and the lossy-link test mode.
|
||||||
+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" "beat_sync.cpp" "ctrl_msg.cpp" "espnow_link.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")
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include "beat_sync.h"
|
||||||
|
|
||||||
|
#include "esp_timer.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr uint8_t kMagic = 0x4C;
|
||||||
|
constexpr uint8_t kBeat = 0x25;
|
||||||
|
constexpr uint32_t kDefaultPeriodMs = 500;
|
||||||
|
constexpr uint32_t kMinPeriodMs = 30;
|
||||||
|
constexpr uint32_t kMaxPeriodMs = 4000;
|
||||||
|
constexpr int kLostPeriods = 4; // no beat for this many periods: the controller has stopped
|
||||||
|
|
||||||
|
volatile uint16_t s_last_idx;
|
||||||
|
volatile uint32_t s_period_ms;
|
||||||
|
volatile int64_t s_last_us;
|
||||||
|
volatile bool s_have;
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void beat_on_frame(const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
if (len != 8 || data[0] != kMagic || data[1] != kBeat) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
uint16_t idx = (uint16_t)(data[3] | (data[4] << 8));
|
||||||
|
uint32_t period = (uint32_t)(data[5] | (data[6] << 8));
|
||||||
|
if (s_have && idx == s_last_idx) {
|
||||||
|
return; // the second copy of a beat already taken
|
||||||
|
}
|
||||||
|
if (period < kMinPeriodMs || period > kMaxPeriodMs) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
s_last_idx = idx;
|
||||||
|
s_period_ms = period;
|
||||||
|
s_last_us = esp_timer_get_time();
|
||||||
|
s_have = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t beat_period_ms(void)
|
||||||
|
{
|
||||||
|
if (!s_have) {
|
||||||
|
return kDefaultPeriodMs;
|
||||||
|
}
|
||||||
|
int64_t age_us = esp_timer_get_time() - s_last_us;
|
||||||
|
if (age_us > (int64_t)s_period_ms * kLostPeriods * 1000) {
|
||||||
|
return kDefaultPeriodMs;
|
||||||
|
}
|
||||||
|
return s_period_ms;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Beat frames from led-controller (ESP-NOW [4C][25][flags][idx u16][period u16][fire_in]). Only the tempo
|
||||||
|
* is used: beat-timed presets (tb) take their quarter-beat durations from it.
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
/** @brief Note a received frame. Called from the ESP-NOW receive callback, so it does no more than store the values. */
|
||||||
|
void beat_on_frame(const uint8_t *data, size_t len);
|
||||||
|
|
||||||
|
/** @brief The controller's beat period in ms while beats are arriving, else 500 (120 BPM). */
|
||||||
|
uint32_t beat_period_ms(void);
|
||||||
@@ -0,0 +1,669 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*/
|
||||||
|
#include "ctrl_msg.h"
|
||||||
|
|
||||||
|
#include <cctype>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_mac.h"
|
||||||
|
#include "nvs.h"
|
||||||
|
#include "nvs_flash.h"
|
||||||
|
|
||||||
|
#include "patterns.h"
|
||||||
|
#include "presets.h"
|
||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
static const char *TAG = "ctrl_msg";
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr uint8_t kMagic = 0x4C;
|
||||||
|
constexpr uint8_t kGroups = 0x02;
|
||||||
|
constexpr uint8_t kCmd = 0x03;
|
||||||
|
constexpr uint8_t kGroupCmd = 0x04;
|
||||||
|
constexpr size_t kGroupsMax = 16;
|
||||||
|
constexpr size_t kGroupIdMax = 24;
|
||||||
|
constexpr size_t kEnvHdr = 5;
|
||||||
|
|
||||||
|
char s_groups[kGroupsMax][kGroupIdMax];
|
||||||
|
size_t s_ngroups;
|
||||||
|
char s_pending[32]; // a select for a preset not saved yet: applied when that preset arrives
|
||||||
|
|
||||||
|
// Copy n bytes as a NUL-terminated string
|
||||||
|
void cstr(char *dst, size_t cap, const uint8_t *src, size_t n)
|
||||||
|
{
|
||||||
|
size_t k = n < cap - 1 ? n : cap - 1;
|
||||||
|
memcpy(dst, src, k);
|
||||||
|
dst[k] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bounds-checked reader over an envelope blob
|
||||||
|
struct Rd {
|
||||||
|
const uint8_t *p;
|
||||||
|
size_t n;
|
||||||
|
size_t off;
|
||||||
|
bool ok;
|
||||||
|
bool bytes(size_t k, const uint8_t **out)
|
||||||
|
{
|
||||||
|
if (!ok || k > n - off) {
|
||||||
|
ok = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
*out = p + off;
|
||||||
|
off += k;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
bool u8(uint8_t *v)
|
||||||
|
{
|
||||||
|
const uint8_t *b;
|
||||||
|
if (!bytes(1, &b)) return false;
|
||||||
|
*v = b[0];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
bool u16(uint16_t *v)
|
||||||
|
{
|
||||||
|
const uint8_t *b;
|
||||||
|
if (!bytes(2, &b)) return false;
|
||||||
|
*v = (uint16_t)(b[0] | (b[1] << 8));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Presets blob: count, then per record name, pattern, colours, delay, brightness, auto, n1..n6 and (v3) an
|
||||||
|
// extension block with fade (key 1) and beat timing (key 2)
|
||||||
|
cJSON *decode_presets(Rd &r, bool v3)
|
||||||
|
{
|
||||||
|
uint8_t count;
|
||||||
|
if (!r.u8(&count)) return nullptr;
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
uint8_t nl, pl, nc;
|
||||||
|
const uint8_t *name, *pat;
|
||||||
|
if (!r.u8(&nl) || !r.bytes(nl, &name) || !r.u8(&pl) || !r.bytes(pl, &pat) || !r.u8(&nc)) {
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
char nm[64], pn[64];
|
||||||
|
cstr(nm, sizeof(nm), name, nl);
|
||||||
|
cstr(pn, sizeof(pn), pat, pl);
|
||||||
|
cJSON *rec = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(rec, "pattern", pn);
|
||||||
|
cJSON *cols = cJSON_AddArrayToObject(rec, "colors");
|
||||||
|
for (int c = 0; c < nc; c++) {
|
||||||
|
const uint8_t *rgb;
|
||||||
|
if (!r.bytes(3, &rgb)) {
|
||||||
|
cJSON_Delete(rec);
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
int v[3] = { rgb[0], rgb[1], rgb[2] };
|
||||||
|
cJSON_AddItemToArray(cols, cJSON_CreateIntArray(v, 3));
|
||||||
|
}
|
||||||
|
uint16_t delay, nn[6];
|
||||||
|
uint8_t br, au;
|
||||||
|
bool ok = r.u16(&delay) && r.u8(&br) && r.u8(&au);
|
||||||
|
for (int k = 0; ok && k < 6; k++) {
|
||||||
|
ok = r.u16(&nn[k]);
|
||||||
|
}
|
||||||
|
if (!ok) {
|
||||||
|
cJSON_Delete(rec);
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
cJSON_AddNumberToObject(rec, "delay", delay);
|
||||||
|
cJSON_AddNumberToObject(rec, "brightness", br);
|
||||||
|
cJSON_AddBoolToObject(rec, "auto", au != 0);
|
||||||
|
for (int k = 0; k < 6; k++) {
|
||||||
|
char key[4] = { 'n', (char)('1' + k), '\0' };
|
||||||
|
cJSON_AddNumberToObject(rec, key, (int16_t)nn[k]);
|
||||||
|
}
|
||||||
|
if (v3) {
|
||||||
|
uint8_t ext_len;
|
||||||
|
const uint8_t *ext;
|
||||||
|
if (!r.u8(&ext_len) || !r.bytes(ext_len, &ext)) {
|
||||||
|
cJSON_Delete(rec);
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
Rd e = { ext, ext_len, 0, true };
|
||||||
|
while (e.off < e.n) {
|
||||||
|
uint8_t key, len;
|
||||||
|
const uint8_t *val;
|
||||||
|
if (!e.u8(&key) || !e.u8(&len) || !e.bytes(len, &val)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (key == 1 && len == 2) {
|
||||||
|
cJSON_AddNumberToObject(rec, "fade", val[0] | (val[1] << 8));
|
||||||
|
} else if (key == 2 && len == 1) {
|
||||||
|
cJSON_AddBoolToObject(rec, "beat_time", val[0] != 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(o, nm, rec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return o;
|
||||||
|
fail:
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Select blob: per device, its preset name and an optional step
|
||||||
|
cJSON *decode_select(Rd &r)
|
||||||
|
{
|
||||||
|
uint8_t count;
|
||||||
|
if (!r.u8(&count)) return nullptr;
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
uint8_t dl, pl, has;
|
||||||
|
const uint8_t *dev, *pname;
|
||||||
|
if (!r.u8(&dl) || !r.bytes(dl, &dev) || !r.u8(&pl) || !r.bytes(pl, &pname) || !r.u8(&has)) {
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
char dn[64], pn[64];
|
||||||
|
cstr(dn, sizeof(dn), dev, dl);
|
||||||
|
cstr(pn, sizeof(pn), pname, pl);
|
||||||
|
cJSON *arr = cJSON_CreateArray();
|
||||||
|
cJSON_AddItemToArray(arr, cJSON_CreateString(pn));
|
||||||
|
if (has) {
|
||||||
|
uint16_t step;
|
||||||
|
if (!r.u16(&step)) {
|
||||||
|
cJSON_Delete(arr);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
cJSON_AddItemToArray(arr, cJSON_CreateNumber(step));
|
||||||
|
}
|
||||||
|
cJSON_AddItemToObject(o, dn, arr);
|
||||||
|
}
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default blob: the startup preset name and the devices it applies to
|
||||||
|
bool decode_default(Rd &r, cJSON *o)
|
||||||
|
{
|
||||||
|
uint8_t nl, nt;
|
||||||
|
const uint8_t *name;
|
||||||
|
if (!r.u8(&nl) || !r.bytes(nl, &name)) return false;
|
||||||
|
char dn[64];
|
||||||
|
cstr(dn, sizeof(dn), name, nl);
|
||||||
|
cJSON_AddStringToObject(o, "default", dn);
|
||||||
|
if (!r.u8(&nt)) return false;
|
||||||
|
cJSON *targets = cJSON_AddArrayToObject(o, "targets");
|
||||||
|
for (int i = 0; i < nt; i++) {
|
||||||
|
uint8_t tl;
|
||||||
|
const uint8_t *t;
|
||||||
|
if (!r.u8(&tl) || !r.bytes(tl, &t)) return false;
|
||||||
|
char tn[64];
|
||||||
|
cstr(tn, sizeof(tn), t, tl);
|
||||||
|
cJSON_AddItemToArray(targets, cJSON_CreateString(tn));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A v2/v3 envelope as the v1 JSON object the MicroPython driver works from
|
||||||
|
cJSON *env_to_json(const uint8_t *b, size_t n)
|
||||||
|
{
|
||||||
|
if (n < kEnvHdr || (b[0] != 2 && b[0] != 3)) return nullptr;
|
||||||
|
size_t lp = b[2], ls = b[3], ld = b[4];
|
||||||
|
// CMD and GROUP_CMD frames may end with the controller's save byte after the envelope: ignored, as settings
|
||||||
|
// are saved on every change
|
||||||
|
size_t want = kEnvHdr + lp + ls + ld;
|
||||||
|
if (n != want && n != want + 1) return nullptr;
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(o, "v", "1");
|
||||||
|
uint8_t w = b[1];
|
||||||
|
if (w < 128) { // device brightness, 0-127 on the wire
|
||||||
|
int v = (w * 255) / 127;
|
||||||
|
cJSON_AddNumberToObject(o, "b", v > 255 ? 255 : v);
|
||||||
|
}
|
||||||
|
Rd p = { b + kEnvHdr, lp, 0, true };
|
||||||
|
Rd s = { b + kEnvHdr + lp, ls, 0, true };
|
||||||
|
Rd d = { b + kEnvHdr + lp + ls, ld, 0, true };
|
||||||
|
if (lp) {
|
||||||
|
cJSON *pr = decode_presets(p, b[0] == 3);
|
||||||
|
if (!pr) goto fail;
|
||||||
|
cJSON_AddItemToObject(o, "presets", pr);
|
||||||
|
}
|
||||||
|
if (ls) {
|
||||||
|
cJSON *sel = decode_select(s);
|
||||||
|
if (!sel) goto fail;
|
||||||
|
cJSON_AddItemToObject(o, "select", sel);
|
||||||
|
}
|
||||||
|
if (ld && !decode_default(d, o)) goto fail;
|
||||||
|
return o;
|
||||||
|
fail:
|
||||||
|
cJSON_Delete(o);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This driver's MAC as 12 lowercase hex digits, the way the controller names a device
|
||||||
|
void own_mac_hex(char out[13])
|
||||||
|
{
|
||||||
|
uint8_t mac[6];
|
||||||
|
esp_read_mac(mac, ESP_MAC_WIFI_STA);
|
||||||
|
snprintf(out, 13, "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A select or default names this driver if it names its hostname or its MAC (any separators), or "*"
|
||||||
|
bool names_me(const char *name)
|
||||||
|
{
|
||||||
|
if (strcmp(name, "*") == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (strcmp(name, n.hostname) == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
char mine[13], hex[13];
|
||||||
|
own_mac_hex(mine);
|
||||||
|
size_t k = 0;
|
||||||
|
for (const char *c = name; *c; c++) {
|
||||||
|
if (isxdigit((unsigned char)*c)) {
|
||||||
|
if (k < 12) hex[k] = (char)tolower((unsigned char)*c);
|
||||||
|
k++;
|
||||||
|
} else if (*c != ':' && *c != '-') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hex[12] = '\0';
|
||||||
|
return k == 12 && strcmp(hex, mine) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool in_group(const char *gid)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < s_ngroups; i++) {
|
||||||
|
if (strcmp(s_groups[i], gid) == 0) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void save_groups(void)
|
||||||
|
{
|
||||||
|
char buf[kGroupsMax * (kGroupIdMax + 1)] = "";
|
||||||
|
for (size_t i = 0; i < s_ngroups; i++) {
|
||||||
|
if (i) strncat(buf, "\n", sizeof(buf) - strlen(buf) - 1);
|
||||||
|
strncat(buf, s_groups[i], sizeof(buf) - strlen(buf) - 1);
|
||||||
|
}
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open("espnow", NVS_READWRITE, &h) == ESP_OK) {
|
||||||
|
nvs_set_str(h, "groups", buf);
|
||||||
|
nvs_commit(h);
|
||||||
|
nvs_close(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GROUPS: [4C][02][count] then per id [len][id]. The list replaces the stored one.
|
||||||
|
void set_groups(const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
if (len < 3) return;
|
||||||
|
size_t count = data[2], off = 3;
|
||||||
|
s_ngroups = 0;
|
||||||
|
for (size_t i = 0; i < count && off < len; i++) {
|
||||||
|
size_t gl = data[off++];
|
||||||
|
if (gl == 0 || off + gl > len) break;
|
||||||
|
if (gl < kGroupIdMax && s_ngroups < kGroupsMax) {
|
||||||
|
cstr(s_groups[s_ngroups], kGroupIdMax, data + off, gl);
|
||||||
|
s_ngroups++;
|
||||||
|
}
|
||||||
|
off += gl;
|
||||||
|
}
|
||||||
|
save_groups();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The device settings in a device_config object, applied to the strip and the saved network settings
|
||||||
|
void apply_device_config(const cJSON *dc)
|
||||||
|
{
|
||||||
|
if (!cJSON_IsObject(dc)) return;
|
||||||
|
const cJSON *v = cJSON_GetObjectItem(dc, "name");
|
||||||
|
if (cJSON_IsString(v) && v->valuestring[0]) {
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
cstr(n.hostname, sizeof(n.hostname), (const uint8_t *)v->valuestring, strlen(v->valuestring));
|
||||||
|
settings_save_net(&n);
|
||||||
|
}
|
||||||
|
hw_cfg_t hw;
|
||||||
|
settings_load_hw(&hw);
|
||||||
|
bool changed = false;
|
||||||
|
v = cJSON_GetObjectItem(dc, "num_leds");
|
||||||
|
if (cJSON_IsNumber(v) && v->valueint >= 1 && v->valueint <= 512) {
|
||||||
|
hw.num_leds = v->valueint;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(dc, "max_brightness");
|
||||||
|
if (cJSON_IsNumber(v) && v->valueint >= 0 && v->valueint <= 255) {
|
||||||
|
hw.max_brightness = (uint8_t)v->valueint;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(dc, "color_order");
|
||||||
|
if (cJSON_IsString(v)) {
|
||||||
|
static const char *orders[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" };
|
||||||
|
for (const char *o : orders) {
|
||||||
|
if (strcmp(v->valuestring, o) == 0) {
|
||||||
|
strncpy(hw.order, o, sizeof(hw.order) - 1);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
settings_save_hw(&hw);
|
||||||
|
patterns_set_hardware(hw);
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(dc, "startup_mode");
|
||||||
|
if (cJSON_IsString(v) && strcmp(v->valuestring, "off") == 0) {
|
||||||
|
presets_set_startup("");
|
||||||
|
}
|
||||||
|
// "reversed" is accepted and ignored: the C++ driver does not reverse its strip yet
|
||||||
|
}
|
||||||
|
|
||||||
|
void clear_all_presets(void)
|
||||||
|
{
|
||||||
|
while (presets_count() > 0) {
|
||||||
|
char name[32];
|
||||||
|
snprintf(name, sizeof(name), "%s", presets_at(0)->name);
|
||||||
|
presets_delete(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save each preset by name. Missing fields keep the pattern's defaults.
|
||||||
|
void apply_presets(const cJSON *presets)
|
||||||
|
{
|
||||||
|
const cJSON *rec;
|
||||||
|
cJSON_ArrayForEach(rec, presets)
|
||||||
|
{
|
||||||
|
const cJSON *pat = cJSON_GetObjectItem(rec, "pattern");
|
||||||
|
int idx = cJSON_IsString(pat) ? patterns_index(pat->valuestring) : -1;
|
||||||
|
if (idx < 0) {
|
||||||
|
ESP_LOGW(TAG, "preset %s: unknown pattern", rec->string);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
preset_t p;
|
||||||
|
preset_defaults(&p, idx);
|
||||||
|
snprintf(p.name, sizeof(p.name), "%s", rec->string);
|
||||||
|
if (preset_from_json(rec, &p)) {
|
||||||
|
presets_save(&p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s_pending[0] && presets_select(s_pending) == ESP_OK) {
|
||||||
|
s_pending[0] = '\0';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The select entry for this driver: a device key that names it, else the only entry
|
||||||
|
const cJSON *pick_select(const cJSON *sel)
|
||||||
|
{
|
||||||
|
if (cJSON_IsString(sel)) {
|
||||||
|
return sel;
|
||||||
|
}
|
||||||
|
if (cJSON_IsArray(sel)) {
|
||||||
|
return cJSON_GetArrayItem(sel, 0);
|
||||||
|
}
|
||||||
|
if (!cJSON_IsObject(sel)) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
const cJSON *e;
|
||||||
|
cJSON_ArrayForEach(e, sel)
|
||||||
|
{
|
||||||
|
if (names_me(e->string)) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cJSON_GetArraySize(sel) == 1 ? sel->child : nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void apply_select(const cJSON *sel)
|
||||||
|
{
|
||||||
|
const cJSON *e = pick_select(sel);
|
||||||
|
if (!e) return;
|
||||||
|
// an entry is [name, step] or a bare name; step is not used by this driver
|
||||||
|
const cJSON *name = cJSON_IsArray(e) ? cJSON_GetArrayItem(e, 0) : e;
|
||||||
|
if (!cJSON_IsString(name) || !name->valuestring[0]) return;
|
||||||
|
if (presets_select(name->valuestring) == ESP_OK) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// "on" and "off" are the built-in patterns (the controller's identify ends with "off"): select them
|
||||||
|
if (strcmp(name->valuestring, "on") == 0 || strcmp(name->valuestring, "off") == 0) {
|
||||||
|
preset_t p;
|
||||||
|
preset_defaults(&p, patterns_index(name->valuestring));
|
||||||
|
snprintf(p.name, sizeof(p.name), "%s", name->valuestring);
|
||||||
|
patterns_select(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
snprintf(s_pending, sizeof(s_pending), "%s", name->valuestring); // preset not here yet
|
||||||
|
}
|
||||||
|
|
||||||
|
// A default applies when there are no targets or this driver is one of them
|
||||||
|
void apply_default(const cJSON *d)
|
||||||
|
{
|
||||||
|
const cJSON *def = cJSON_GetObjectItem(d, "default");
|
||||||
|
if (!cJSON_IsString(def)) return;
|
||||||
|
const cJSON *targets = cJSON_GetObjectItem(d, "targets");
|
||||||
|
if (cJSON_IsArray(targets) && cJSON_GetArraySize(targets) > 0) {
|
||||||
|
bool hit = false;
|
||||||
|
const cJSON *t;
|
||||||
|
cJSON_ArrayForEach(t, targets)
|
||||||
|
{
|
||||||
|
if (cJSON_IsString(t) && names_me(t->valuestring)) hit = true;
|
||||||
|
}
|
||||||
|
if (!hit) return;
|
||||||
|
}
|
||||||
|
presets_set_startup(def->valuestring);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The controller's JSON path shortens keys (engine.c compact()); these map them back to the long names
|
||||||
|
struct KeyName {
|
||||||
|
const char *shortk;
|
||||||
|
const char *longk;
|
||||||
|
};
|
||||||
|
constexpr KeyName kTopKeys[] = {
|
||||||
|
{"p", "presets"}, {"s", "select"}, {"g", "groups"}, {"sg", "set_groups"},
|
||||||
|
{"sv", "save"}, {"df", "default"}, {"dc", "device_config"}, {"cp", "clear_presets"},
|
||||||
|
{"mf", "manifest"},
|
||||||
|
};
|
||||||
|
constexpr KeyName kPresetKeys[] = {
|
||||||
|
{"p", "pattern"}, {"c", "colors"}, {"d", "delay"}, {"b", "brightness"},
|
||||||
|
{"a", "auto"}, {"bg", "background"}, {"f", "fade"}, {"tb", "beat_time"},
|
||||||
|
};
|
||||||
|
|
||||||
|
const char *long_name(const KeyName *map, size_t n, const char *k)
|
||||||
|
{
|
||||||
|
for (size_t i = 0; i < n; i++) {
|
||||||
|
if (strcmp(map[i].shortk, k) == 0) return map[i].longk;
|
||||||
|
}
|
||||||
|
return k;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A copy of one preset object with long key names
|
||||||
|
cJSON *expand_preset(const cJSON *src)
|
||||||
|
{
|
||||||
|
cJSON *out = cJSON_CreateObject();
|
||||||
|
const cJSON *it;
|
||||||
|
cJSON_ArrayForEach(it, src)
|
||||||
|
{
|
||||||
|
const char *k = long_name(kPresetKeys, sizeof(kPresetKeys) / sizeof(kPresetKeys[0]), it->string);
|
||||||
|
if (!cJSON_HasObjectItem(out, k)) cJSON_AddItemToObject(out, k, cJSON_Duplicate(it, true));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A copy of a v1 message with long key names (its presets too)
|
||||||
|
cJSON *expand_v1(const cJSON *src)
|
||||||
|
{
|
||||||
|
cJSON *out = cJSON_CreateObject();
|
||||||
|
const cJSON *it;
|
||||||
|
cJSON_ArrayForEach(it, src)
|
||||||
|
{
|
||||||
|
const char *k = long_name(kTopKeys, sizeof(kTopKeys) / sizeof(kTopKeys[0]), it->string);
|
||||||
|
if (cJSON_HasObjectItem(out, k)) continue;
|
||||||
|
if (strcmp(k, "presets") == 0 && cJSON_IsObject(it)) {
|
||||||
|
cJSON *ps = cJSON_AddObjectToObject(out, "presets");
|
||||||
|
const cJSON *p;
|
||||||
|
cJSON_ArrayForEach(p, it) { cJSON_AddItemToObject(ps, p->string, expand_preset(p)); }
|
||||||
|
} else {
|
||||||
|
cJSON_AddItemToObject(out, k, cJSON_Duplicate(it, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A JSON message with groups applies only when this driver is in one of them (no groups: everyone)
|
||||||
|
bool json_for_me(const cJSON *o)
|
||||||
|
{
|
||||||
|
const cJSON *groups = cJSON_GetObjectItem(o, "groups");
|
||||||
|
if (!cJSON_IsArray(groups) || cJSON_GetArraySize(groups) == 0) return true;
|
||||||
|
const cJSON *g;
|
||||||
|
cJSON_ArrayForEach(g, groups)
|
||||||
|
{
|
||||||
|
if (cJSON_IsString(g) && in_group(g->valuestring)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One v1 object, in the order controller_messages.py applies them
|
||||||
|
void apply_v1(const cJSON *d)
|
||||||
|
{
|
||||||
|
const cJSON *v = cJSON_GetObjectItem(d, "v");
|
||||||
|
if (!cJSON_IsString(v) || strcmp(v->valuestring, "1") != 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
apply_device_config(cJSON_GetObjectItem(d, "device_config"));
|
||||||
|
v = cJSON_GetObjectItem(d, "b");
|
||||||
|
if (cJSON_IsNumber(v)) {
|
||||||
|
int b = v->valueint < 0 ? 0 : (v->valueint > 255 ? 255 : v->valueint);
|
||||||
|
patterns_set_global((uint8_t)b);
|
||||||
|
}
|
||||||
|
if (cJSON_HasObjectItem(d, "clear_presets")) {
|
||||||
|
clear_all_presets();
|
||||||
|
}
|
||||||
|
const cJSON *presets = cJSON_GetObjectItem(d, "presets");
|
||||||
|
if (cJSON_IsObject(presets)) {
|
||||||
|
apply_presets(presets);
|
||||||
|
}
|
||||||
|
const cJSON *sel = cJSON_GetObjectItem(d, "select");
|
||||||
|
if (sel) {
|
||||||
|
apply_select(sel);
|
||||||
|
}
|
||||||
|
apply_default(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A v2/v3 envelope: applied as a v1 object
|
||||||
|
void handle_env(const uint8_t *env, size_t n)
|
||||||
|
{
|
||||||
|
cJSON *o = env_to_json(env, n);
|
||||||
|
if (!o) {
|
||||||
|
ESP_LOGW(TAG, "bad envelope, %u bytes", (unsigned)n);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
apply_v1(o);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void ctrl_init(void)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open("espnow", NVS_READONLY, &h) != ESP_OK) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
char buf[kGroupsMax * (kGroupIdMax + 1)];
|
||||||
|
size_t len = sizeof(buf);
|
||||||
|
if (nvs_get_str(h, "groups", buf, &len) == ESP_OK) {
|
||||||
|
s_ngroups = 0;
|
||||||
|
char *save = nullptr;
|
||||||
|
for (char *tok = strtok_r(buf, "\n", &save); tok && s_ngroups < kGroupsMax; tok = strtok_r(nullptr, "\n", &save)) {
|
||||||
|
snprintf(s_groups[s_ngroups], kGroupIdMax, "%s", tok);
|
||||||
|
s_ngroups++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nvs_close(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ctrl_handle(const uint8_t mac[6], const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
(void)mac;
|
||||||
|
if (len < 1) return;
|
||||||
|
if (data[0] == '{') {
|
||||||
|
cJSON *raw = cJSON_ParseWithLength((const char *)data, len);
|
||||||
|
if (raw) {
|
||||||
|
cJSON *o = expand_v1(raw);
|
||||||
|
cJSON_Delete(raw);
|
||||||
|
if (json_for_me(o)) apply_v1(o);
|
||||||
|
cJSON_Delete(o);
|
||||||
|
} else {
|
||||||
|
ESP_LOGW(TAG, "bad JSON");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (len < 2 || data[0] != kMagic) return;
|
||||||
|
switch (data[1]) {
|
||||||
|
case kGroups:
|
||||||
|
set_groups(data, len);
|
||||||
|
break;
|
||||||
|
case kCmd:
|
||||||
|
handle_env(data + 2, len - 2); // a trailing save byte is ignored: settings are saved on every change
|
||||||
|
break;
|
||||||
|
case kGroupCmd: {
|
||||||
|
if (len < 3) return;
|
||||||
|
size_t gl = data[2];
|
||||||
|
if (len < 3 + gl) return;
|
||||||
|
char gid[kGroupIdMax];
|
||||||
|
cstr(gid, sizeof(gid), data + 3, gl);
|
||||||
|
if (!in_group(gid)) return;
|
||||||
|
size_t off = 3 + gl;
|
||||||
|
handle_env(data + off, len - off);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t ctrl_build_announce(uint8_t *out, size_t cap)
|
||||||
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
hw_cfg_t hw;
|
||||||
|
settings_load_hw(&hw);
|
||||||
|
size_t nl = strlen(n.hostname);
|
||||||
|
if (nl > 47) nl = 47;
|
||||||
|
static const char *orders[] = { "rgb", "rbg", "grb", "gbr", "brg", "bgr" };
|
||||||
|
int co = 0;
|
||||||
|
for (int i = 0; i < 6; i++) {
|
||||||
|
if (strcmp(hw.order, orders[i]) == 0) co = i;
|
||||||
|
}
|
||||||
|
char cfg[160];
|
||||||
|
snprintf(cfg, sizeof(cfg),
|
||||||
|
"{\"max_brightness\":%u,\"num_leds\":%d,\"color_order\":\"%s\",\"startup_mode\":\"default\",\"reversed\":false}",
|
||||||
|
(unsigned)hw.max_brightness, hw.num_leds, hw.order);
|
||||||
|
size_t cl = strlen(cfg);
|
||||||
|
size_t need = 3 + nl + 6 + 1 + cl;
|
||||||
|
if (need > cap || need > 250) return 0;
|
||||||
|
size_t off = 0;
|
||||||
|
out[off++] = kMagic;
|
||||||
|
out[off++] = 0x01; // ANNOUNCE
|
||||||
|
out[off++] = (uint8_t)nl;
|
||||||
|
memcpy(out + off, n.hostname, nl);
|
||||||
|
off += nl;
|
||||||
|
out[off++] = hw.num_leds & 0xFF;
|
||||||
|
out[off++] = (hw.num_leds >> 8) & 0xFF;
|
||||||
|
out[off++] = (uint8_t)co;
|
||||||
|
out[off++] = 0; // startup mode: default
|
||||||
|
out[off++] = patterns_get_global();
|
||||||
|
out[off++] = 0; // device type: LED strip
|
||||||
|
out[off++] = (uint8_t)cl;
|
||||||
|
memcpy(out + off, cfg, cl);
|
||||||
|
off += cl;
|
||||||
|
return off;
|
||||||
|
}
|
||||||
|
|
||||||
|
cJSON *ctrl_groups_json(void)
|
||||||
|
{
|
||||||
|
cJSON *arr = cJSON_CreateArray();
|
||||||
|
for (size_t i = 0; i < s_ngroups; i++) {
|
||||||
|
cJSON_AddItemToArray(arr, cJSON_CreateString(s_groups[i]));
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Messages from led-controller over ESP-NOW: envelopes (0x4C CMD / GROUP_CMD, v2 and v3 binary), v1 JSON
|
||||||
|
* objects, and the group list. They are applied as the MicroPython driver applies them (controller_messages.py).
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "cJSON.h"
|
||||||
|
|
||||||
|
/** @brief Load the saved group list. Call once, after NVS is up. */
|
||||||
|
void ctrl_init(void);
|
||||||
|
|
||||||
|
/** @brief Handle one controller message from mac. Runs in the ESP-NOW link task. */
|
||||||
|
void ctrl_handle(const uint8_t mac[6], const uint8_t *data, size_t len);
|
||||||
|
|
||||||
|
/** @brief This driver's ANNOUNCE packet (boot hello, with its settings) into out. Returns its length. */
|
||||||
|
size_t ctrl_build_announce(uint8_t *out, size_t cap);
|
||||||
|
|
||||||
|
/** @brief The group ids this driver is in, as a new JSON array. The caller frees it. */
|
||||||
|
cJSON *ctrl_groups_json(void);
|
||||||
+4
-2
@@ -78,8 +78,10 @@ static void ddp_task(void *arg)
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
uint8_t dtype = buf[2];
|
uint8_t dtype = buf[2];
|
||||||
if (dtype != 0x00 && dtype != 0x01) {
|
// 8-bit RGB: 0x00 (undefined, taken as RGB), 0x01 (the shorthand ddp_test sends) and 0x0B (RGB, 8 bits
|
||||||
continue; // only 8-bit RGB
|
// per channel, the DDP specification's code, which is what the controller sends)
|
||||||
|
if (dtype != 0x00 && dtype != 0x01 && dtype != 0x0B) {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
uint32_t offset = be32(buf + 4);
|
uint32_t offset = be32(buf + 4);
|
||||||
size_t len = be16(buf + 8);
|
size_t len = be16(buf + 8);
|
||||||
|
|||||||
+4
-2
@@ -92,8 +92,8 @@ int nz(int v, int def); // v when v > 0, else def
|
|||||||
rgb mk(int r, int g, int b); // clamped
|
rgb mk(int r, int g, int b); // clamped
|
||||||
rgb ab(rgb c, int level); // c scaled by level/255
|
rgb ab(rgb c, int level); // c scaled by level/255
|
||||||
rgb mix(rgb a, rgb b, int k); // a -> b, k 0..255
|
rgb mix(rgb a, rgb b, int k); // a -> b, k 0..255
|
||||||
int sgn(const fx_t &f, int v); // v, negated when reversed
|
int sgn(const fx_t &f, int v); // v unchanged; reverse is applied in led_at only
|
||||||
int led_at(const fx_t &f, int i); // logical index -> physical (reverse)
|
int led_at(const fx_t &f, int i); // logical index -> physical (mirrors when reverse)
|
||||||
void put(fx_t &f, int phys, rgb c);
|
void put(fx_t &f, int phys, rgb c);
|
||||||
void putl(fx_t &f, int logical, rgb c);
|
void putl(fx_t &f, int logical, rgb c);
|
||||||
void fill(fx_t &f, rgb c);
|
void fill(fx_t &f, rgb c);
|
||||||
@@ -121,6 +121,7 @@ bool fx_chase(fx_t &f, st_t &s);
|
|||||||
bool fx_circle(fx_t &f, st_t &s);
|
bool fx_circle(fx_t &f, st_t &s);
|
||||||
bool fx_clock_sweep(fx_t &f, st_t &s);
|
bool fx_clock_sweep(fx_t &f, st_t &s);
|
||||||
bool fx_colour_cycle(fx_t &f, st_t &s);
|
bool fx_colour_cycle(fx_t &f, st_t &s);
|
||||||
|
bool fx_rainbow(fx_t &f, st_t &s);
|
||||||
bool fx_flicker(fx_t &f, st_t &s);
|
bool fx_flicker(fx_t &f, st_t &s);
|
||||||
bool fx_gradient_wipe(fx_t &f, st_t &s);
|
bool fx_gradient_wipe(fx_t &f, st_t &s);
|
||||||
bool fx_hit(fx_t &f, st_t &s);
|
bool fx_hit(fx_t &f, st_t &s);
|
||||||
@@ -129,6 +130,7 @@ bool fx_keyframes(fx_t &f, st_t &s);
|
|||||||
bool fx_orbit(fx_t &f, st_t &s);
|
bool fx_orbit(fx_t &f, st_t &s);
|
||||||
bool fx_pulse(fx_t &f, st_t &s);
|
bool fx_pulse(fx_t &f, st_t &s);
|
||||||
bool fx_transition(fx_t &f, st_t &s);
|
bool fx_transition(fx_t &f, st_t &s);
|
||||||
|
bool fx_wipe(fx_t &f, st_t &s);
|
||||||
bool fx_strobe_burst(fx_t &f, st_t &s);
|
bool fx_strobe_burst(fx_t &f, st_t &s);
|
||||||
bool fx_plasma(fx_t &f, st_t &s);
|
bool fx_plasma(fx_t &f, st_t &s);
|
||||||
|
|
||||||
|
|||||||
+65
-16
@@ -268,8 +268,7 @@ bool fx_chase(fx_t &f, st_t &s)
|
|||||||
(void)nc;
|
(void)nc;
|
||||||
int on_len = nz(f.pr->n[1], 3);
|
int on_len = nz(f.pr->n[1], 3);
|
||||||
int off_len = nz(f.pr->n[2], 2);
|
int off_len = nz(f.pr->n[2], 2);
|
||||||
int step = abs(sgn(f, nz(f.pr->n[3], 1)));
|
int step = f.pr->n[3] == 0 ? 1 : f.pr->n[3]; // negative steps walk the other way
|
||||||
if (step < 1) step = 1;
|
|
||||||
int period = on_len + off_len;
|
int period = on_len + off_len;
|
||||||
if (first_call(s)) {
|
if (first_call(s)) {
|
||||||
s.last = f.now;
|
s.last = f.now;
|
||||||
@@ -284,7 +283,7 @@ bool fx_chase(fx_t &f, st_t &s)
|
|||||||
int m = pmod(i + s.phase, period);
|
int m = pmod(i + s.phase, period);
|
||||||
putl(f, i, m < on_len ? col : bgc);
|
putl(f, i, m < on_len ? col : bgc);
|
||||||
}
|
}
|
||||||
s.phase = pmod(s.phase + sgn(f, step), period);
|
s.phase = pmod(s.phase + step, period);
|
||||||
return !f.pr->autorun;
|
return !f.pr->autorun;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,10 +295,9 @@ bool fx_chase(fx_t &f, st_t &s)
|
|||||||
rgb color1 = ab(nc > 1 ? c[1] : c[0], b);
|
rgb color1 = ab(nc > 1 ? c[1] : c[0], b);
|
||||||
int n1 = nz(f.pr->n[1], 1);
|
int n1 = nz(f.pr->n[1], 1);
|
||||||
int n2 = nz(f.pr->n[2], 1);
|
int n2 = nz(f.pr->n[2], 1);
|
||||||
// Always move forward: a negative n3/n4 would otherwise make the dot bounce back.
|
// Steps may be negative: a negative n3/n4 walks the dot the other way. 0 (unset) means 1.
|
||||||
// sgn() still applies the preset's reverse flag.
|
int n3 = f.pr->n[3] == 0 ? 1 : f.pr->n[3];
|
||||||
int n3 = sgn(f, abs(f.pr->n[3]));
|
int n4 = f.pr->n[4] == 0 ? 1 : f.pr->n[4];
|
||||||
int n4 = sgn(f, abs(f.pr->n[4]));
|
|
||||||
int seg = n1 + n2;
|
int seg = n1 + n2;
|
||||||
int max_pos = nled + seg;
|
int max_pos = nled + seg;
|
||||||
auto position = [&](int sc) {
|
auto position = [&](int sc) {
|
||||||
@@ -313,7 +311,7 @@ bool fx_chase(fx_t &f, st_t &s)
|
|||||||
};
|
};
|
||||||
if (!f.pr->autorun) {
|
if (!f.pr->autorun) {
|
||||||
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
|
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
|
||||||
s.sc = (s.sc + 1) % 2;
|
s.sc = (s.sc + 1) % (2 * max_pos); // the dot walks the whole cycle; even modulus keeps the parity
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
uint32_t dur_ms = f.pr->delay < 10 ? 10 : f.pr->delay;
|
uint32_t dur_ms = f.pr->delay < 10 ? 10 : f.pr->delay;
|
||||||
@@ -322,7 +320,7 @@ bool fx_chase(fx_t &f, st_t &s)
|
|||||||
}
|
}
|
||||||
if ((int32_t)(f.now - s.last) >= (int32_t)dur_ms) {
|
if ((int32_t)(f.now - s.last) >= (int32_t)dur_ms) {
|
||||||
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
|
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
|
||||||
s.sc = (s.sc + 1) % 2;
|
s.sc = (s.sc + 1) % (2 * max_pos); // the dot walks the whole cycle; even modulus keeps the parity
|
||||||
s.last += dur_ms;
|
s.last += dur_ms;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -495,6 +493,24 @@ bool fx_colour_cycle(fx_t &f, st_t &s)
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Rainbow: the spectrum wheel scrolling at n1 steps per frame (the controller's "rainbow" pattern)
|
||||||
|
bool fx_rainbow(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
int step_amount = nz(f.pr->n[1], 1);
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
rainbow_render(f, s.phase);
|
||||||
|
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
|
||||||
|
if (!due(f.now, s.last, d)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
rainbow_render(f, s.phase);
|
||||||
|
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// ---- flicker -----------------------------------------------------------------------------------
|
// ---- flicker -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
bool fx_flicker(fx_t &f, st_t &s)
|
bool fx_flicker(fx_t &f, st_t &s)
|
||||||
@@ -787,6 +803,41 @@ bool fx_pulse(fx_t &f, st_t &s)
|
|||||||
|
|
||||||
// ---- transition --------------------------------------------------------------------------------
|
// ---- transition --------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Wipe: the next colour sweeps in from the first LED to the last over `delay` ms, then becomes the
|
||||||
|
// current colour and the one after it starts wiping in.
|
||||||
|
bool fx_wipe(fx_t &f, st_t &s)
|
||||||
|
{
|
||||||
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
|
int nc = get_colours(f, &WHITE, 1, c);
|
||||||
|
int b = f.pr->brightness;
|
||||||
|
if (nc == 1) {
|
||||||
|
fill(f, ab(c[0], b));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (first_call(s)) {
|
||||||
|
s.aux = f.now;
|
||||||
|
}
|
||||||
|
int duration = f.pr->delay < 10 ? 10 : (int)f.pr->delay;
|
||||||
|
int elapsed = (int)(f.now - s.aux);
|
||||||
|
if (elapsed >= duration) {
|
||||||
|
if (!f.pr->autorun) {
|
||||||
|
fill(f, ab(c[(s.ci + 1) % nc], b));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
s.ci = (s.ci + 1) % nc;
|
||||||
|
s.aux = f.now;
|
||||||
|
elapsed = 0;
|
||||||
|
}
|
||||||
|
rgb cur = c[s.ci % nc];
|
||||||
|
rgb nxt = c[(s.ci + 1) % nc];
|
||||||
|
int front = (elapsed * f.n) / duration; // LEDs already showing the next colour
|
||||||
|
for (int i = 0; i < f.n; i++) {
|
||||||
|
putl(f, i, ab(i < front ? nxt : cur, b));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Transition: the whole bar shows one colour, which fades from each colour to the next over `delay` ms.
|
||||||
bool fx_transition(fx_t &f, st_t &s)
|
bool fx_transition(fx_t &f, st_t &s)
|
||||||
{
|
{
|
||||||
rgb c[PATTERN_MAX_COLOURS];
|
rgb c[PATTERN_MAX_COLOURS];
|
||||||
@@ -808,14 +859,12 @@ bool fx_transition(fx_t &f, st_t &s)
|
|||||||
}
|
}
|
||||||
s.ci = (s.ci + 1) % nc;
|
s.ci = (s.ci + 1) % nc;
|
||||||
s.aux = f.now;
|
s.aux = f.now;
|
||||||
return false;
|
elapsed = 0;
|
||||||
}
|
}
|
||||||
rgb c1 = c[s.ci % nc];
|
rgb cur = c[s.ci % nc];
|
||||||
rgb c2 = c[(s.ci + 1) % nc];
|
rgb nxt = c[(s.ci + 1) % nc];
|
||||||
float factor = (float)elapsed / duration;
|
int k = (elapsed * 255) / duration; // 0 = all current colour, 255 = all next colour
|
||||||
rgb m = { (int)(c1.r + (c2.r - c1.r) * factor), (int)(c1.g + (c2.g - c1.g) * factor),
|
fill(f, ab(mix(cur, nxt, k), b));
|
||||||
(int)(c1.b + (c2.b - c1.b) * factor) };
|
|
||||||
fill(f, ab(m, b));
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+5
-3
@@ -634,9 +634,11 @@ bool fx_radiate(fx_t &f, st_t &s)
|
|||||||
int nc = get_colours(f, def, 1, c);
|
int nc = get_colours(f, def, 1, c);
|
||||||
int b = f.pr->brightness;
|
int b = f.pr->brightness;
|
||||||
rgb off_c = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
rgb off_c = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
|
||||||
int spacing = nz(f.pr->n[1], 1);
|
// n1 spacing (LEDs); n2/n3 rise and fall in ms, default half a period each so a ring is seen
|
||||||
int outward = nz(f.pr->n[2], 1);
|
int half = (int)(period_of(f) / 2) < 1 ? 1 : (int)(period_of(f) / 2);
|
||||||
int ret = nz(f.pr->n[3], 1);
|
int spacing = nz(f.pr->n[1], 24);
|
||||||
|
int outward = nz(f.pr->n[2], half);
|
||||||
|
int ret = nz(f.pr->n[3], half);
|
||||||
int maxd = spacing / 2;
|
int maxd = spacing / 2;
|
||||||
int life = outward + ret;
|
int life = outward + ret;
|
||||||
int num = f.n;
|
int num = f.n;
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
|
||||||
#include "esp_random.h"
|
#include "esp_random.h"
|
||||||
|
#include "beat_sync.h"
|
||||||
#include "effects.h"
|
#include "effects.h"
|
||||||
|
|
||||||
int clampi(int v, int lo, int hi)
|
int clampi(int v, int lo, int hi)
|
||||||
@@ -57,9 +58,9 @@ rgb mix(rgb a, rgb b, int k)
|
|||||||
return o;
|
return o;
|
||||||
}
|
}
|
||||||
|
|
||||||
int sgn(const fx_t &f, int v)
|
int sgn(const fx_t &, int v)
|
||||||
{
|
{
|
||||||
return f.pr->reverse ? -v : v;
|
return v; // reverse mirrors the strip only (led_at), it does not change direction
|
||||||
}
|
}
|
||||||
|
|
||||||
int led_at(const fx_t &f, int i)
|
int led_at(const fx_t &f, int i)
|
||||||
@@ -95,13 +96,11 @@ bool due(uint32_t now, uint32_t &last, uint32_t d)
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The beat is 500 ms here (there is no beat source on this board)
|
// A preset's timing is always milliseconds. Beats belong to sequences and animations, which the
|
||||||
uint32_t dur(const fx_t &f, int v)
|
// controller plays, so a preset never follows the tempo.
|
||||||
|
uint32_t dur(const fx_t &, int v)
|
||||||
{
|
{
|
||||||
if (v < 0) {
|
return v < 0 ? 0 : (uint32_t)v;
|
||||||
v = 0;
|
|
||||||
}
|
|
||||||
return f.pr->beat_time ? (uint32_t)(v * 500 / 4) : (uint32_t)v;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int get_colours(const fx_t &f, const rgb *def, int ndef, rgb *out)
|
int get_colours(const fx_t &f, const rgb *def, int ndef, rgb *out)
|
||||||
|
|||||||
@@ -0,0 +1,443 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* Port of led-driver/src/espnow_rx.py (the MicroPython driver) and the announce and ping parts of
|
||||||
|
* espnow_transport.py. Frames arrive in the ESP-NOW callback; beats are taken there, the rest is queued for
|
||||||
|
* the link task, which does the reliable-link work and calls ctrl_handle.
|
||||||
|
*/
|
||||||
|
#include "espnow_link.h"
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "esp_check.h"
|
||||||
|
#include "esp_log.h"
|
||||||
|
#include "esp_now.h"
|
||||||
|
#include "esp_random.h"
|
||||||
|
#include "esp_timer.h"
|
||||||
|
#include "esp_wifi.h"
|
||||||
|
#include "freertos/FreeRTOS.h"
|
||||||
|
#include "freertos/queue.h"
|
||||||
|
#include "freertos/task.h"
|
||||||
|
|
||||||
|
#include "beat_sync.h"
|
||||||
|
#include "ctrl_msg.h"
|
||||||
|
#include "net.h"
|
||||||
|
#include "settings.h"
|
||||||
|
|
||||||
|
static const char *TAG = "espnow";
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr uint8_t kMagic = 0x4C;
|
||||||
|
constexpr uint8_t kAnnounce = 0x01;
|
||||||
|
constexpr uint8_t kData = 0x20;
|
||||||
|
constexpr uint8_t kAck = 0x21;
|
||||||
|
constexpr uint8_t kDigest = 0x22;
|
||||||
|
constexpr uint8_t kResync = 0x23;
|
||||||
|
constexpr uint8_t kBeat = 0x25;
|
||||||
|
constexpr uint8_t kPingReq = 0x05;
|
||||||
|
constexpr uint8_t kPingRsp = 0x06;
|
||||||
|
constexpr uint8_t kFlagAck = 1;
|
||||||
|
constexpr uint8_t kFlagCommit = 2;
|
||||||
|
|
||||||
|
constexpr size_t kHdr = 9; // DATA header: [4C][20][flags][seq u16][ver u16][idx][cnt]
|
||||||
|
constexpr size_t kFragMax = 238; // bytes of the inner packet per DATA frame
|
||||||
|
constexpr int kMaxFrags = 32;
|
||||||
|
constexpr int kAsmSlots = 2; // messages being reassembled at once
|
||||||
|
constexpr int kDoneMax = 16; // recent messages kept for duplicate detection
|
||||||
|
constexpr int kInboxLen = 24;
|
||||||
|
constexpr int64_t kAsmTimeoutUs = 3000000;
|
||||||
|
constexpr int64_t kResyncGapUs = 3000000;
|
||||||
|
constexpr int64_t kAnnounceUs[3] = { 300000, 1300000, 2600000 };
|
||||||
|
// After the boot announces, repeat every 10 s: the radio's channel can hop while the client scans for its
|
||||||
|
// network, so one burst can be missed. The controller updates the device it already has, so repeats are harmless.
|
||||||
|
constexpr int64_t kAnnounceEveryUs = 10000000;
|
||||||
|
|
||||||
|
struct Frame {
|
||||||
|
uint8_t mac[6];
|
||||||
|
uint16_t len;
|
||||||
|
uint8_t data[250];
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Asm {
|
||||||
|
bool used;
|
||||||
|
uint8_t mac[6];
|
||||||
|
uint16_t seq;
|
||||||
|
uint8_t cnt;
|
||||||
|
uint8_t flags;
|
||||||
|
uint16_t ver;
|
||||||
|
uint32_t mask;
|
||||||
|
uint16_t lens[kMaxFrags];
|
||||||
|
uint8_t *buf; // cnt * kFragMax
|
||||||
|
int64_t last_us;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Done {
|
||||||
|
uint8_t mac[6];
|
||||||
|
uint16_t seq;
|
||||||
|
};
|
||||||
|
|
||||||
|
QueueHandle_t s_inbox;
|
||||||
|
bool s_started;
|
||||||
|
espnow_stats_t s_st;
|
||||||
|
Asm s_asm[kAsmSlots];
|
||||||
|
Done s_done[kDoneMax];
|
||||||
|
int s_ndone;
|
||||||
|
uint16_t s_ver; // state version this driver has
|
||||||
|
bool s_resync_pending;
|
||||||
|
int64_t s_resync_at;
|
||||||
|
int64_t s_last_resync;
|
||||||
|
bool s_ping_pending;
|
||||||
|
int64_t s_ping_at;
|
||||||
|
uint8_t s_ping_mac[6];
|
||||||
|
uint32_t s_ping_id;
|
||||||
|
int s_announce_left;
|
||||||
|
int64_t s_announce_base;
|
||||||
|
int64_t s_next_announce;
|
||||||
|
|
||||||
|
// ---- sending ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
esp_err_t send_to(const uint8_t mac[6], const uint8_t *data, size_t len)
|
||||||
|
{
|
||||||
|
if (!esp_now_is_peer_exist(mac)) {
|
||||||
|
esp_now_peer_info_t p = {};
|
||||||
|
memcpy(p.peer_addr, mac, 6);
|
||||||
|
p.ifidx = WIFI_IF_STA;
|
||||||
|
p.encrypt = false;
|
||||||
|
esp_err_t e = esp_now_add_peer(&p);
|
||||||
|
if (e != ESP_OK && e != ESP_ERR_ESPNOW_EXIST) {
|
||||||
|
s_st.send_fail++;
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
esp_err_t e = esp_now_send(mac, data, len);
|
||||||
|
if (e == ESP_OK) {
|
||||||
|
s_st.sent++;
|
||||||
|
} else {
|
||||||
|
s_st.send_fail++;
|
||||||
|
}
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t kBroadcast[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
|
||||||
|
|
||||||
|
void send_announce(void)
|
||||||
|
{
|
||||||
|
uint8_t pkt[250];
|
||||||
|
size_t n = ctrl_build_announce(pkt, sizeof(pkt));
|
||||||
|
if (n) {
|
||||||
|
send_to(kBroadcast, pkt, n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void send_ack(const uint8_t mac[6], uint16_t seq, uint8_t cnt, uint32_t mask)
|
||||||
|
{
|
||||||
|
uint8_t p[10] = { kMagic, kAck, 0, (uint8_t)(seq & 0xFF), (uint8_t)(seq >> 8), cnt,
|
||||||
|
(uint8_t)(mask & 0xFF), (uint8_t)(mask >> 8), (uint8_t)(mask >> 16), (uint8_t)(mask >> 24) };
|
||||||
|
send_to(mac, p, sizeof(p));
|
||||||
|
s_st.acks++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void send_resync(void)
|
||||||
|
{
|
||||||
|
if (!s_st.master_seen) return;
|
||||||
|
uint8_t p[4] = { kMagic, kResync, (uint8_t)(s_ver & 0xFF), (uint8_t)(s_ver >> 8) };
|
||||||
|
send_to(s_st.master, p, sizeof(p));
|
||||||
|
s_st.resyncs++;
|
||||||
|
s_last_resync = esp_timer_get_time();
|
||||||
|
}
|
||||||
|
|
||||||
|
void send_ping_rsp(void)
|
||||||
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
size_t nl = strlen(n.hostname);
|
||||||
|
uint8_t p[250];
|
||||||
|
p[0] = kMagic;
|
||||||
|
p[1] = kPingRsp;
|
||||||
|
p[2] = s_ping_id & 0xFF;
|
||||||
|
p[3] = (s_ping_id >> 8) & 0xFF;
|
||||||
|
p[4] = (s_ping_id >> 16) & 0xFF;
|
||||||
|
p[5] = (s_ping_id >> 24) & 0xFF;
|
||||||
|
p[6] = (uint8_t)nl;
|
||||||
|
memcpy(p + 7, n.hostname, nl);
|
||||||
|
send_to(s_ping_mac, p, 7 + nl);
|
||||||
|
s_st.pings++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- receiving (link task) --------------------------------------------------------------------
|
||||||
|
|
||||||
|
void asm_free(Asm &a)
|
||||||
|
{
|
||||||
|
free(a.buf);
|
||||||
|
a.buf = nullptr;
|
||||||
|
a.used = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Asm *asm_find(const uint8_t mac[6], uint16_t seq)
|
||||||
|
{
|
||||||
|
for (auto &a : s_asm) {
|
||||||
|
if (a.used && a.seq == seq && memcmp(a.mac, mac, 6) == 0) return &a;
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool done_has(const uint8_t mac[6], uint16_t seq)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < s_ndone; i++) {
|
||||||
|
if (s_done[i].seq == seq && memcmp(s_done[i].mac, mac, 6) == 0) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void done_add(const uint8_t mac[6], uint16_t seq)
|
||||||
|
{
|
||||||
|
if (s_ndone == kDoneMax) {
|
||||||
|
memmove(&s_done[0], &s_done[1], sizeof(Done) * (kDoneMax - 1));
|
||||||
|
s_ndone--;
|
||||||
|
}
|
||||||
|
memcpy(s_done[s_ndone].mac, mac, 6);
|
||||||
|
s_done[s_ndone].seq = seq;
|
||||||
|
s_ndone++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void on_data(const uint8_t mac[6], const uint8_t *data, size_t len, int64_t now)
|
||||||
|
{
|
||||||
|
if (len <= kHdr) return;
|
||||||
|
uint8_t flags = data[2];
|
||||||
|
uint16_t seq = (uint16_t)(data[3] | (data[4] << 8));
|
||||||
|
uint16_t ver = (uint16_t)(data[5] | (data[6] << 8));
|
||||||
|
uint8_t idx = data[7], cnt = data[8];
|
||||||
|
if (cnt == 0 || cnt > kMaxFrags || idx >= cnt) return;
|
||||||
|
memcpy(s_st.master, mac, 6);
|
||||||
|
s_st.master_seen = true;
|
||||||
|
uint32_t full = cnt < 32 ? ((1u << cnt) - 1) : 0xFFFFFFFFu;
|
||||||
|
if (done_has(mac, seq)) {
|
||||||
|
s_st.dups++;
|
||||||
|
if (flags & kFlagAck) send_ack(mac, seq, cnt, full); // our earlier ack was lost
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Asm *a = asm_find(mac, seq);
|
||||||
|
if (!a) {
|
||||||
|
// a free slot, else the one idle longest
|
||||||
|
Asm *pick = nullptr;
|
||||||
|
for (auto &s : s_asm) {
|
||||||
|
if (!s.used) { pick = &s; break; }
|
||||||
|
}
|
||||||
|
if (!pick) {
|
||||||
|
pick = &s_asm[0];
|
||||||
|
for (auto &s : s_asm) {
|
||||||
|
if (s.last_us < pick->last_us) pick = &s;
|
||||||
|
}
|
||||||
|
asm_free(*pick);
|
||||||
|
}
|
||||||
|
pick->buf = (uint8_t *)malloc((size_t)cnt * kFragMax);
|
||||||
|
if (!pick->buf) return;
|
||||||
|
pick->used = true;
|
||||||
|
memcpy(pick->mac, mac, 6);
|
||||||
|
pick->seq = seq;
|
||||||
|
pick->cnt = cnt;
|
||||||
|
pick->flags = flags;
|
||||||
|
pick->ver = ver;
|
||||||
|
pick->mask = 0;
|
||||||
|
memset(pick->lens, 0, sizeof(pick->lens));
|
||||||
|
a = pick;
|
||||||
|
}
|
||||||
|
size_t frag = len - kHdr;
|
||||||
|
if (frag > kFragMax) frag = kFragMax;
|
||||||
|
memcpy(a->buf + (size_t)idx * kFragMax, data + kHdr, frag);
|
||||||
|
a->lens[idx] = (uint16_t)frag;
|
||||||
|
a->mask |= 1u << idx;
|
||||||
|
a->last_us = now;
|
||||||
|
if (flags & kFlagAck) send_ack(mac, seq, cnt, a->mask);
|
||||||
|
if (a->mask != full) return;
|
||||||
|
|
||||||
|
// complete: the message is the fragments in order
|
||||||
|
size_t total = 0;
|
||||||
|
for (int i = 0; i < cnt; i++) total += a->lens[i];
|
||||||
|
uint8_t *msg = (uint8_t *)malloc(total ? total : 1);
|
||||||
|
if (msg) {
|
||||||
|
size_t off = 0;
|
||||||
|
for (int i = 0; i < cnt; i++) {
|
||||||
|
memcpy(msg + off, a->buf + (size_t)i * kFragMax, a->lens[i]);
|
||||||
|
off += a->lens[i];
|
||||||
|
}
|
||||||
|
done_add(mac, seq);
|
||||||
|
s_st.msgs++;
|
||||||
|
ctrl_handle(mac, msg, total);
|
||||||
|
free(msg);
|
||||||
|
}
|
||||||
|
if ((a->flags & kFlagCommit) && a->ver) {
|
||||||
|
s_ver = a->ver;
|
||||||
|
s_st.ver = a->ver;
|
||||||
|
s_resync_pending = false;
|
||||||
|
}
|
||||||
|
asm_free(*a);
|
||||||
|
}
|
||||||
|
|
||||||
|
void on_digest(const uint8_t mac[6], const uint8_t *data, size_t len, int64_t now)
|
||||||
|
{
|
||||||
|
if (len < 4) return;
|
||||||
|
memcpy(s_st.master, mac, 6);
|
||||||
|
s_st.master_seen = true;
|
||||||
|
uint16_t ver = (uint16_t)(data[2] | (data[3] << 8));
|
||||||
|
if (ver == 0 || ver == s_ver || s_resync_pending) return;
|
||||||
|
if (s_last_resync && now - s_last_resync < kResyncGapUs) return;
|
||||||
|
// spread the drivers' resync requests over a few hundred ms
|
||||||
|
s_resync_at = now + (int64_t)(esp_random() % 400) * 1000;
|
||||||
|
s_resync_pending = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void handle_frame(const Frame &f, int64_t now)
|
||||||
|
{
|
||||||
|
if (f.len < 2) return;
|
||||||
|
if (f.data[0] == kMagic) {
|
||||||
|
switch (f.data[1]) {
|
||||||
|
case kData:
|
||||||
|
on_data(f.mac, f.data, f.len, now);
|
||||||
|
return;
|
||||||
|
case kDigest:
|
||||||
|
on_digest(f.mac, f.data, f.len, now);
|
||||||
|
return;
|
||||||
|
case kPingReq:
|
||||||
|
if (f.len >= 6) {
|
||||||
|
s_ping_id = f.data[2] | (f.data[3] << 8) | (f.data[4] << 16) | ((uint32_t)f.data[5] << 24);
|
||||||
|
memcpy(s_ping_mac, f.mac, 6);
|
||||||
|
s_ping_at = now + (int64_t)(50 + esp_random() % 451) * 1000; // 50-500 ms, as the other drivers
|
||||||
|
s_ping_pending = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
case kAck:
|
||||||
|
case kResync:
|
||||||
|
case 0x24: // echo: bench only
|
||||||
|
case kPingRsp:
|
||||||
|
case kAnnounce:
|
||||||
|
return; // controller-bound messages, not for a driver
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctrl_handle(f.mac, f.data, f.len);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The ESP-NOW receive callback: beats are taken here, anything else is queued
|
||||||
|
void on_recv(const esp_now_recv_info_t *info, const uint8_t *data, int len)
|
||||||
|
{
|
||||||
|
s_st.frames++;
|
||||||
|
if (len < 2 || len > 250) return;
|
||||||
|
if (data[0] == kMagic && data[1] == kBeat) {
|
||||||
|
beat_on_frame(data, (size_t)len);
|
||||||
|
s_st.beats++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Frame f;
|
||||||
|
memcpy(f.mac, info->src_addr, 6);
|
||||||
|
f.len = (uint16_t)len;
|
||||||
|
memcpy(f.data, data, len);
|
||||||
|
if (xQueueSend(s_inbox, &f, 0) != pdTRUE) {
|
||||||
|
s_st.dropped++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// One pass of the link: up to a burst of received frames (waiting up to wait for the first), then the timed sends
|
||||||
|
// (announces, resync, ping reply) and expired reassemblies
|
||||||
|
void link_pass(TickType_t wait)
|
||||||
|
{
|
||||||
|
Frame f;
|
||||||
|
// at most a burst of frames per pass, then the other tasks run
|
||||||
|
if (xQueueReceive(s_inbox, &f, wait) == pdTRUE) {
|
||||||
|
for (int burst = 0; burst < 8; burst++) {
|
||||||
|
handle_frame(f, esp_timer_get_time());
|
||||||
|
if (xQueueReceive(s_inbox, &f, 0) != pdTRUE) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (wait) {
|
||||||
|
vTaskDelay(1);
|
||||||
|
}
|
||||||
|
int64_t now = esp_timer_get_time();
|
||||||
|
if (s_announce_left > 0 && now >= s_announce_base + kAnnounceUs[3 - s_announce_left]) {
|
||||||
|
s_announce_left--;
|
||||||
|
send_announce();
|
||||||
|
if (s_announce_left == 0) {
|
||||||
|
s_next_announce = now + kAnnounceEveryUs;
|
||||||
|
}
|
||||||
|
} else if (s_announce_left == 0 && now >= s_next_announce) {
|
||||||
|
s_next_announce = now + kAnnounceEveryUs;
|
||||||
|
send_announce();
|
||||||
|
}
|
||||||
|
if (s_resync_pending && now >= s_resync_at) {
|
||||||
|
s_resync_pending = false;
|
||||||
|
send_resync();
|
||||||
|
}
|
||||||
|
if (s_ping_pending && now >= s_ping_at) {
|
||||||
|
s_ping_pending = false;
|
||||||
|
send_ping_rsp();
|
||||||
|
}
|
||||||
|
for (auto &a : s_asm) {
|
||||||
|
if (a.used && now - a.last_us > kAsmTimeoutUs) asm_free(a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void link_task(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
for (;;) {
|
||||||
|
link_pass(pdMS_TO_TICKS(5));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
esp_err_t espnow_link_start(void)
|
||||||
|
{
|
||||||
|
if (s_started) {
|
||||||
|
return ESP_ERR_INVALID_STATE;
|
||||||
|
}
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (!n.espnow_enabled) {
|
||||||
|
ESP_LOGI(TAG, "ESP-NOW is off in settings");
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
ctrl_init();
|
||||||
|
// ESP-NOW uses the radio's channel: the access point's, or the router's when the client is joined.
|
||||||
|
// It is not set here, since changing the channel while the client connects breaks the association.
|
||||||
|
uint8_t primary = n.espnow_channel;
|
||||||
|
wifi_second_chan_t second;
|
||||||
|
if (esp_wifi_get_channel(&primary, &second) == ESP_OK) {
|
||||||
|
s_st.channel = primary;
|
||||||
|
}
|
||||||
|
ESP_RETURN_ON_ERROR(esp_now_init(), TAG, "esp_now_init");
|
||||||
|
ESP_RETURN_ON_ERROR(esp_now_register_recv_cb(on_recv), TAG, "recv cb");
|
||||||
|
esp_now_peer_info_t bcast = {};
|
||||||
|
memcpy(bcast.peer_addr, kBroadcast, 6);
|
||||||
|
bcast.ifidx = WIFI_IF_STA;
|
||||||
|
esp_now_add_peer(&bcast); // it may already exist
|
||||||
|
|
||||||
|
s_inbox = xQueueCreate(kInboxLen, sizeof(Frame));
|
||||||
|
if (!s_inbox) {
|
||||||
|
return ESP_ERR_NO_MEM;
|
||||||
|
}
|
||||||
|
s_announce_left = 3;
|
||||||
|
s_announce_base = esp_timer_get_time();
|
||||||
|
s_st.running = true;
|
||||||
|
s_started = true;
|
||||||
|
xTaskCreate(link_task, "espnow_link", 6144, nullptr, 5, nullptr);
|
||||||
|
ESP_LOGI(TAG, "ESP-NOW on channel %u", n.espnow_channel);
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
void espnow_link_poll(void)
|
||||||
|
{
|
||||||
|
if (s_started) {
|
||||||
|
link_pass(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void espnow_link_stats(espnow_stats_t *out)
|
||||||
|
{
|
||||||
|
*out = s_st;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/*
|
||||||
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
|
*
|
||||||
|
* ESP-NOW link to led-controller: the 0x4C wire protocol the MicroPython drivers speak. The driver announces
|
||||||
|
* itself at boot, takes the controller's reliable messages (acked, reassembled, deduplicated, resynced by
|
||||||
|
* digest), answers pings, and passes everything else to ctrl_msg. Beats set the tempo (beat_sync).
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "esp_err.h"
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
bool running;
|
||||||
|
uint8_t channel;
|
||||||
|
bool master_seen;
|
||||||
|
uint8_t master[6];
|
||||||
|
uint32_t msgs; // reliable messages delivered
|
||||||
|
uint32_t dups; // duplicate fragments of a message already delivered
|
||||||
|
uint32_t acks;
|
||||||
|
uint32_t resyncs;
|
||||||
|
uint32_t pings;
|
||||||
|
uint32_t beats;
|
||||||
|
uint32_t dropped; // frames lost to a full inbox
|
||||||
|
uint32_t frames; // every ESP-NOW frame the radio delivered
|
||||||
|
uint32_t sent;
|
||||||
|
uint32_t send_fail;
|
||||||
|
uint16_t ver; // state version of the last committed message
|
||||||
|
} espnow_stats_t;
|
||||||
|
|
||||||
|
/** @brief Start ESP-NOW and the link task, if enabled in settings. Call after net_start(). */
|
||||||
|
esp_err_t espnow_link_start(void);
|
||||||
|
|
||||||
|
/** @brief One pass of the link without waiting: the received frames, then the timed sends. The link task runs it
|
||||||
|
* in a loop; a build without that task (the browser simulator) calls it from a timer. */
|
||||||
|
void espnow_link_poll(void);
|
||||||
|
|
||||||
|
/** @brief Copy the link's counters and state. */
|
||||||
|
void espnow_link_stats(espnow_stats_t *out);
|
||||||
@@ -5,10 +5,12 @@
|
|||||||
#include "nvs_flash.h"
|
#include "nvs_flash.h"
|
||||||
|
|
||||||
#include "ddp.h"
|
#include "ddp.h"
|
||||||
|
#include "espnow_link.h"
|
||||||
#include "net.h"
|
#include "net.h"
|
||||||
#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";
|
||||||
@@ -29,7 +31,9 @@ extern "C" void app_main(void)
|
|||||||
ESP_ERROR_CHECK(presets_init());
|
ESP_ERROR_CHECK(presets_init());
|
||||||
presets_apply_startup();
|
presets_apply_startup();
|
||||||
ESP_ERROR_CHECK(net_start());
|
ESP_ERROR_CHECK(net_start());
|
||||||
|
espnow_link_start(); // ESP-NOW from led-controller, if enabled in settings
|
||||||
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();
|
||||||
|
|
||||||
|
|||||||
+89
-6
@@ -8,6 +8,7 @@
|
|||||||
#include "esp_log.h"
|
#include "esp_log.h"
|
||||||
#include "esp_mac.h"
|
#include "esp_mac.h"
|
||||||
#include "esp_netif.h"
|
#include "esp_netif.h"
|
||||||
|
#include "esp_system.h"
|
||||||
#include "esp_timer.h"
|
#include "esp_timer.h"
|
||||||
#include "esp_wifi.h"
|
#include "esp_wifi.h"
|
||||||
#include "mdns.h"
|
#include "mdns.h"
|
||||||
@@ -15,7 +16,7 @@
|
|||||||
|
|
||||||
static const char *TAG = "net";
|
static const char *TAG = "net";
|
||||||
|
|
||||||
#define AP_CHANNEL 1
|
#define AP_CHANNEL 1 // the access point's channel when ESP-NOW is off; otherwise the ESP-NOW channel
|
||||||
#define AP_MAX_CLIENTS 4
|
#define AP_MAX_CLIENTS 4
|
||||||
#define RETRY_MAX_MS 30000
|
#define RETRY_MAX_MS 30000
|
||||||
|
|
||||||
@@ -47,21 +48,31 @@ static void apply_sta_config(const wifi_creds_t *c)
|
|||||||
esp_wifi_set_config(WIFI_IF_STA, &cfg);
|
esp_wifi_set_config(WIFI_IF_STA, &cfg);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Turn the access point on (with its led-XXXXXX name, open) or off. The client keeps running either way.
|
// Turn the access point on (its saved name and password, or led-XXXXXX and open) or off.
|
||||||
|
// The client keeps running either way.
|
||||||
static void apply_ap(bool on)
|
static void apply_ap(bool on)
|
||||||
{
|
{
|
||||||
if (on) {
|
if (on) {
|
||||||
char ssid[16];
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
char ssid[33];
|
||||||
net_ap_ssid(ssid, sizeof(ssid));
|
net_ap_ssid(ssid, sizeof(ssid));
|
||||||
wifi_config_t ap = {};
|
wifi_config_t ap = {};
|
||||||
strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1);
|
strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1);
|
||||||
ap.ap.ssid_len = strlen(ssid);
|
ap.ap.ssid_len = strlen(ssid);
|
||||||
ap.ap.channel = AP_CHANNEL;
|
ap.ap.channel = n.espnow_enabled ? n.espnow_channel : AP_CHANNEL;
|
||||||
ap.ap.max_connection = AP_MAX_CLIENTS;
|
ap.ap.max_connection = AP_MAX_CLIENTS;
|
||||||
|
// A password of 8-63 characters is WPA2; anything else is an open network
|
||||||
|
const size_t plen = strlen(n.ap_pass);
|
||||||
|
if (plen >= 8) {
|
||||||
|
strncpy((char *)ap.ap.password, n.ap_pass, sizeof(ap.ap.password) - 1);
|
||||||
|
ap.ap.authmode = WIFI_AUTH_WPA2_PSK;
|
||||||
|
} else {
|
||||||
ap.ap.authmode = WIFI_AUTH_OPEN;
|
ap.ap.authmode = WIFI_AUTH_OPEN;
|
||||||
|
}
|
||||||
esp_wifi_set_config(WIFI_IF_AP, &ap);
|
esp_wifi_set_config(WIFI_IF_AP, &ap);
|
||||||
esp_wifi_set_mode(WIFI_MODE_APSTA);
|
esp_wifi_set_mode(WIFI_MODE_APSTA);
|
||||||
ESP_LOGI(TAG, "Access point %s on", ssid);
|
ESP_LOGI(TAG, "Access point %s on (%s)", ssid, plen >= 8 ? "WPA2" : "open");
|
||||||
} else {
|
} else {
|
||||||
esp_wifi_set_mode(WIFI_MODE_STA);
|
esp_wifi_set_mode(WIFI_MODE_STA);
|
||||||
ESP_LOGI(TAG, "Access point off");
|
ESP_LOGI(TAG, "Access point off");
|
||||||
@@ -69,17 +80,32 @@ static void apply_ap(bool on)
|
|||||||
s_ap_on = on;
|
s_ap_on = on;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Switch the access point later, from a timer task (not inside a Wi-Fi event)
|
// Switch the access point later, from a timer task (not inside a Wi-Fi event).
|
||||||
|
// s_ap_reapply: the access point stays on but its name or password changed, so restart it with them.
|
||||||
|
static bool s_ap_reapply;
|
||||||
|
|
||||||
static void ap_timer_cb(void *arg)
|
static void ap_timer_cb(void *arg)
|
||||||
{
|
{
|
||||||
(void)arg;
|
(void)arg;
|
||||||
if (s_ap_want != s_ap_on) {
|
if (s_ap_want != s_ap_on) {
|
||||||
apply_ap(s_ap_want);
|
apply_ap(s_ap_want);
|
||||||
|
} else if (s_ap_want && s_ap_reapply) {
|
||||||
|
apply_ap(true);
|
||||||
}
|
}
|
||||||
|
s_ap_reapply = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
static esp_err_t apply_client_ip(const net_cfg_t *c);
|
static esp_err_t apply_client_ip(const net_cfg_t *c);
|
||||||
|
|
||||||
|
// The Wi-Fi client and ESP-NOW share the radio, and a client that searches for its network hops channels and
|
||||||
|
// breaks ESP-NOW, so only one is on: with ESP-NOW enabled the client stays off (no connect, no retries).
|
||||||
|
static bool client_allowed(void)
|
||||||
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
return !n.espnow_enabled;
|
||||||
|
}
|
||||||
|
|
||||||
static void reconnect_cb(void *arg)
|
static void reconnect_cb(void *arg)
|
||||||
{
|
{
|
||||||
(void)arg;
|
(void)arg;
|
||||||
@@ -89,8 +115,10 @@ static void reconnect_cb(void *arg)
|
|||||||
if (apply_client_ip(&s_pending_net) != ESP_OK) {
|
if (apply_client_ip(&s_pending_net) != ESP_OK) {
|
||||||
ESP_LOGW(TAG, "Client address could not be applied");
|
ESP_LOGW(TAG, "Client address could not be applied");
|
||||||
}
|
}
|
||||||
|
if (client_allowed()) {
|
||||||
esp_wifi_connect();
|
esp_wifi_connect();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static void ap_switch_later(bool on, uint64_t delay_us)
|
static void ap_switch_later(bool on, uint64_t delay_us)
|
||||||
{
|
{
|
||||||
@@ -131,6 +159,9 @@ static esp_err_t apply_client_ip(const net_cfg_t *c)
|
|||||||
static void retry_cb(void *arg)
|
static void retry_cb(void *arg)
|
||||||
{
|
{
|
||||||
(void)arg;
|
(void)arg;
|
||||||
|
if (!client_allowed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
esp_wifi_connect();
|
esp_wifi_connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,7 +181,11 @@ static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *da
|
|||||||
n.use_static = false;
|
n.use_static = false;
|
||||||
apply_client_ip(&n);
|
apply_client_ip(&n);
|
||||||
}
|
}
|
||||||
|
if (!n.espnow_enabled) {
|
||||||
esp_wifi_connect();
|
esp_wifi_connect();
|
||||||
|
} else {
|
||||||
|
ESP_LOGI(TAG, "ESP-NOW is on: the Wi-Fi client stays off");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -186,6 +221,12 @@ static void on_ip_event(void *arg, esp_event_base_t base, int32_t id, void *data
|
|||||||
|
|
||||||
void net_ap_ssid(char *buf, size_t len)
|
void net_ap_ssid(char *buf, size_t len)
|
||||||
{
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (n.ap_ssid[0]) {
|
||||||
|
snprintf(buf, len, "%s", n.ap_ssid);
|
||||||
|
return;
|
||||||
|
}
|
||||||
uint8_t mac[6];
|
uint8_t mac[6];
|
||||||
esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP);
|
esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP);
|
||||||
snprintf(buf, len, "led-%02X%02X%02X", mac[3], mac[4], mac[5]);
|
snprintf(buf, len, "led-%02X%02X%02X", mac[3], mac[4], mac[5]);
|
||||||
@@ -243,6 +284,8 @@ esp_err_t net_start(void)
|
|||||||
}
|
}
|
||||||
|
|
||||||
ESP_ERROR_CHECK(esp_wifi_start());
|
ESP_ERROR_CHECK(esp_wifi_start());
|
||||||
|
// No modem sleep: the radio stays awake so the AP never holds DDP unicast until a beacon
|
||||||
|
ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
|
||||||
|
|
||||||
// mDNS: <hostname>.local, with an HTTP service on port 80
|
// mDNS: <hostname>.local, with an HTTP service on port 80
|
||||||
ESP_ERROR_CHECK(mdns_init());
|
ESP_ERROR_CHECK(mdns_init());
|
||||||
@@ -255,6 +298,11 @@ esp_err_t net_start(void)
|
|||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool net_ap_on(void)
|
||||||
|
{
|
||||||
|
return s_ap_on;
|
||||||
|
}
|
||||||
|
|
||||||
bool net_sta_status(char *ip, size_t ip_len)
|
bool net_sta_status(char *ip, size_t ip_len)
|
||||||
{
|
{
|
||||||
if (ip_len) {
|
if (ip_len) {
|
||||||
@@ -267,12 +315,42 @@ bool net_sta_status(char *ip, size_t ip_len)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Restart after a Wi-Fi change, so the reply goes out first
|
||||||
|
static void restart_cb(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
esp_restart();
|
||||||
|
}
|
||||||
|
|
||||||
esp_err_t net_sta_connect(const wifi_creds_t *c)
|
esp_err_t net_sta_connect(const wifi_creds_t *c)
|
||||||
{
|
{
|
||||||
esp_err_t err = settings_save_wifi(c);
|
esp_err_t err = settings_save_wifi(c);
|
||||||
if (err != ESP_OK) {
|
if (err != ESP_OK) {
|
||||||
return err;
|
return err;
|
||||||
}
|
}
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
if (n.espnow_enabled) {
|
||||||
|
// Wi-Fi and ESP-NOW share the radio, so Wi-Fi mode means ESP-NOW off. Restart into it: the
|
||||||
|
// saved credentials are joined at boot.
|
||||||
|
n.espnow_enabled = false;
|
||||||
|
err = settings_save_net(&n);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
static esp_timer_handle_t restart_timer;
|
||||||
|
if (!restart_timer) {
|
||||||
|
esp_timer_create_args_t a = {};
|
||||||
|
a.callback = restart_cb;
|
||||||
|
a.name = "wifi_restart";
|
||||||
|
err = esp_timer_create(&a, &restart_timer);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ESP_LOGI(TAG, "Wi-Fi set: ESP-NOW off, restarting into Wi-Fi mode");
|
||||||
|
return esp_timer_start_once(restart_timer, 1500000);
|
||||||
|
}
|
||||||
esp_timer_stop(s_retry_timer);
|
esp_timer_stop(s_retry_timer);
|
||||||
esp_wifi_disconnect();
|
esp_wifi_disconnect();
|
||||||
s_retries = 0;
|
s_retries = 0;
|
||||||
@@ -296,9 +374,14 @@ esp_err_t net_save_network(const net_cfg_t *c)
|
|||||||
if (err != ESP_OK) {
|
if (err != ESP_OK) {
|
||||||
return err;
|
return err;
|
||||||
}
|
}
|
||||||
|
const bool ap_cfg_changed = strcmp(old.ap_ssid, c->ap_ssid) != 0 || strcmp(old.ap_pass, c->ap_pass) != 0;
|
||||||
if (c->ap_enabled != s_ap_on) {
|
if (c->ap_enabled != s_ap_on) {
|
||||||
// After the reply has gone out, so the page that asked still gets it
|
// After the reply has gone out, so the page that asked still gets it
|
||||||
ap_switch_later(c->ap_enabled, c->ap_enabled ? 1000000 : 1500000);
|
ap_switch_later(c->ap_enabled, c->ap_enabled ? 1000000 : 1500000);
|
||||||
|
} else if (c->ap_enabled && ap_cfg_changed) {
|
||||||
|
// Still on, with a new name or password: restart it after the reply has gone out
|
||||||
|
s_ap_reapply = true;
|
||||||
|
ap_switch_later(true, 1500000);
|
||||||
}
|
}
|
||||||
// Reconnect with the new address settings if a client is configured (after the reply, see reconnect_cb)
|
// Reconnect with the new address settings if a client is configured (after the reply, see reconnect_cb)
|
||||||
wifi_creds_t w;
|
wifi_creds_t w;
|
||||||
|
|||||||
@@ -16,6 +16,9 @@ esp_err_t net_start(void);
|
|||||||
/** @brief Fill buf with the AP SSID, e.g. "led-A1B2C3". */
|
/** @brief Fill buf with the AP SSID, e.g. "led-A1B2C3". */
|
||||||
void net_ap_ssid(char *buf, size_t len);
|
void net_ap_ssid(char *buf, size_t len);
|
||||||
|
|
||||||
|
/** @brief True while the access point is running. */
|
||||||
|
bool net_ap_on(void);
|
||||||
|
|
||||||
/** @brief Client link state and its IPv4 address ("" if not connected). */
|
/** @brief Client link state and its IPv4 address ("" if not connected). */
|
||||||
bool net_sta_status(char *ip, size_t ip_len);
|
bool net_sta_status(char *ip, size_t ip_len);
|
||||||
|
|
||||||
|
|||||||
+35
-17
@@ -59,6 +59,7 @@ static const pattern_def_t kPatterns[] = {
|
|||||||
{ "pulse", fx_pulse },
|
{ "pulse", fx_pulse },
|
||||||
{ "radiate", fx_radiate },
|
{ "radiate", fx_radiate },
|
||||||
{ "rain_drops", fx_rain_drops },
|
{ "rain_drops", fx_rain_drops },
|
||||||
|
{ "rainbow", fx_rainbow },
|
||||||
{ "rime", fx_rime },
|
{ "rime", fx_rime },
|
||||||
{ "ripple", fx_ripple },
|
{ "ripple", fx_ripple },
|
||||||
{ "sparkle", fx_sparkle },
|
{ "sparkle", fx_sparkle },
|
||||||
@@ -67,6 +68,7 @@ static const pattern_def_t kPatterns[] = {
|
|||||||
{ "sweep", fx_sweep },
|
{ "sweep", fx_sweep },
|
||||||
{ "transition", fx_transition },
|
{ "transition", fx_transition },
|
||||||
{ "twinkle", fx_twinkle },
|
{ "twinkle", fx_twinkle },
|
||||||
|
{ "wipe", fx_wipe },
|
||||||
};
|
};
|
||||||
#define PATTERN_COUNT ((int)(sizeof(kPatterns) / sizeof(kPatterns[0])))
|
#define PATTERN_COUNT ((int)(sizeof(kPatterns) / sizeof(kPatterns[0])))
|
||||||
|
|
||||||
@@ -85,11 +87,10 @@ static rgb *s_from; // frame the crossfade starts from
|
|||||||
static int s_cap; // LEDs the buffers are sized for
|
static int s_cap; // LEDs the buffers are sized for
|
||||||
static bool s_fading;
|
static bool s_fading;
|
||||||
|
|
||||||
// DDP: pixels sent by a controller. While they keep arriving they replace the pattern.
|
// DDP: pixels sent by a controller replace the pattern, and the last frame stays up when they stop.
|
||||||
#define DDP_TIMEOUT_MS 2000
|
#define DDP_TIMEOUT_MS 2000
|
||||||
static uint8_t s_ddp[FX_LEDS_MAX * 3];
|
static uint8_t s_ddp[FX_LEDS_MAX * 3];
|
||||||
static uint32_t s_ddp_last_ms; // 0: never
|
static uint32_t s_ddp_last_ms; // 0: never
|
||||||
static bool s_ddp_was;
|
|
||||||
static uint32_t s_ddp_packets;
|
static uint32_t s_ddp_packets;
|
||||||
static uint32_t s_ddp_frames; // frames completed (PUSH seen)
|
static uint32_t s_ddp_frames; // frames completed (PUSH seen)
|
||||||
static uint32_t s_ddp_sum; // checksum of the last completed frame
|
static uint32_t s_ddp_sum; // checksum of the last completed frame
|
||||||
@@ -153,9 +154,13 @@ static void sanitize(preset_t *p)
|
|||||||
if (p->ncol < 0) p->ncol = 0;
|
if (p->ncol < 0) p->ncol = 0;
|
||||||
if (p->ncol > PATTERN_MAX_COLOURS) p->ncol = PATTERN_MAX_COLOURS;
|
if (p->ncol > PATTERN_MAX_COLOURS) p->ncol = PATTERN_MAX_COLOURS;
|
||||||
if (p->fade > 10000) p->fade = 10000;
|
if (p->fade > 10000) p->fade = 10000;
|
||||||
|
// Chase steps (n3/n4) may be negative to run the dot backwards; other values stay >= 0.
|
||||||
|
const bool chase = p->pattern == patterns_index("chase");
|
||||||
for (int i = 1; i <= 6; i++) {
|
for (int i = 1; i <= 6; i++) {
|
||||||
if (p->n[i] < 0) p->n[i] = 0;
|
bool step = chase && (i == 3 || i == 4);
|
||||||
|
if (p->n[i] < 0 && !step) p->n[i] = 0;
|
||||||
if (p->n[i] > 100000) p->n[i] = 100000;
|
if (p->n[i] > 100000) p->n[i] = 100000;
|
||||||
|
if (p->n[i] < -100000) p->n[i] = -100000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,12 +232,19 @@ static uint32_t now_ms(void)
|
|||||||
return (uint32_t)(esp_timer_get_time() / 1000);
|
return (uint32_t)(esp_timer_get_time() / 1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// True if a timestamp stored as `now | 1` is recent. That value can be 1 ms ahead of a `now` read in the
|
||||||
|
// same millisecond, so the difference is signed: an unsigned one would wrap and look like a timeout.
|
||||||
|
static bool within(uint32_t now, uint32_t stamp, uint32_t window_ms)
|
||||||
|
{
|
||||||
|
return stamp != 0 && (int32_t)(now - stamp) < (int32_t)window_ms;
|
||||||
|
}
|
||||||
|
|
||||||
// Show the shadow frame, crossfading from the previous frame while a fade runs
|
// Show the shadow frame, crossfading from the previous frame while a fade runs
|
||||||
static void output(uint32_t now, bool full_brightness)
|
static void output(uint32_t now, bool full_brightness)
|
||||||
{
|
{
|
||||||
// device brightness x master scale, under the max brightness ceiling. DDP frames are shown at
|
// Pattern output: device brightness x master scale, under the max brightness ceiling. DDP frames
|
||||||
// full brightness: the sender sets the colours.
|
// skip the device and master brightness (the sender sets the colours) but still respect the ceiling.
|
||||||
int s_scale = full_brightness ? 255 : s_global * s_master / 255 * s_max_brightness / 255;
|
int s_scale = full_brightness ? s_max_brightness : s_global * s_master / 255 * s_max_brightness / 255;
|
||||||
int k = -1;
|
int k = -1;
|
||||||
if (s_fading) {
|
if (s_fading) {
|
||||||
uint32_t el = now - s_fade_t0;
|
uint32_t el = now - s_fade_t0;
|
||||||
@@ -337,22 +349,21 @@ void st_reset(void)
|
|||||||
memset(next_on, 0, s_cap);
|
memset(next_on, 0, s_cap);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The whole frame (pattern and output) runs under s_lock, so the buffers can't be replaced mid-frame
|
// One frame: the whole frame (pattern and output) runs under s_lock, so the buffers can't be replaced mid-frame
|
||||||
static void patterns_task(void *arg)
|
void patterns_frame(void)
|
||||||
{
|
{
|
||||||
(void)arg;
|
|
||||||
s_fx.pr = &s_run;
|
|
||||||
while (true) {
|
|
||||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
|
s_fx.pr = &s_run;
|
||||||
bool reset = s_reset_pending;
|
bool reset = s_reset_pending;
|
||||||
s_reset_pending = false;
|
s_reset_pending = false;
|
||||||
s_run = s_cur;
|
s_run = s_cur;
|
||||||
uint32_t now = now_ms();
|
uint32_t now = now_ms();
|
||||||
bool ddp_on = s_ddp_last_ms != 0 && now - s_ddp_last_ms < DDP_TIMEOUT_MS;
|
if (reset) {
|
||||||
if (!ddp_on && s_ddp_was) {
|
s_ddp_last_ms = 0; // selecting a pattern takes the strip back from DDP
|
||||||
reset = true; // the pattern starts again when the pixels stop
|
|
||||||
}
|
}
|
||||||
s_ddp_was = ddp_on;
|
// Once pixels have arrived the strip keeps the last frame when they stop: the pattern does not
|
||||||
|
// come back until one is selected
|
||||||
|
bool ddp_on = s_ddp_last_ms != 0;
|
||||||
if (reset) {
|
if (reset) {
|
||||||
if (s_run.fade > 0) {
|
if (s_run.fade > 0) {
|
||||||
memcpy(s_from, s_shown, s_fx.n * sizeof(rgb));
|
memcpy(s_from, s_shown, s_fx.n * sizeof(rgb));
|
||||||
@@ -378,6 +389,13 @@ static void patterns_task(void *arg)
|
|||||||
}
|
}
|
||||||
output(now, ddp_on);
|
output(now, ddp_on);
|
||||||
xSemaphoreGive(s_lock);
|
xSemaphoreGive(s_lock);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void patterns_task(void *arg)
|
||||||
|
{
|
||||||
|
(void)arg;
|
||||||
|
while (true) {
|
||||||
|
patterns_frame();
|
||||||
vTaskDelay(pdMS_TO_TICKS(FRAME_MS));
|
vTaskDelay(pdMS_TO_TICKS(FRAME_MS));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -475,7 +493,7 @@ void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool p
|
|||||||
s_ddp_packets++;
|
s_ddp_packets++;
|
||||||
if (push) {
|
if (push) {
|
||||||
s_ddp_frames++;
|
s_ddp_frames++;
|
||||||
bool syncing = s_sync_last_ms != 0 && now - s_sync_last_ms < DDP_SYNC_TIMEOUT_MS;
|
bool syncing = within(now, s_sync_last_ms, DDP_SYNC_TIMEOUT_MS);
|
||||||
if (syncing) {
|
if (syncing) {
|
||||||
// Syncs are arriving: hold the frame until the next one. The sender acks each frame before it
|
// Syncs are arriving: hold the frame until the next one. The sender acks each frame before it
|
||||||
// sends the sync, so the frame is always here when its sync arrives.
|
// sends the sync, so the frame is always here when its sync arrives.
|
||||||
@@ -506,7 +524,7 @@ void patterns_ddp_sync(uint32_t seq)
|
|||||||
void patterns_ddp_status(bool *active, uint32_t *packets)
|
void patterns_ddp_status(bool *active, uint32_t *packets)
|
||||||
{
|
{
|
||||||
xSemaphoreTake(s_lock, portMAX_DELAY);
|
xSemaphoreTake(s_lock, portMAX_DELAY);
|
||||||
*active = s_ddp_last_ms != 0 && now_ms() - s_ddp_last_ms < DDP_TIMEOUT_MS;
|
*active = within(now_ms(), s_ddp_last_ms, DDP_TIMEOUT_MS);
|
||||||
*packets = s_ddp_packets;
|
*packets = s_ddp_packets;
|
||||||
xSemaphoreGive(s_lock);
|
xSemaphoreGive(s_lock);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ void patterns_start(const struct hw_cfg_t &hw);
|
|||||||
/** @brief Apply new strip settings (count, colour order, brightness ceiling) while running. */
|
/** @brief Apply new strip settings (count, colour order, brightness ceiling) while running. */
|
||||||
esp_err_t patterns_set_hardware(const struct hw_cfg_t &hw);
|
esp_err_t patterns_set_hardware(const struct hw_cfg_t &hw);
|
||||||
|
|
||||||
|
/** @brief Run one frame of the pattern engine and show it. The pattern task calls it every 10 ms. */
|
||||||
|
void patterns_frame(void);
|
||||||
|
|
||||||
/** @brief Live update of the preset on the strip. A new pattern restarts; other changes keep its place. */
|
/** @brief Live update of the preset on the strip. A new pattern restarts; other changes keep its place. */
|
||||||
void patterns_set(const preset_t &p);
|
void patterns_set(const preset_t &p);
|
||||||
|
|
||||||
|
|||||||
+170
-28
@@ -40,6 +40,19 @@ static cJSON *rgb_json(const uint8_t *c)
|
|||||||
|
|
||||||
static bool read_rgb(const cJSON *a, uint8_t *out)
|
static bool read_rgb(const cJSON *a, uint8_t *out)
|
||||||
{
|
{
|
||||||
|
// The controller sends colours as "#RRGGBB" text
|
||||||
|
if (cJSON_IsString(a)) {
|
||||||
|
const char *s = a->valuestring[0] == '#' ? a->valuestring + 1 : a->valuestring;
|
||||||
|
char *end = nullptr;
|
||||||
|
unsigned long v = strtoul(s, &end, 16);
|
||||||
|
if (end != s + 6 || s[0] == '+' || s[0] == '-' || s[0] == ' ') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
out[0] = (uint8_t)(v >> 16);
|
||||||
|
out[1] = (uint8_t)((v >> 8) & 0xFF);
|
||||||
|
out[2] = (uint8_t)(v & 0xFF);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
if (!cJSON_IsArray(a) || cJSON_GetArraySize(a) != 3) {
|
if (!cJSON_IsArray(a) || cJSON_GetArraySize(a) != 3) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -120,8 +133,8 @@ bool preset_from_json(const cJSON *o, preset_t *p)
|
|||||||
if (cJSON_IsNumber(v)) p->fade = (uint32_t)(v->valueint < 0 ? 0 : v->valueint);
|
if (cJSON_IsNumber(v)) p->fade = (uint32_t)(v->valueint < 0 ? 0 : v->valueint);
|
||||||
v = cJSON_GetObjectItem(o, "beat_time");
|
v = cJSON_GetObjectItem(o, "beat_time");
|
||||||
if (cJSON_IsBool(v)) p->beat_time = cJSON_IsTrue(v);
|
if (cJSON_IsBool(v)) p->beat_time = cJSON_IsTrue(v);
|
||||||
static const char *keys[] = { "n1", "n2", "n3", "n4" };
|
static const char *keys[] = { "n1", "n2", "n3", "n4", "n5", "n6" };
|
||||||
for (int i = 0; i < 4; i++) {
|
for (int i = 0; i < 6; i++) {
|
||||||
v = cJSON_GetObjectItem(o, keys[i]);
|
v = cJSON_GetObjectItem(o, keys[i]);
|
||||||
if (cJSON_IsNumber(v)) p->n[i + 1] = v->valueint;
|
if (cJSON_IsNumber(v)) p->n[i + 1] = v->valueint;
|
||||||
}
|
}
|
||||||
@@ -130,27 +143,65 @@ bool preset_from_json(const cJSON *o, preset_t *p)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write the whole list to NVS as one JSON blob
|
// One key per preset ("p00".."p63"), so a save writes one small entry instead of the whole list.
|
||||||
static esp_err_t save_list(void)
|
// NVS_SLOTS is the most keys any build has written; the 24 KB nvs partition holds about 50 presets.
|
||||||
|
#define NVS_SLOTS 64
|
||||||
|
static void entry_key(char *out, size_t n, size_t i)
|
||||||
{
|
{
|
||||||
cJSON *arr = cJSON_CreateArray();
|
snprintf(out, n, "p%02u", (unsigned)i);
|
||||||
for (size_t i = 0; i < s_count; i++) {
|
|
||||||
cJSON_AddItemToArray(arr, preset_to_json(&s_list[i]));
|
|
||||||
}
|
}
|
||||||
char *s = cJSON_PrintUnformatted(arr);
|
|
||||||
cJSON_Delete(arr);
|
static esp_err_t save_entry(nvs_handle_t h, size_t i)
|
||||||
|
{
|
||||||
|
cJSON *o = preset_to_json(&s_list[i]);
|
||||||
|
char *s = cJSON_PrintUnformatted(o);
|
||||||
|
cJSON_Delete(o);
|
||||||
if (!s) {
|
if (!s) {
|
||||||
return ESP_ERR_NO_MEM;
|
return ESP_ERR_NO_MEM;
|
||||||
}
|
}
|
||||||
|
char key[8];
|
||||||
|
entry_key(key, sizeof(key), i);
|
||||||
|
esp_err_t err = nvs_set_str(h, key, s);
|
||||||
|
cJSON_free(s);
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write every preset, the count and the startup name. Erases keys past the new count and the old blob.
|
||||||
|
static esp_err_t save_list(void)
|
||||||
|
{
|
||||||
nvs_handle_t h;
|
nvs_handle_t h;
|
||||||
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||||
if (err == ESP_OK) {
|
if (err != ESP_OK) {
|
||||||
err = nvs_set_blob(h, "list", s, strlen(s));
|
return err;
|
||||||
|
}
|
||||||
|
for (size_t i = 0; i < s_count && err == ESP_OK; i++) {
|
||||||
|
err = save_entry(h, i);
|
||||||
|
}
|
||||||
|
for (size_t i = s_count; i < NVS_SLOTS; i++) {
|
||||||
|
char key[8];
|
||||||
|
entry_key(key, sizeof(key), i);
|
||||||
|
nvs_erase_key(h, key); // also keys left by an older build with a bigger limit
|
||||||
|
}
|
||||||
|
nvs_erase_key(h, "list"); // the single blob written by older firmware
|
||||||
|
if (err == ESP_OK) err = nvs_set_u32(h, "n", (uint32_t)s_count);
|
||||||
if (err == ESP_OK) err = nvs_set_str(h, "startup", s_startup);
|
if (err == ESP_OK) err = nvs_set_str(h, "startup", s_startup);
|
||||||
if (err == ESP_OK) err = nvs_commit(h);
|
if (err == ESP_OK) err = nvs_commit(h);
|
||||||
nvs_close(h);
|
nvs_close(h);
|
||||||
|
return err;
|
||||||
}
|
}
|
||||||
cJSON_free(s);
|
|
||||||
|
// Write one preset (slot idx) and the count
|
||||||
|
static esp_err_t save_one(size_t idx)
|
||||||
|
{
|
||||||
|
nvs_handle_t h;
|
||||||
|
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
err = save_entry(h, idx);
|
||||||
|
if (err == ESP_OK) err = nvs_set_u32(h, "n", (uint32_t)s_count);
|
||||||
|
if (err == ESP_OK) err = nvs_commit(h);
|
||||||
|
nvs_close(h);
|
||||||
return err;
|
return err;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,6 +234,21 @@ static int build_defaults(preset_t *out, int max)
|
|||||||
p->delay = 150;
|
p->delay = 150;
|
||||||
p->brightness = 180;
|
p->brightness = 180;
|
||||||
}
|
}
|
||||||
|
if ((p = add("Chase Marquee", "chase"))) {
|
||||||
|
p->ncol = 1;
|
||||||
|
p->col[0][0] = 255; p->col[0][1] = 200; p->col[0][2] = 80;
|
||||||
|
p->n[1] = 3; p->n[2] = 2; p->n[3] = 1; p->n[6] = 1; // dashes that scroll
|
||||||
|
p->delay = 120;
|
||||||
|
p->brightness = 180;
|
||||||
|
}
|
||||||
|
if ((p = add("Chase Reverse", "chase"))) {
|
||||||
|
p->ncol = 2;
|
||||||
|
p->col[0][0] = 0; p->col[0][1] = 255; p->col[0][2] = 120;
|
||||||
|
p->col[1][0] = 120; p->col[1][1] = 0; p->col[1][2] = 255;
|
||||||
|
p->n[1] = 6; p->n[2] = 6; p->n[3] = -1; p->n[4] = -1; // negative steps run it backwards
|
||||||
|
p->delay = 120;
|
||||||
|
p->brightness = 180;
|
||||||
|
}
|
||||||
if ((p = add("Aurora", "aurora"))) {
|
if ((p = add("Aurora", "aurora"))) {
|
||||||
p->n[1] = 3;
|
p->n[1] = 3;
|
||||||
p->n[2] = 40;
|
p->n[2] = 40;
|
||||||
@@ -243,22 +309,19 @@ int presets_add_defaults(void)
|
|||||||
return added;
|
return added;
|
||||||
}
|
}
|
||||||
|
|
||||||
esp_err_t presets_init(void)
|
// Read the one JSON list written by older firmware. Returns false if there is none.
|
||||||
|
static bool load_legacy(nvs_handle_t h)
|
||||||
{
|
{
|
||||||
s_count = 0;
|
|
||||||
s_startup[0] = '\0';
|
|
||||||
s_selected[0] = '\0';
|
|
||||||
|
|
||||||
nvs_handle_t h;
|
|
||||||
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
|
|
||||||
presets_add_defaults(); // a new board
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
size_t len = 0;
|
size_t len = 0;
|
||||||
bool have_list = nvs_get_blob(h, "list", NULL, &len) == ESP_OK;
|
if (nvs_get_blob(h, "list", NULL, &len) != ESP_OK || len == 0) {
|
||||||
if (have_list && len > 0) {
|
return false;
|
||||||
|
}
|
||||||
char *buf = (char *)malloc(len + 1);
|
char *buf = (char *)malloc(len + 1);
|
||||||
if (buf && nvs_get_blob(h, "list", buf, &len) == ESP_OK) {
|
if (!buf) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
bool ok = false;
|
||||||
|
if (nvs_get_blob(h, "list", buf, &len) == ESP_OK) {
|
||||||
buf[len] = '\0';
|
buf[len] = '\0';
|
||||||
cJSON *arr = cJSON_Parse(buf);
|
cJSON *arr = cJSON_Parse(buf);
|
||||||
cJSON *o;
|
cJSON *o;
|
||||||
@@ -271,18 +334,76 @@ esp_err_t presets_init(void)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
cJSON_Delete(arr);
|
cJSON_Delete(arr);
|
||||||
|
ok = true;
|
||||||
|
}
|
||||||
|
free(buf);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void load_entry(nvs_handle_t h, uint32_t i)
|
||||||
|
{
|
||||||
|
char key[8];
|
||||||
|
entry_key(key, sizeof(key), i);
|
||||||
|
size_t len = 0;
|
||||||
|
if (nvs_get_str(h, key, NULL, &len) != ESP_OK || len == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
char *buf = (char *)malloc(len);
|
||||||
|
if (!buf) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (nvs_get_str(h, key, buf, &len) == ESP_OK) {
|
||||||
|
cJSON *o = cJSON_Parse(buf);
|
||||||
|
preset_t p;
|
||||||
|
preset_defaults(&p, 0);
|
||||||
|
if (o && preset_from_json(o, &p) && p.name[0] && s_count < PRESETS_MAX) {
|
||||||
|
s_list[s_count++] = p;
|
||||||
|
}
|
||||||
|
cJSON_Delete(o);
|
||||||
}
|
}
|
||||||
free(buf);
|
free(buf);
|
||||||
}
|
}
|
||||||
len = sizeof(s_startup);
|
|
||||||
|
esp_err_t presets_init(void)
|
||||||
|
{
|
||||||
|
s_count = 0;
|
||||||
|
s_startup[0] = '\0';
|
||||||
|
s_selected[0] = '\0';
|
||||||
|
|
||||||
|
nvs_handle_t h;
|
||||||
|
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
|
||||||
|
presets_add_defaults(); // a new board
|
||||||
|
return ESP_OK;
|
||||||
|
}
|
||||||
|
uint32_t n = 0;
|
||||||
|
bool have_list = nvs_get_u32(h, "n", &n) == ESP_OK;
|
||||||
|
bool legacy = false;
|
||||||
|
if (have_list) {
|
||||||
|
if (n > PRESETS_MAX) {
|
||||||
|
ESP_LOGW(TAG, "%u presets saved, room for %d: the rest are not loaded", (unsigned)n, PRESETS_MAX);
|
||||||
|
}
|
||||||
|
for (uint32_t i = 0; i < n && i < PRESETS_MAX; i++) {
|
||||||
|
load_entry(h, i);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
legacy = load_legacy(h);
|
||||||
|
have_list = legacy;
|
||||||
|
}
|
||||||
|
size_t len = sizeof(s_startup);
|
||||||
if (nvs_get_str(h, "startup", s_startup, &len) != ESP_OK) {
|
if (nvs_get_str(h, "startup", s_startup, &len) != ESP_OK) {
|
||||||
s_startup[0] = '\0';
|
s_startup[0] = '\0';
|
||||||
}
|
}
|
||||||
nvs_close(h);
|
nvs_close(h);
|
||||||
|
if (legacy) {
|
||||||
|
save_list(); // move the old blob to per-preset keys
|
||||||
|
}
|
||||||
if (!have_list) {
|
if (!have_list) {
|
||||||
presets_add_defaults(); // nothing saved yet: start with the defaults
|
presets_add_defaults(); // nothing saved yet: start with the defaults
|
||||||
}
|
}
|
||||||
ESP_LOGI(TAG, "%u presets loaded", (unsigned)s_count);
|
ESP_LOGI(TAG, "%u presets loaded", (unsigned)s_count);
|
||||||
|
for (size_t i = 0; i < s_count; i++) {
|
||||||
|
ESP_LOGI(TAG, " [%u] %s", (unsigned)i, s_list[i].name);
|
||||||
|
}
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,17 +417,36 @@ const preset_t *presets_at(size_t i)
|
|||||||
return i < s_count ? &s_list[i] : NULL;
|
return i < s_count ? &s_list[i] : NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static uint32_t s_dropped; // saves refused because the store was full
|
||||||
|
|
||||||
|
uint32_t presets_dropped(void)
|
||||||
|
{
|
||||||
|
return s_dropped;
|
||||||
|
}
|
||||||
|
|
||||||
esp_err_t presets_save(const preset_t *preset)
|
esp_err_t presets_save(const preset_t *preset)
|
||||||
{
|
{
|
||||||
int idx = find(preset->name);
|
int idx = find(preset->name);
|
||||||
if (idx < 0) {
|
bool added = idx < 0;
|
||||||
|
if (added) {
|
||||||
if (s_count >= PRESETS_MAX) {
|
if (s_count >= PRESETS_MAX) {
|
||||||
|
s_dropped++;
|
||||||
|
ESP_LOGW(TAG, "store full (%d presets): '%s' not saved", PRESETS_MAX, preset->name);
|
||||||
return ESP_ERR_NO_MEM;
|
return ESP_ERR_NO_MEM;
|
||||||
}
|
}
|
||||||
idx = (int)s_count++;
|
idx = (int)s_count++;
|
||||||
}
|
}
|
||||||
s_list[idx] = *preset;
|
s_list[idx] = *preset;
|
||||||
return save_list();
|
ESP_LOGI(TAG, "save '%s' (%s), %u presets", preset->name, added ? "new" : "update", (unsigned)s_count);
|
||||||
|
esp_err_t err = save_one((size_t)idx);
|
||||||
|
if (err != ESP_OK) {
|
||||||
|
s_dropped++;
|
||||||
|
ESP_LOGW(TAG, "'%s' not saved to flash: %s", preset->name, esp_err_to_name(err));
|
||||||
|
if (added) {
|
||||||
|
s_count--; // keep RAM and flash the same
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err;
|
||||||
}
|
}
|
||||||
|
|
||||||
esp_err_t presets_set_order(const char *const *names, size_t n)
|
esp_err_t presets_set_order(const char *const *names, size_t n)
|
||||||
@@ -328,6 +468,7 @@ esp_err_t presets_set_order(const char *const *names, size_t n)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
memcpy(s_list, fresh, m * sizeof(preset_t));
|
memcpy(s_list, fresh, m * sizeof(preset_t));
|
||||||
|
ESP_LOGI(TAG, "order: %u presets (was %u)", (unsigned)m, (unsigned)s_count);
|
||||||
s_count = m;
|
s_count = m;
|
||||||
return save_list();
|
return save_list();
|
||||||
}
|
}
|
||||||
@@ -342,6 +483,7 @@ esp_err_t presets_delete(const char *name)
|
|||||||
s_list[i] = s_list[i + 1];
|
s_list[i] = s_list[i + 1];
|
||||||
}
|
}
|
||||||
s_count--;
|
s_count--;
|
||||||
|
ESP_LOGI(TAG, "delete '%s', %u presets", name, (unsigned)s_count);
|
||||||
if (strcmp(s_startup, name) == 0) {
|
if (strcmp(s_startup, name) == 0) {
|
||||||
s_startup[0] = '\0';
|
s_startup[0] = '\0';
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-1
@@ -9,7 +9,8 @@
|
|||||||
#include "esp_err.h"
|
#include "esp_err.h"
|
||||||
#include "patterns.h"
|
#include "patterns.h"
|
||||||
|
|
||||||
#define PRESETS_MAX 32
|
// Flash holds about 50 presets (the nvs partition is 24 KB); 48 leaves room for garbage collection
|
||||||
|
#define PRESETS_MAX 48
|
||||||
|
|
||||||
/** @brief Load the saved presets and the startup name from NVS. Call after NVS is initialised. */
|
/** @brief Load the saved presets and the startup name from NVS. Call after NVS is initialised. */
|
||||||
esp_err_t presets_init(void);
|
esp_err_t presets_init(void);
|
||||||
@@ -26,6 +27,9 @@ const preset_t *presets_at(size_t i);
|
|||||||
/** @brief Create a preset, or update the one with the same name. ESP_ERR_NO_MEM when full. */
|
/** @brief Create a preset, or update the one with the same name. ESP_ERR_NO_MEM when full. */
|
||||||
esp_err_t presets_save(const preset_t *preset);
|
esp_err_t presets_save(const preset_t *preset);
|
||||||
|
|
||||||
|
/** @brief Saves refused since boot: store full, or flash write failed. */
|
||||||
|
uint32_t presets_dropped(void);
|
||||||
|
|
||||||
/** @brief Put the presets in this order. Names not given keep their place at the end. */
|
/** @brief Put the presets in this order. Names not given keep their place at the end. */
|
||||||
esp_err_t presets_set_order(const char *const *names, size_t n);
|
esp_err_t presets_set_order(const char *const *names, size_t n);
|
||||||
|
|
||||||
|
|||||||
@@ -113,6 +113,8 @@ esp_err_t settings_load_net(net_cfg_t *c)
|
|||||||
memset(c, 0, sizeof(*c));
|
memset(c, 0, sizeof(*c));
|
||||||
c->ap_enabled = true;
|
c->ap_enabled = true;
|
||||||
c->ddp_enabled = true;
|
c->ddp_enabled = true;
|
||||||
|
c->espnow_enabled = true;
|
||||||
|
c->espnow_channel = 6;
|
||||||
nvs_handle_t h;
|
nvs_handle_t h;
|
||||||
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
|
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
|
||||||
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
||||||
@@ -134,9 +136,17 @@ esp_err_t settings_load_net(net_cfg_t *c)
|
|||||||
char ap[8];
|
char ap[8];
|
||||||
get_str(h, "ap", ap, sizeof(ap), "on");
|
get_str(h, "ap", ap, sizeof(ap), "on");
|
||||||
c->ap_enabled = strcmp(ap, "off") != 0;
|
c->ap_enabled = strcmp(ap, "off") != 0;
|
||||||
|
get_str(h, "ap_ssid", c->ap_ssid, sizeof(c->ap_ssid), "");
|
||||||
|
get_str(h, "ap_pass", c->ap_pass, sizeof(c->ap_pass), "");
|
||||||
char ddp[8];
|
char ddp[8];
|
||||||
get_str(h, "ddp", ddp, sizeof(ddp), "on");
|
get_str(h, "ddp", ddp, sizeof(ddp), "on");
|
||||||
c->ddp_enabled = strcmp(ddp, "off") != 0;
|
c->ddp_enabled = strcmp(ddp, "off") != 0;
|
||||||
|
char espnow[8];
|
||||||
|
get_str(h, "espnow", espnow, sizeof(espnow), "on");
|
||||||
|
c->espnow_enabled = strcmp(espnow, "off") != 0;
|
||||||
|
int64_t ch = 6;
|
||||||
|
nvs_get_i64(h, "espnow_ch", &ch);
|
||||||
|
c->espnow_channel = (uint8_t)(ch >= 1 && ch <= 13 ? ch : 6);
|
||||||
nvs_close(h);
|
nvs_close(h);
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
@@ -155,7 +165,11 @@ esp_err_t settings_save_net(const net_cfg_t *c)
|
|||||||
if (err == ESP_OK) err = nvs_set_str(h, "gateway", c->gateway);
|
if (err == ESP_OK) err = nvs_set_str(h, "gateway", c->gateway);
|
||||||
if (err == ESP_OK) err = nvs_set_str(h, "dns", c->dns);
|
if (err == ESP_OK) err = nvs_set_str(h, "dns", c->dns);
|
||||||
if (err == ESP_OK) err = nvs_set_str(h, "ap", c->ap_enabled ? "on" : "off");
|
if (err == ESP_OK) err = nvs_set_str(h, "ap", c->ap_enabled ? "on" : "off");
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "ap_ssid", c->ap_ssid);
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "ap_pass", c->ap_pass);
|
||||||
if (err == ESP_OK) err = nvs_set_str(h, "ddp", c->ddp_enabled ? "on" : "off");
|
if (err == ESP_OK) err = nvs_set_str(h, "ddp", c->ddp_enabled ? "on" : "off");
|
||||||
|
if (err == ESP_OK) err = nvs_set_str(h, "espnow", c->espnow_enabled ? "on" : "off");
|
||||||
|
if (err == ESP_OK) err = nvs_set_i64(h, "espnow_ch", c->espnow_channel);
|
||||||
if (err == ESP_OK) err = nvs_commit(h);
|
if (err == ESP_OK) err = nvs_commit(h);
|
||||||
nvs_close(h);
|
nvs_close(h);
|
||||||
return err;
|
return err;
|
||||||
|
|||||||
@@ -20,7 +20,11 @@ struct net_cfg_t {
|
|||||||
char gateway[16];
|
char gateway[16];
|
||||||
char dns[16]; // optional; empty uses the gateway
|
char dns[16]; // optional; empty uses the gateway
|
||||||
bool ap_enabled; // the access point (led-XXXXXX) is on; default on
|
bool ap_enabled; // the access point (led-XXXXXX) is on; default on
|
||||||
|
char ap_ssid[33]; // access point name; empty uses led-XXXXXX from the MAC
|
||||||
|
char ap_pass[65]; // access point password, 8-63 characters (WPA2); empty is an open network
|
||||||
bool ddp_enabled; // DDP pixels and frame sync are received; default on
|
bool ddp_enabled; // DDP pixels and frame sync are received; default on
|
||||||
|
bool espnow_enabled; // ESP-NOW link to led-controller (0x4C wire protocol); default on
|
||||||
|
uint8_t espnow_channel; // Wi-Fi channel shared with the controller and its bridge; default 6
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @brief Read saved Wi-Fi client credentials. ESP_ERR_NVS_NOT_FOUND if none are saved. */
|
/** @brief Read saved Wi-Fi client credentials. ESP_ERR_NVS_NOT_FOUND if none are saved. */
|
||||||
|
|||||||
@@ -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
|
||||||
+150
-3
@@ -10,14 +10,19 @@
|
|||||||
#include "mdns.h"
|
#include "mdns.h"
|
||||||
#include "esp_http_server.h"
|
#include "esp_http_server.h"
|
||||||
#include "esp_log.h"
|
#include "esp_log.h"
|
||||||
|
#include "esp_mac.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"
|
||||||
#include "net.h"
|
#include "net.h"
|
||||||
#include "ota.h"
|
#include "ota.h"
|
||||||
|
#include "ctrl_msg.h"
|
||||||
#include "ddp.h"
|
#include "ddp.h"
|
||||||
|
#include "espnow_link.h"
|
||||||
#include "patterns.h"
|
#include "patterns.h"
|
||||||
#include "effects.h"
|
#include "effects.h"
|
||||||
#include "presets.h"
|
#include "presets.h"
|
||||||
@@ -242,7 +247,14 @@ static esp_err_t status_get(api_req_t *req)
|
|||||||
settings_load_net(&n);
|
settings_load_net(&n);
|
||||||
cJSON *o = preset_to_json(&p);
|
cJSON *o = preset_to_json(&p);
|
||||||
cJSON_AddStringToObject(o, "ap_ssid", ap);
|
cJSON_AddStringToObject(o, "ap_ssid", ap);
|
||||||
|
cJSON_AddBoolToObject(o, "ap_on", net_ap_on());
|
||||||
cJSON_AddStringToObject(o, "hostname", n.hostname);
|
cJSON_AddStringToObject(o, "hostname", n.hostname);
|
||||||
|
// The station MAC is the one the board uses on ESP-NOW too, so the controller ties the two records together
|
||||||
|
uint8_t mac[6];
|
||||||
|
esp_read_mac(mac, ESP_MAC_WIFI_STA);
|
||||||
|
char mac_hex[13];
|
||||||
|
snprintf(mac_hex, sizeof(mac_hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||||
|
cJSON_AddStringToObject(o, "mac", mac_hex);
|
||||||
cJSON_AddBoolToObject(o, "sta_connected", up);
|
cJSON_AddBoolToObject(o, "sta_connected", up);
|
||||||
cJSON_AddStringToObject(o, "sta_ip", ip);
|
cJSON_AddStringToObject(o, "sta_ip", ip);
|
||||||
cJSON_AddStringToObject(o, "selected", presets_selected());
|
cJSON_AddStringToObject(o, "selected", presets_selected());
|
||||||
@@ -265,11 +277,17 @@ static esp_err_t pattern_post(api_req_t *req)
|
|||||||
preset_t p;
|
preset_t p;
|
||||||
patterns_get(&p);
|
patterns_get(&p);
|
||||||
bool ok = preset_from_json(in, &p);
|
bool ok = preset_from_json(in, &p);
|
||||||
|
// "select": the controller's preset select: restart the pattern, and fade in if the preset says so
|
||||||
|
bool select = cJSON_IsTrue(cJSON_GetObjectItem(in, "select"));
|
||||||
cJSON_Delete(in);
|
cJSON_Delete(in);
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
return send_error(req, "400 Bad Request", "unknown pattern");
|
return send_error(req, "400 Bad Request", "unknown pattern");
|
||||||
}
|
}
|
||||||
|
if (select) {
|
||||||
|
patterns_select(p);
|
||||||
|
} else {
|
||||||
patterns_set(p);
|
patterns_set(p);
|
||||||
|
}
|
||||||
return send_json(req, cJSON_CreateObject());
|
return send_json(req, cJSON_CreateObject());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,13 +333,17 @@ static esp_err_t wifi_post(api_req_t *req)
|
|||||||
strncpy(c.pass, pw, sizeof(c.pass) - 1);
|
strncpy(c.pass, pw, sizeof(c.pass) - 1);
|
||||||
cJSON_Delete(in);
|
cJSON_Delete(in);
|
||||||
|
|
||||||
|
net_cfg_t before;
|
||||||
|
settings_load_net(&before);
|
||||||
esp_err_t err = net_sta_connect(&c);
|
esp_err_t err = net_sta_connect(&c);
|
||||||
if (err != ESP_OK) {
|
if (err != ESP_OK) {
|
||||||
ESP_LOGW(TAG, "Connect to %s failed: %s", c.ssid, esp_err_to_name(err));
|
ESP_LOGW(TAG, "Connect to %s failed: %s", c.ssid, esp_err_to_name(err));
|
||||||
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
|
||||||
}
|
}
|
||||||
cJSON *o = cJSON_CreateObject();
|
cJSON *o = cJSON_CreateObject();
|
||||||
cJSON_AddStringToObject(o, "message", "saved; connecting");
|
cJSON_AddStringToObject(o, "message", before.espnow_enabled
|
||||||
|
? "saved; ESP-NOW is off, restarting into Wi-Fi mode"
|
||||||
|
: "saved; connecting");
|
||||||
return send_json(req, o);
|
return send_json(req, o);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -387,6 +409,11 @@ static esp_err_t network_get(api_req_t *req)
|
|||||||
cJSON_AddBoolToObject(o, "connected", up);
|
cJSON_AddBoolToObject(o, "connected", up);
|
||||||
cJSON_AddStringToObject(o, "current_ip", ip);
|
cJSON_AddStringToObject(o, "current_ip", ip);
|
||||||
cJSON_AddBoolToObject(o, "ap_enabled", n.ap_enabled);
|
cJSON_AddBoolToObject(o, "ap_enabled", n.ap_enabled);
|
||||||
|
char ap_name[33];
|
||||||
|
net_ap_ssid(ap_name, sizeof(ap_name));
|
||||||
|
cJSON_AddStringToObject(o, "ap_ssid", ap_name); // the name in use now
|
||||||
|
cJSON_AddBoolToObject(o, "ap_ssid_custom", n.ap_ssid[0] != '\0');
|
||||||
|
cJSON_AddBoolToObject(o, "ap_password_set", strlen(n.ap_pass) >= 8); // the password itself is never sent
|
||||||
cJSON_AddBoolToObject(o, "ddp_enabled", n.ddp_enabled);
|
cJSON_AddBoolToObject(o, "ddp_enabled", n.ddp_enabled);
|
||||||
return send_json(req, o);
|
return send_json(req, o);
|
||||||
}
|
}
|
||||||
@@ -446,6 +473,24 @@ static esp_err_t network_post(api_req_t *req)
|
|||||||
if (cJSON_IsBool(ap)) {
|
if (cJSON_IsBool(ap)) {
|
||||||
n.ap_enabled = cJSON_IsTrue(ap);
|
n.ap_enabled = cJSON_IsTrue(ap);
|
||||||
}
|
}
|
||||||
|
// Access point name: empty goes back to led-XXXXXX. Password: empty is open, else 8-63 characters.
|
||||||
|
cJSON *apn = cJSON_GetObjectItem(in, "ap_ssid");
|
||||||
|
if (cJSON_IsString(apn)) {
|
||||||
|
if (strlen(apn->valuestring) > 32) {
|
||||||
|
cJSON_Delete(in);
|
||||||
|
return send_error(req, "400 Bad Request", "ap_ssid: up to 32 characters, or empty for the default name");
|
||||||
|
}
|
||||||
|
snprintf(n.ap_ssid, sizeof(n.ap_ssid), "%s", apn->valuestring);
|
||||||
|
}
|
||||||
|
cJSON *app = cJSON_GetObjectItem(in, "ap_password");
|
||||||
|
if (cJSON_IsString(app)) {
|
||||||
|
const size_t plen = strlen(app->valuestring);
|
||||||
|
if (plen != 0 && (plen < 8 || plen > 63)) {
|
||||||
|
cJSON_Delete(in);
|
||||||
|
return send_error(req, "400 Bad Request", "ap_password: empty (open) or 8-63 characters");
|
||||||
|
}
|
||||||
|
snprintf(n.ap_pass, sizeof(n.ap_pass), "%s", app->valuestring);
|
||||||
|
}
|
||||||
cJSON *ddp = cJSON_GetObjectItem(in, "ddp_enabled");
|
cJSON *ddp = cJSON_GetObjectItem(in, "ddp_enabled");
|
||||||
if (cJSON_IsBool(ddp)) {
|
if (cJSON_IsBool(ddp)) {
|
||||||
n.ddp_enabled = cJSON_IsTrue(ddp);
|
n.ddp_enabled = cJSON_IsTrue(ddp);
|
||||||
@@ -664,6 +709,7 @@ static esp_err_t presets_get(api_req_t *req)
|
|||||||
cJSON_AddStringToObject(o, "selected", presets_selected());
|
cJSON_AddStringToObject(o, "selected", presets_selected());
|
||||||
cJSON_AddStringToObject(o, "startup", presets_startup());
|
cJSON_AddStringToObject(o, "startup", presets_startup());
|
||||||
cJSON_AddNumberToObject(o, "max", PRESETS_MAX);
|
cJSON_AddNumberToObject(o, "max", PRESETS_MAX);
|
||||||
|
cJSON_AddNumberToObject(o, "dropped", presets_dropped());
|
||||||
return send_json(req, o);
|
return send_json(req, o);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1129,6 +1175,74 @@ typedef struct {
|
|||||||
api_fn_t fn;
|
api_fn_t fn;
|
||||||
} api_route_t;
|
} api_route_t;
|
||||||
|
|
||||||
|
// GET /api/espnow: the ESP-NOW link to led-controller: its settings, the controller, the groups, the counters
|
||||||
|
static esp_err_t espnow_get(api_req_t *req)
|
||||||
|
{
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
espnow_stats_t st;
|
||||||
|
espnow_link_stats(&st);
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
cJSON_AddBoolToObject(o, "enabled", n.espnow_enabled);
|
||||||
|
cJSON_AddBoolToObject(o, "running", st.running);
|
||||||
|
cJSON_AddNumberToObject(o, "channel", n.espnow_channel);
|
||||||
|
uint8_t radio = 0;
|
||||||
|
wifi_second_chan_t second;
|
||||||
|
if (esp_wifi_get_channel(&radio, &second) == ESP_OK) {
|
||||||
|
cJSON_AddNumberToObject(o, "radio_channel", radio); // the channel ESP-NOW actually uses
|
||||||
|
}
|
||||||
|
char ctrl[24] = "";
|
||||||
|
if (st.master_seen) {
|
||||||
|
snprintf(ctrl, sizeof(ctrl), "%02x:%02x:%02x:%02x:%02x:%02x", st.master[0], st.master[1], st.master[2],
|
||||||
|
st.master[3], st.master[4], st.master[5]);
|
||||||
|
}
|
||||||
|
cJSON_AddStringToObject(o, "controller", ctrl);
|
||||||
|
cJSON_AddItemToObject(o, "groups", ctrl_groups_json());
|
||||||
|
cJSON *c = cJSON_AddObjectToObject(o, "counters");
|
||||||
|
cJSON_AddNumberToObject(c, "msgs", st.msgs);
|
||||||
|
cJSON_AddNumberToObject(c, "dups", st.dups);
|
||||||
|
cJSON_AddNumberToObject(c, "acks", st.acks);
|
||||||
|
cJSON_AddNumberToObject(c, "resyncs", st.resyncs);
|
||||||
|
cJSON_AddNumberToObject(c, "pings", st.pings);
|
||||||
|
cJSON_AddNumberToObject(c, "beats", st.beats);
|
||||||
|
cJSON_AddNumberToObject(c, "dropped", st.dropped);
|
||||||
|
cJSON_AddNumberToObject(c, "frames", st.frames);
|
||||||
|
cJSON_AddNumberToObject(c, "sent", st.sent);
|
||||||
|
cJSON_AddNumberToObject(c, "send_fail", st.send_fail);
|
||||||
|
cJSON_AddNumberToObject(c, "ver", st.ver);
|
||||||
|
return send_json(req, o);
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/espnow {"enabled": bool, "channel": 1-13}. Saved now; the link starts or moves channel on restart.
|
||||||
|
static esp_err_t espnow_post(api_req_t *req)
|
||||||
|
{
|
||||||
|
cJSON *in = read_json(req);
|
||||||
|
if (!in) {
|
||||||
|
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
|
||||||
|
}
|
||||||
|
net_cfg_t n;
|
||||||
|
settings_load_net(&n);
|
||||||
|
cJSON *v = cJSON_GetObjectItem(in, "enabled");
|
||||||
|
if (cJSON_IsBool(v)) {
|
||||||
|
n.espnow_enabled = cJSON_IsTrue(v);
|
||||||
|
}
|
||||||
|
v = cJSON_GetObjectItem(in, "channel");
|
||||||
|
if (cJSON_IsNumber(v)) {
|
||||||
|
if (v->valueint < 1 || v->valueint > 13) {
|
||||||
|
cJSON_Delete(in);
|
||||||
|
return send_error(req, "400 Bad Request", "channel must be 1-13");
|
||||||
|
}
|
||||||
|
n.espnow_channel = (uint8_t)v->valueint;
|
||||||
|
}
|
||||||
|
cJSON_Delete(in);
|
||||||
|
if (settings_save_net(&n) != ESP_OK) {
|
||||||
|
return send_error(req, "500 Internal Server Error", "could not save");
|
||||||
|
}
|
||||||
|
cJSON *o = cJSON_CreateObject();
|
||||||
|
cJSON_AddStringToObject(o, "message", "saved, restart to apply");
|
||||||
|
return send_json(req, o);
|
||||||
|
}
|
||||||
|
|
||||||
static const api_route_t s_api[] = {
|
static const api_route_t s_api[] = {
|
||||||
{"/api/status", HTTP_GET, status_get},
|
{"/api/status", HTTP_GET, status_get},
|
||||||
{"/api/pattern", HTTP_POST, pattern_post},
|
{"/api/pattern", HTTP_POST, pattern_post},
|
||||||
@@ -1138,6 +1252,8 @@ static const api_route_t s_api[] = {
|
|||||||
{"/api/network", HTTP_GET, network_get},
|
{"/api/network", HTTP_GET, network_get},
|
||||||
{"/api/network", HTTP_POST, network_post},
|
{"/api/network", HTTP_POST, network_post},
|
||||||
{"/api/ddp", HTTP_GET, ddp_get},
|
{"/api/ddp", HTTP_GET, ddp_get},
|
||||||
|
{"/api/espnow", HTTP_GET, espnow_get},
|
||||||
|
{"/api/espnow", HTTP_POST, espnow_post},
|
||||||
{"/api/hardware", HTTP_GET, hardware_get},
|
{"/api/hardware", HTTP_GET, hardware_get},
|
||||||
{"/api/hardware", HTTP_POST, hardware_post},
|
{"/api/hardware", HTTP_POST, hardware_post},
|
||||||
{"/api/presets", HTTP_GET, presets_get},
|
{"/api/presets", HTTP_GET, presets_get},
|
||||||
@@ -1160,8 +1276,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 +1350,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 16384 // 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
|
||||||
+6
-5
@@ -1,6 +1,7 @@
|
|||||||
# Name, Type, SubType, Offset, Size
|
# Name, Type, SubType, Offset, Size
|
||||||
nvs, data, nvs, 0x9000, 0x6000
|
# 4 MB flash. The two OTA slots take 1.5 MB each (the app is ~1.2 MB); nvs is at the end.
|
||||||
otadata, data, ota, 0xf000, 0x2000
|
otadata, data, ota, 0x9000, 0x2000
|
||||||
phy_init, data, phy, 0x11000, 0x1000
|
phy_init, data, phy, 0xB000, 0x1000
|
||||||
ota_0, app, ota_0, 0x20000, 0x1E0000
|
ota_0, app, ota_0, 0x10000, 0x180000
|
||||||
ota_1, app, ota_1, 0x200000, 0x1E0000
|
ota_1, app, ota_1, 0x190000, 0x180000
|
||||||
|
nvs, data, nvs, 0x310000, 0xF0000
|
||||||
|
@@ -9,3 +9,7 @@ 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
|
||||||
|
# The web UI's /ws WebSocket (web.cpp) needs the httpd WebSocket support
|
||||||
|
CONFIG_HTTPD_WS_SUPPORT=y
|
||||||
+710
-60
@@ -2,19 +2,30 @@
|
|||||||
"""
|
"""
|
||||||
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 # the devices in tools/rig.json (their IPs and places in the rig)
|
||||||
python3 tools/ddp_test.py --subnet=192.168.4 # or pick the subnet
|
python3 tools/ddp_test.py --broadcast-only # send the sync only as a broadcast (default: also to each device by unicast)
|
||||||
|
python3 tools/ddp_test.py --discover # finds every device on this machine's subnet (/24)
|
||||||
|
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, lowered for big rigs: 250 / number of devices)
|
||||||
|
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 --expect=5 # keep scanning until 5 devices answer (a busy device can be slow)
|
||||||
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 os
|
||||||
|
import random
|
||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import re
|
import re
|
||||||
@@ -27,17 +38,44 @@ import urllib.request
|
|||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
PORT = 4048
|
PORT = 4048
|
||||||
|
RIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rig.json")
|
||||||
|
ROW_OF = {} # device index in the soak -> its row in the rig, for the patterns that follow the layout
|
||||||
SYNC_PORT = 4049
|
SYNC_PORT = 4049
|
||||||
LEDS = 119
|
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
|
FRAME_BUDGET = 250 # frames per second the Wi-Fi carried for the whole rig (measured with 16 bars: 15 fps worked, 25+ did not)
|
||||||
|
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 load_rig(path=RIG_FILE):
|
||||||
|
"""The rig map: {"rows", "columns", "devices": [{name, ip, row, column, reversed, usb?}]}, in the order
|
||||||
|
the soak lays the bars out (row by row, left to right). None if there is no map file."""
|
||||||
|
try:
|
||||||
|
with open(path) as f:
|
||||||
|
rig = json.load(f)
|
||||||
|
except FileNotFoundError:
|
||||||
|
return None
|
||||||
|
rig["devices"].sort(key=lambda d: (d["row"], d["column"]))
|
||||||
|
return rig
|
||||||
|
|
||||||
|
|
||||||
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 +89,21 @@ 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):
|
UNICAST_SYNC = True # also send each device its own copy of every sync (--broadcast-only turns this off)
|
||||||
"""Broadcast a sync: every device shows the frame it holds."""
|
|
||||||
sock.sendto(b"LSY1" + struct.pack(">I", seq & 0xFFFFFFFF), ("255.255.255.255", SYNC_PORT))
|
|
||||||
|
def send_sync(sock, seq, broadcast, devices=()):
|
||||||
|
"""Broadcast a sync to the network's broadcast address: every device shows the frame it holds. A Wi-Fi
|
||||||
|
access point may not deliver broadcasts to every client (one of ours got none), so with UNICAST_SYNC each
|
||||||
|
of `devices` is also sent the sync directly. A device that gets both shows the frame on the first and
|
||||||
|
finds nothing held on the second, which does nothing."""
|
||||||
|
msg = b"LSY1" + struct.pack(">I", seq & 0xFFFFFFFF)
|
||||||
|
targets = [broadcast] + (list(devices) if UNICAST_SYNC else [])
|
||||||
|
for t in targets:
|
||||||
|
try:
|
||||||
|
sock.sendto(msg, (t, SYNC_PORT))
|
||||||
|
except BlockingIOError:
|
||||||
|
pass # the socket's send buffer is full: this copy is dropped, as a lost packet would be
|
||||||
|
|
||||||
|
|
||||||
def frame_sum(pixels):
|
def frame_sum(pixels):
|
||||||
@@ -72,9 +122,33 @@ def read_serial(port, stop, lines):
|
|||||||
lines.extend(buf.decode("utf-8", "replace").splitlines())
|
lines.extend(buf.decode("utf-8", "replace").splitlines())
|
||||||
|
|
||||||
|
|
||||||
def get(host, path):
|
def get(host, path, timeout=5, tries=3):
|
||||||
with urllib.request.urlopen(f"http://{host}{path}", timeout=5) as r:
|
"""GET a JSON path from a device. A device busy with a stream can miss a request, so a timeout is
|
||||||
|
retried (tries in all) before it is raised; the soak's samples use tries=1 and count a miss instead."""
|
||||||
|
for n in range(tries):
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(f"http://{host}{path}", timeout=timeout) as r:
|
||||||
return json.loads(r.read().decode())
|
return json.loads(r.read().decode())
|
||||||
|
except OSError:
|
||||||
|
if n == tries - 1:
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
class Missing(dict):
|
||||||
|
"""What soft_get returns for a device that did not answer: every field reads as a value that fails
|
||||||
|
its check (rgb is -1, active is False, counters are -1), so one silent device fails its own checks
|
||||||
|
and the test goes on with the rest."""
|
||||||
|
|
||||||
|
def __missing__(self, key):
|
||||||
|
return [-1, -1, -1] if key == "rgb" else False if key == "active" else -1
|
||||||
|
|
||||||
|
|
||||||
|
def soft_get(host, path, **kw):
|
||||||
|
"""get(), but a device that does not answer gives a Missing instead of ending the whole run."""
|
||||||
|
try:
|
||||||
|
return get(host, path, **kw)
|
||||||
|
except OSError:
|
||||||
|
return Missing()
|
||||||
|
|
||||||
|
|
||||||
def local_prefix():
|
def local_prefix():
|
||||||
@@ -88,20 +162,49 @@ def local_prefix():
|
|||||||
return ip.rsplit(".", 1)[0]
|
return ip.rsplit(".", 1)[0]
|
||||||
|
|
||||||
|
|
||||||
def find_devices(prefix):
|
def neighbours(prefix):
|
||||||
"""Every host on the subnet that answers the driver's /api/ddp endpoint."""
|
"""Addresses on the subnet that this machine has seen on the LAN (its ARP table), whether or not they
|
||||||
|
answered HTTP: a device that is up but slow to answer shows here."""
|
||||||
def probe(ip):
|
import subprocess
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(f"http://{ip}/api/ddp", timeout=1) as r:
|
out = subprocess.run(["ip", "-4", "neigh"], capture_output=True, text=True, timeout=5).stdout
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
ips = []
|
||||||
|
for line in out.splitlines():
|
||||||
|
parts = line.split()
|
||||||
|
if parts and parts[0].startswith(prefix + ".") and "FAILED" not in parts and "INCOMPLETE" not in parts:
|
||||||
|
ips.append(parts[0])
|
||||||
|
return ips
|
||||||
|
|
||||||
|
|
||||||
|
def find_devices(prefix, expect=None):
|
||||||
|
"""Every host on the subnet that answers the driver's /api/ddp endpoint. A device that is busy can be
|
||||||
|
slow to answer, so after the full sweep, hosts seen on the LAN that did not answer are retried with a
|
||||||
|
longer timeout (3 times). If fewer than `expect` devices answered, one more full sweep runs."""
|
||||||
|
|
||||||
|
def probe(ip, timeout):
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(f"http://{ip}/api/ddp", timeout=timeout) as r:
|
||||||
json.loads(r.read().decode())
|
json.loads(r.read().decode())
|
||||||
return ip
|
return ip
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
ips = [f"{prefix}.{i}" for i in range(1, 255)]
|
def sweep(ips, timeout):
|
||||||
with ThreadPoolExecutor(64) as pool:
|
with ThreadPoolExecutor(64) as pool:
|
||||||
return [ip for ip in pool.map(probe, ips) if ip]
|
return {ip for ip in pool.map(lambda ip: probe(ip, timeout), ips) if ip}
|
||||||
|
|
||||||
|
all_ips = [f"{prefix}.{i}" for i in range(1, 255)]
|
||||||
|
found = sweep(all_ips, 1.5)
|
||||||
|
for _ in range(3):
|
||||||
|
silent = [ip for ip in neighbours(prefix) if ip not in found]
|
||||||
|
if not silent:
|
||||||
|
break
|
||||||
|
found |= sweep(silent, 3.0)
|
||||||
|
if expect is not None and len(found) < expect:
|
||||||
|
found |= sweep([ip for ip in all_ips if ip not in found], 3.0)
|
||||||
|
return sorted(found, key=lambda ip: int(ip.rsplit(".", 1)[1]))
|
||||||
|
|
||||||
|
|
||||||
# Test animations: each maps (LED index, frame number) to an RGB colour
|
# Test animations: each maps (LED index, frame number) to an RGB colour
|
||||||
@@ -122,9 +225,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 +259,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 +284,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, self.ip_of.values())
|
||||||
|
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, self.ip_of.values())
|
||||||
|
|
||||||
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:
|
|
||||||
continue
|
|
||||||
if data[:4] == b"LAK1" and len(data) >= 5 and (data[4] & 0x0F) == nibble:
|
if data[:4] == b"LAK1" and len(data) >= 5 and (data[4] & 0x0F) == nibble:
|
||||||
waiting.discard(addr[0])
|
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 +369,457 @@ 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_row_sweep(i, k, n):
|
||||||
|
row = ROW_OF.get(i // LEDS, 0)
|
||||||
|
rows = max(ROW_OF.values(), default=0) + 1
|
||||||
|
lit = (k // 30) % rows # one row of the rig lit at a time, 0.75 s each, top to bottom
|
||||||
|
return (255, 80, 0) if row == lit else (10, 0, 0)
|
||||||
|
|
||||||
|
|
||||||
|
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,
|
||||||
|
"row sweep": soak_row_sweep,
|
||||||
|
"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}
|
||||||
|
# The devices apply their max brightness ceiling to DDP frames, so a sample is compared to that
|
||||||
|
scale = {h: get(h, "/api/hardware")["max_brightness"] for h in hosts}
|
||||||
|
stats = {h: {"samples": 0, "bad": 0, "idle": 0, "errors": 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(expected([f[led]], scale[h])[0]) for f in history[h]} for h in hosts}
|
||||||
|
|
||||||
|
def sample(h, led=led):
|
||||||
|
# A short timeout: the sender waits for this, so a slow device must not stall the frames
|
||||||
|
try:
|
||||||
|
r = get(h, f"/api/ddp?led={led}", timeout=1.0, tries=1)
|
||||||
|
except OSError:
|
||||||
|
return h, led, None, None, wants[h]
|
||||||
|
return h, led, tuple(r["rgb"]), r["active"], wants[h]
|
||||||
|
|
||||||
|
for h, l, got, active, w in pool.map(sample, hosts):
|
||||||
|
st = stats[h]
|
||||||
|
if got is None: # no answer in time: counted, but not a mismatch
|
||||||
|
st["errors"] += 1
|
||||||
|
continue
|
||||||
|
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 = soft_get(h, "/api/ddp")
|
||||||
|
sy, sb = a["sync"], before[h]["sync"]
|
||||||
|
if not isinstance(sy, dict):
|
||||||
|
sy = {"frames": sb["frames"] - 1, "shown": sb["shown"] - 1}
|
||||||
|
st = stats[h]
|
||||||
|
print(f"== {h}: frames +{sy['frames'] - sb['frames']}, shown +{sy['shown'] - sb['shown']}, "
|
||||||
|
f"samples {st['samples']}, "
|
||||||
|
f"mismatches {st['bad']}, no answer {st['errors']}, 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}
|
||||||
@@ -227,12 +834,13 @@ def run_all(hosts, serial_port):
|
|||||||
|
|
||||||
before, scale = {}, {}
|
before, scale = {}, {}
|
||||||
for h in hosts:
|
for h in hosts:
|
||||||
before[h] = get(h, "/api/ddp")
|
before[h] = soft_get(h, "/api/ddp")
|
||||||
scale[h] = 255 # DDP frames are shown at full brightness, whatever the device's brightness settings
|
# DDP frames ignore the device and master brightness, but the max brightness ceiling still applies
|
||||||
|
scale[h] = soft_get(h, "/api/hardware")["max_brightness"]
|
||||||
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 = []
|
||||||
@@ -252,9 +860,9 @@ def run_all(hosts, serial_port):
|
|||||||
for h in hosts:
|
for h in hosts:
|
||||||
out[h].append(f"frames not acked in time while streaming: {sender.missed[h]}")
|
out[h].append(f"frames not acked in time while streaming: {sender.missed[h]}")
|
||||||
for h in hosts:
|
for h in hosts:
|
||||||
mid = get(h, "/api/ddp")
|
mid = soft_get(h, "/api/ddp")
|
||||||
check(h, "receiving while sending", mid["active"], f"packets={mid['packets']}")
|
check(h, "receiving while sending", mid["active"], f"packets={mid['packets']}")
|
||||||
check(h, "packets counted", mid["packets"] - before[h]["packets"] >= 120,
|
check(h, "packets counted", mid["packets"] - before[h]["packets"] >= 50, # one packet per frame, 60 frames (a few may be lost)
|
||||||
f"+{mid['packets'] - before[h]['packets']}")
|
f"+{mid['packets'] - before[h]['packets']}")
|
||||||
|
|
||||||
# A frame waits for a sync: send one by unicast alone, then a sync, and check the strip changes
|
# A frame waits for a sync: send one by unicast alone, then a sync, and check the strip changes
|
||||||
@@ -262,19 +870,19 @@ 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, sender.ip_of.values()) # 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)
|
||||||
time.sleep(0.3)
|
time.sleep(0.3)
|
||||||
for h in hosts:
|
for h in hosts:
|
||||||
got = get(h, "/api/ddp?led=0")["rgb"]
|
got = soft_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, sender.ip_of.values())
|
||||||
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 = soft_get(h, "/api/ddp?led=0")["rgb"]
|
||||||
check(h, "frame shows on the sync", got == expected([waiting[0]], scale[h])[0], f"LED 0 {got}")
|
check(h, "frame shows on the sync", got == expected([waiting[0]], scale[h])[0], f"LED 0 {got}")
|
||||||
sender.paused = False
|
sender.paused = False
|
||||||
|
|
||||||
@@ -301,7 +909,11 @@ def run_all(hosts, serial_port):
|
|||||||
want_all = expected(pixels, scale[h])
|
want_all = expected(pixels, scale[h])
|
||||||
bad = []
|
bad = []
|
||||||
for i in range(LEDS):
|
for i in range(LEDS):
|
||||||
got = get(h, f"/api/ddp?led={i}")["rgb"]
|
try:
|
||||||
|
got = get(h, f"/api/ddp?led={i}", timeout=3, tries=2)["rgb"]
|
||||||
|
except OSError: # no answer: this check fails for the device, the run goes on
|
||||||
|
bad.append((i, "no answer", want_all[i]))
|
||||||
|
break
|
||||||
if got != want_all[i]:
|
if got != want_all[i]:
|
||||||
bad.append((i, got, want_all[i]))
|
bad.append((i, got, want_all[i]))
|
||||||
return bad
|
return bad
|
||||||
@@ -326,7 +938,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)
|
||||||
@@ -339,30 +951,52 @@ def run_all(hosts, serial_port):
|
|||||||
time.sleep(0.2)
|
time.sleep(0.2)
|
||||||
for h in hosts:
|
for h in hosts:
|
||||||
check(h, "out-of-range packet ignored",
|
check(h, "out-of-range packet ignored",
|
||||||
get(h, "/api/ddp?led=0")["rgb"] == expected([shown[0]], scale[h])[0])
|
soft_get(h, "/api/ddp?led=0")["rgb"] == expected([shown[0]], scale[h])[0])
|
||||||
|
|
||||||
# Stop sending: the pattern should come back after the timeout
|
# Stop sending: the pattern should come back after the timeout
|
||||||
sender.stop()
|
sender.stop()
|
||||||
time.sleep(3.0)
|
time.sleep(3.0)
|
||||||
for h in hosts:
|
for h in hosts:
|
||||||
after = get(h, "/api/ddp")
|
after = soft_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 = soft_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)))
|
||||||
|
global UNICAST_SYNC
|
||||||
|
UNICAST_SYNC = "--broadcast-only" not in sys.argv[1:]
|
||||||
|
expect = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--expect=")), None)
|
||||||
|
prefix = subnet or local_prefix()
|
||||||
|
broadcast = f"{prefix}.255" # the sync is broadcast to this network's broadcast address
|
||||||
|
rig = None if "--discover" in sys.argv[1:] else load_rig()
|
||||||
if args:
|
if args:
|
||||||
hosts = args
|
hosts = args
|
||||||
|
elif rig:
|
||||||
|
hosts = [d["ip"] for d in rig["devices"]]
|
||||||
|
ROW_OF.update({n: d["row"] - 1 for n, d in enumerate(rig["devices"])})
|
||||||
|
print(f"rig map {os.path.basename(RIG_FILE)}: {len(hosts)} device(s)")
|
||||||
|
for d in rig["devices"]:
|
||||||
|
print(f" {d['name']} {d['ip']} row {d['row']} column {d['column']}"
|
||||||
|
f"{' reversed' if d.get('reversed') else ''}{' usb ' + d['usb'] if d.get('usb') else ''}")
|
||||||
|
print()
|
||||||
|
if serial_port is None:
|
||||||
|
usb = [d for d in rig["devices"] if d.get("usb")]
|
||||||
|
if len(hosts) == 1 and usb:
|
||||||
|
serial_port = usb[0]["usb"]
|
||||||
else:
|
else:
|
||||||
prefix = subnet or local_prefix()
|
hosts = find_devices(prefix, int(expect) if expect else None)
|
||||||
hosts = find_devices(prefix)
|
if expect and len(hosts) < int(expect):
|
||||||
|
print(f"warning: expected {expect} device(s), found {len(hosts)}")
|
||||||
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:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
@@ -370,7 +1004,23 @@ 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 not any(a.startswith("--fps=") for a in sys.argv[1:]):
|
||||||
|
# Every bar gets every frame, so the network carries bars x fps frames a second: past FRAME_BUDGET the
|
||||||
|
# devices stop answering HTTP and frames are lost. A big rig runs slower unless --fps says otherwise.
|
||||||
|
fps = max(1, min(FPS, FRAME_BUDGET // len(hosts)))
|
||||||
|
if fps < FPS:
|
||||||
|
set_fps(fps)
|
||||||
|
print(f"{len(hosts)} devices: running at {fps} fps (the Wi-Fi carries about {FRAME_BUDGET} frames a second in all; --fps=N overrides)\n")
|
||||||
|
|
||||||
|
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}")
|
||||||
|
|||||||
Executable
+112
@@ -0,0 +1,112 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Move bars to another Wi-Fi network (SSID), one at a time, checking each comes back.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
tools/move_bars.py --ssid=lighting-b 109 110 111 112 113 114 115 116
|
||||||
|
tools/move_bars.py --ssid=lighting-b --password-env=WIFI_PASS 109 # password from an environment variable
|
||||||
|
tools/move_bars.py --ssid=lighting-b --dry-run 109 # show what would change, send nothing
|
||||||
|
|
||||||
|
Bars are the last octet (109) or a full address (192.168.50.109).
|
||||||
|
|
||||||
|
The password is asked for at a prompt (hidden), or read from the environment variable named by
|
||||||
|
--password-env. It is never taken from the command line, so it does not land in the shell history or the
|
||||||
|
process list. The same password is used for the new network and, if a bar does not come back, for putting
|
||||||
|
it back on the network it was on, so both networks need the same password.
|
||||||
|
|
||||||
|
Each bar is changed, then polled until it reports the new SSID and is connected. The first bar that does
|
||||||
|
not come back is put back on its old network and the run stops, so a mistake costs one bar, not all of them.
|
||||||
|
Run this from a machine that is on the LED subnet.
|
||||||
|
"""
|
||||||
|
import getpass
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
PREFIX = "192.168.50."
|
||||||
|
COME_BACK_S = 45 # how long a bar has to join the new network
|
||||||
|
POLL_S = 2
|
||||||
|
|
||||||
|
|
||||||
|
def call(host, path, body=None, timeout=5):
|
||||||
|
req = urllib.request.Request(f"http://{host}{path}")
|
||||||
|
if body is not None:
|
||||||
|
req.add_header("Content-Type", "application/json")
|
||||||
|
req.data = json.dumps(body).encode()
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||||
|
return json.loads(r.read().decode() or "{}")
|
||||||
|
|
||||||
|
|
||||||
|
def wifi_state(host):
|
||||||
|
try:
|
||||||
|
return call(host, "/api/wifi", timeout=3)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def switch(host, ssid, password):
|
||||||
|
"""Tell a bar to join ssid and wait for it to report that it has. True if it did."""
|
||||||
|
try:
|
||||||
|
call(host, "/api/wifi", {"ssid": ssid, "password": password})
|
||||||
|
except OSError:
|
||||||
|
pass # the bar may drop the connection as it switches; the poll below tells
|
||||||
|
end = time.time() + COME_BACK_S
|
||||||
|
time.sleep(POLL_S)
|
||||||
|
while time.time() < end:
|
||||||
|
st = wifi_state(host)
|
||||||
|
if st and st.get("ssid") == ssid and st.get("connected"):
|
||||||
|
return True
|
||||||
|
time.sleep(POLL_S)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = sys.argv[1:]
|
||||||
|
opts = {a.split("=", 1)[0]: (a.split("=", 1)[1] if "=" in a else True) for a in args if a.startswith("--")}
|
||||||
|
names = [a for a in args if not a.startswith("--")]
|
||||||
|
ssid = opts.get("--ssid")
|
||||||
|
if not isinstance(ssid, str) or not names:
|
||||||
|
print(__doc__)
|
||||||
|
return 2
|
||||||
|
hosts = [n if "." in n else PREFIX + n for n in names]
|
||||||
|
dry = "--dry-run" in opts
|
||||||
|
|
||||||
|
password = ""
|
||||||
|
if not dry:
|
||||||
|
env = opts.get("--password-env")
|
||||||
|
password = os.environ.get(env, "") if isinstance(env, str) else getpass.getpass(f"Wi-Fi password for {ssid} (hidden): ")
|
||||||
|
if len(password) != 0 and not 8 <= len(password) <= 64:
|
||||||
|
print("The password must be empty or 8-64 characters.")
|
||||||
|
return 2
|
||||||
|
|
||||||
|
moved = 0
|
||||||
|
for h in hosts:
|
||||||
|
st = wifi_state(h)
|
||||||
|
if st is None:
|
||||||
|
print(f"{h}: no answer, skipped")
|
||||||
|
continue
|
||||||
|
old = st.get("ssid", "")
|
||||||
|
if old == ssid and st.get("connected"):
|
||||||
|
print(f"{h}: already on {ssid}")
|
||||||
|
continue
|
||||||
|
if dry:
|
||||||
|
print(f"{h}: would move from {old!r} to {ssid!r}")
|
||||||
|
continue
|
||||||
|
print(f"{h}: {old!r} -> {ssid!r} ...", end=" ", flush=True)
|
||||||
|
if switch(h, ssid, password):
|
||||||
|
print("ok")
|
||||||
|
moved += 1
|
||||||
|
continue
|
||||||
|
print("did not come back; putting it back on", repr(old))
|
||||||
|
if old and switch(h, old, password):
|
||||||
|
print(f"{h}: back on {old!r}. Stopping, the other bars were not touched.")
|
||||||
|
else:
|
||||||
|
print(f"{h}: NOT reachable. Power-cycle it; it keeps the last network it was given.")
|
||||||
|
return 1
|
||||||
|
print(f"{moved} bar(s) moved")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
"""
|
||||||
|
Find every LED driver on a Wi-Fi subnet and update them in parallel.
|
||||||
|
|
||||||
|
A driver answers GET /ota with its partition and build info (see ota.py), so discovery is a
|
||||||
|
parallel probe of every address on the subnet. Then each found driver gets the same image,
|
||||||
|
JOBS at a time.
|
||||||
|
|
||||||
|
python3 tools/ota_all.py # discover on this machine's subnet, then update all
|
||||||
|
python3 tools/ota_all.py --subnet=192.168.4 # pick the subnet
|
||||||
|
python3 tools/ota_all.py --list # only discover and print, no update
|
||||||
|
python3 tools/ota_all.py --jobs=2 # fewer simultaneous uploads (default 4)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import concurrent.futures as cf
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
from ota import IMAGE_NAME, _default_image, _info, ota_update # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def local_subnet() -> str:
|
||||||
|
"""First three octets of the address this machine uses to reach the internet."""
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
try:
|
||||||
|
s.connect(("192.0.2.1", 9)) # no packet is sent for a UDP connect
|
||||||
|
ip = s.getsockname()[0]
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
return ".".join(ip.split(".")[:3])
|
||||||
|
|
||||||
|
|
||||||
|
def discover(subnet: str, port: int, workers: int, timeout: float) -> list[tuple[str, dict]]:
|
||||||
|
hosts = [f"{subnet}.{i}" for i in range(1, 255)]
|
||||||
|
found = []
|
||||||
|
with cf.ThreadPoolExecutor(max_workers=workers) as pool:
|
||||||
|
futures = {pool.submit(_info, h, port): h for h in hosts}
|
||||||
|
for fut in cf.as_completed(futures):
|
||||||
|
info = fut.result()
|
||||||
|
if info:
|
||||||
|
found.append((futures[fut], info))
|
||||||
|
return sorted(found, key=lambda t: tuple(int(x) for x in t[0].split(".")))
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
ap = argparse.ArgumentParser(description="Discover LED drivers on a subnet and update them in parallel.")
|
||||||
|
ap.add_argument("--subnet", help="first three octets, e.g. 192.168.4 (default: this machine's subnet)")
|
||||||
|
ap.add_argument("--image", help=f"firmware image (default: build/{IMAGE_NAME})")
|
||||||
|
ap.add_argument("--port", type=int, default=80)
|
||||||
|
ap.add_argument("--jobs", type=int, default=4, help="simultaneous uploads (default 4)")
|
||||||
|
ap.add_argument("--scan-workers", type=int, default=64, help="simultaneous probes during discovery")
|
||||||
|
ap.add_argument("--list", action="store_true", help="only discover and list drivers, do not update")
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
subnet = args.subnet or local_subnet()
|
||||||
|
print(f"Scanning {subnet}.1-254 on port {args.port}...")
|
||||||
|
drivers = discover(subnet, args.port, args.scan_workers, timeout=1.5)
|
||||||
|
if not drivers:
|
||||||
|
print("No drivers found.", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print(f"Found {len(drivers)} driver(s):")
|
||||||
|
for host, info in drivers:
|
||||||
|
print(f" {host:<16} {info.get('partition', '?'):<8} built {info.get('built', '?')}")
|
||||||
|
if args.list:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
image = args.image or _default_image()
|
||||||
|
if not image:
|
||||||
|
print(f"error: no image given and {IMAGE_NAME} not found under ./build (run make build)", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print(f"\nUpdating {len(drivers)} driver(s) with {image}, {args.jobs} at a time...")
|
||||||
|
failed = []
|
||||||
|
with cf.ThreadPoolExecutor(max_workers=args.jobs) as pool:
|
||||||
|
futures = {pool.submit(ota_update, h, image, args.port): h for h, _ in drivers}
|
||||||
|
for fut in cf.as_completed(futures):
|
||||||
|
host = futures[fut]
|
||||||
|
try:
|
||||||
|
fut.result()
|
||||||
|
print(f"OK {host}")
|
||||||
|
except RuntimeError as e:
|
||||||
|
failed.append(host)
|
||||||
|
print(f"FAILED {host}: {e}", file=sys.stderr)
|
||||||
|
|
||||||
|
ok = len(drivers) - len(failed)
|
||||||
|
print(f"\n{ok} updated, {len(failed)} failed" + (f": {' '.join(failed)}" if failed else ""))
|
||||||
|
return 1 if failed else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"_note": "Where each LED driver is. row 1 is the front and row 8 the back; column 1 is the left and column 2 the right (the simulator's grid, led-simulator/layout.py). Devices 101-108 are the left column front to back, 109-116 the right column. Rows 2-7 follow the IP order and were not checked one by one. reversed: true if the strip runs right to left.",
|
||||||
|
"rows": 8,
|
||||||
|
"columns": 2,
|
||||||
|
"devices": [
|
||||||
|
{"name": "c1-r1", "ip": "192.168.50.101", "row": 1, "column": 1, "reversed": false},
|
||||||
|
{"name": "c1-r2", "ip": "192.168.50.102", "row": 2, "column": 1, "reversed": false},
|
||||||
|
{"name": "c1-r3", "ip": "192.168.50.103", "row": 3, "column": 1, "reversed": false},
|
||||||
|
{"name": "c1-r4", "ip": "192.168.50.104", "row": 4, "column": 1, "reversed": false},
|
||||||
|
{"name": "c1-r5", "ip": "192.168.50.105", "row": 5, "column": 1, "reversed": false, "usb": "/dev/ttyACM0"},
|
||||||
|
{"name": "c1-r6", "ip": "192.168.50.106", "row": 6, "column": 1, "reversed": false},
|
||||||
|
{"name": "c1-r7", "ip": "192.168.50.107", "row": 7, "column": 1, "reversed": false},
|
||||||
|
{"name": "c1-r8", "ip": "192.168.50.108", "row": 8, "column": 1, "reversed": false},
|
||||||
|
{"name": "c2-r1", "ip": "192.168.50.109", "row": 1, "column": 2, "reversed": false},
|
||||||
|
{"name": "c2-r2", "ip": "192.168.50.110", "row": 2, "column": 2, "reversed": false},
|
||||||
|
{"name": "c2-r3", "ip": "192.168.50.111", "row": 3, "column": 2, "reversed": false},
|
||||||
|
{"name": "c2-r4", "ip": "192.168.50.112", "row": 4, "column": 2, "reversed": false},
|
||||||
|
{"name": "c2-r5", "ip": "192.168.50.113", "row": 5, "column": 2, "reversed": false},
|
||||||
|
{"name": "c2-r6", "ip": "192.168.50.114", "row": 6, "column": 2, "reversed": false},
|
||||||
|
{"name": "c2-r7", "ip": "192.168.50.115", "row": 7, "column": 2, "reversed": false},
|
||||||
|
{"name": "c2-r8", "ip": "192.168.50.116", "row": 8, "column": 2, "reversed": false}
|
||||||
|
]
|
||||||
|
}
|
||||||
+19
-2
@@ -596,6 +596,8 @@
|
|||||||
$('globalOut').textContent = level;
|
$('globalOut').textContent = level;
|
||||||
}
|
}
|
||||||
$('apName').textContent = s.ap_ssid;
|
$('apName').textContent = s.ap_ssid;
|
||||||
|
$('apInfo').hidden = !s.ap_on;
|
||||||
|
$('apOffInfo').hidden = !!s.ap_on;
|
||||||
$('staState').textContent = s.sta_connected ? 'connected (' + s.sta_ip + ')' : 'not connected';
|
$('staState').textContent = s.sta_connected ? 'connected (' + s.sta_ip + ')' : 'not connected';
|
||||||
await loadPatterns(s);
|
await loadPatterns(s);
|
||||||
}
|
}
|
||||||
@@ -888,6 +890,11 @@
|
|||||||
$('sGw').value = n.gateway;
|
$('sGw').value = n.gateway;
|
||||||
$('sDns').value = n.dns;
|
$('sDns').value = n.dns;
|
||||||
$('apOn').checked = n.ap_enabled !== false;
|
$('apOn').checked = n.ap_enabled !== false;
|
||||||
|
$('apSsid').value = n.ap_ssid_custom ? n.ap_ssid : '';
|
||||||
|
$('apSsid').placeholder = n.ap_ssid;
|
||||||
|
$('apPass').value = '';
|
||||||
|
$('apOpen').checked = false;
|
||||||
|
$('apPassHint').textContent = n.ap_password_set ? '(set; blank keeps it)' : '(open network now)';
|
||||||
$('ddpOn').checked = n.ddp_enabled !== false;
|
$('ddpOn').checked = n.ddp_enabled !== false;
|
||||||
updateStaticFields();
|
updateStaticFields();
|
||||||
}
|
}
|
||||||
@@ -942,12 +949,23 @@
|
|||||||
dns: $('sDns').value.trim(),
|
dns: $('sDns').value.trim(),
|
||||||
ap_enabled: $('apOn').checked,
|
ap_enabled: $('apOn').checked,
|
||||||
ddp_enabled: $('ddpOn').checked,
|
ddp_enabled: $('ddpOn').checked,
|
||||||
|
ap_ssid: $('apSsid').value.trim(),
|
||||||
};
|
};
|
||||||
|
if ($('apOpen').checked) {
|
||||||
|
body.ap_password = '';
|
||||||
|
} else if ($('apPass').value) {
|
||||||
|
body.ap_password = $('apPass').value;
|
||||||
|
}
|
||||||
$('netMsg').textContent = 'Saving…';
|
$('netMsg').textContent = 'Saving…';
|
||||||
try {
|
try {
|
||||||
const j = await post('/api/network', body);
|
const j = await post('/api/network', body);
|
||||||
$('netMsg').textContent = `Saved. The client reconnects; open http://${j.address}/ in a few seconds.`;
|
$('netMsg').textContent = `Saved. The client reconnects; open http://${j.address}/ in a few seconds.`;
|
||||||
$('mdnsName').textContent = body.hostname;
|
$('mdnsName').textContent = body.hostname;
|
||||||
|
$('apPass').value = '';
|
||||||
|
$('apOpen').checked = false;
|
||||||
|
if (body.ap_password !== undefined) {
|
||||||
|
$('apPassHint').textContent = body.ap_password ? '(set; blank keeps it)' : '(open network now)';
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
$('netMsg').textContent = e.message;
|
$('netMsg').textContent = e.message;
|
||||||
}
|
}
|
||||||
@@ -982,7 +1000,7 @@
|
|||||||
let found = [];
|
let found = [];
|
||||||
let localName = ''; // this device's name (its hostname), shown in the dropdown
|
let localName = ''; // this device's name (its hostname), shown in the dropdown
|
||||||
|
|
||||||
// The dropdown: This device, every driver found on the network, and any added by hand.
|
// The dropdown: This device, and the drivers added by hand. Drivers found by mDNS are not listed.
|
||||||
function deviceChoices() {
|
function deviceChoices() {
|
||||||
const here = location.hostname;
|
const here = location.hostname;
|
||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
@@ -992,7 +1010,6 @@
|
|||||||
seen.add(host);
|
seen.add(host);
|
||||||
out.push([host, label]);
|
out.push([host, label]);
|
||||||
};
|
};
|
||||||
found.filter((d) => d.ip !== here).forEach((d) => add(d.host, d.name));
|
|
||||||
loadDevices().forEach((h) => add(h, h));
|
loadDevices().forEach((h) => add(h, h));
|
||||||
// A device that drops off the network stays selected rather than vanishing from the list
|
// A device that drops off the network stays selected rather than vanishing from the list
|
||||||
if (base && base !== ALL && !seen.has(base)) out.push([base, base]);
|
if (base && base !== ALL && !seen.has(base)) out.push([base, base]);
|
||||||
|
|||||||
+9
-1
@@ -117,7 +117,8 @@
|
|||||||
|
|
||||||
<div class="subpage" data-sub="network" hidden>
|
<div class="subpage" data-sub="network" hidden>
|
||||||
<h2>Access point</h2>
|
<h2>Access point</h2>
|
||||||
<p>Network <strong id="apName">…</strong> (open). Address <strong>192.168.4.1</strong>.</p>
|
<p id="apInfo" hidden>Network <strong id="apName">…</strong> (open). Address <strong>192.168.4.1</strong>.</p>
|
||||||
|
<p id="apOffInfo" class="muted" hidden>Access point is off.</p>
|
||||||
|
|
||||||
<h2>Wi-Fi client</h2>
|
<h2>Wi-Fi client</h2>
|
||||||
<p>Status: <span id="staState">…</span></p>
|
<p>Status: <span id="staState">…</span></p>
|
||||||
@@ -161,6 +162,13 @@
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<label class="check"><input type="checkbox" id="apOn"> Access point on</label>
|
<label class="check"><input type="checkbox" id="apOn"> Access point on</label>
|
||||||
|
<label>Access point name <span class="muted">(blank for the default led-XXXXXX)</span>
|
||||||
|
<input id="apSsid" maxlength="32" autocomplete="off">
|
||||||
|
</label>
|
||||||
|
<label>Access point password <span class="muted" id="apPassHint">(blank keeps the current one)</span>
|
||||||
|
<input id="apPass" type="password" maxlength="63" autocomplete="off">
|
||||||
|
</label>
|
||||||
|
<label class="check"><input type="checkbox" id="apOpen"> Open network (no password)</label>
|
||||||
<label class="check"><input type="checkbox" id="ddpOn"> DDP and sync receive on</label>
|
<label class="check"><input type="checkbox" id="ddpOn"> DDP and sync receive on</label>
|
||||||
<p class="muted">Turn it off to use only your Wi-Fi network. Turning it off needs a connected Wi-Fi network. If the network stays down for about a minute, the access point comes back on by itself.</p>
|
<p class="muted">Turn it off to use only your Wi-Fi network. Turning it off needs a connected Wi-Fi network. If the network stays down for about a minute, the access point comes back on by itself.</p>
|
||||||
<button type="submit">Save network settings</button>
|
<button type="submit">Save network settings</button>
|
||||||
|
|||||||
Reference in new issue
Block a user