diff --git a/CMakeLists.txt b/CMakeLists.txt index 7face26..a962618 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,3 +1,8 @@ -cmake_minimum_required(VERSION 3.16) +# The following lines of boilerplate have to be in your project's CMakeLists +# in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.22) + include($ENV{IDF_PATH}/tools/cmake/project.cmake) +# "Trim" the build. Include the minimal set of components, main, and anything it depends on. +idf_build_set_property(MINIMAL_BUILD ON) project(led_driver) diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..eab8c04 --- /dev/null +++ b/Makefile @@ -0,0 +1,75 @@ +# Top-level Makefile for the led_strip ESP-IDF project. +# Thin wrapper around idf.py. Runs on Linux, macOS (bash) and Windows (GNU make with cmd.exe or sh). +# +# Override any variable on the command line, for example: +# make flash PORT=/dev/ttyUSB0 # Linux +# make flash PORT=/dev/cu.usbmodem101 # macOS +# make flash PORT=COM4 # Windows + +ifeq ($(OS),Windows_NT) + HOST_OS := windows + HOME_DIR := $(USERPROFILE) + DEFAULT_PORT := COM3 +else + HOST_OS := $(shell uname -s) + HOME_DIR := $(HOME) + ifeq ($(HOST_OS),Darwin) + DEFAULT_PORT := /dev/cu.usbmodem101 + else + DEFAULT_PORT := /dev/ttyACM0 + endif +endif + +IDF_PATH ?= $(HOME_DIR)/.espressif/v6.1/esp-idf +IDF_PYTHON_ENV_PATH ?= $(HOME_DIR)/.espressif/python_env/idf6.1_py3.12_env +PORT ?= $(DEFAULT_PORT) + +export IDF_PATH +export IDF_PYTHON_ENV_PATH + +# Run idf.py in a shell that has sourced ESP-IDF's environment script (sets PATH and toolchains). +ifeq ($(HOST_OS),windows) +define idf + cmd /c "$(subst /,\,$(IDF_PATH))\export.bat && idf.py $(1)" +endef +else +define idf + bash -c '. "$(IDF_PATH)/export.sh" >/dev/null 2>&1 && idf.py $(1)' +endef +endif + +.PHONY: all build flash monitor flash-monitor menuconfig clean fullclean help + +all: build + +build: + $(call idf,build) + +flash: build + $(call idf,-p $(PORT) flash) + +monitor: + $(call idf,-p $(PORT) monitor) + +flash-monitor: build + $(call idf,-p $(PORT) flash monitor) + +menuconfig: + $(call idf,menuconfig) + +clean: + $(call idf,clean) + +fullclean: + $(call idf,fullclean) + +help: + @echo Targets: + @echo build Build the firmware + @echo flash Build, then flash to the board on PORT + @echo monitor Open the serial monitor on PORT + @echo flash-monitor Build, flash, then open the serial monitor + @echo menuconfig Open the project configuration menu + @echo clean Remove build outputs + @echo fullclean Delete the build directory entirely + @echo help Show this help diff --git a/README.md b/README.md index a9e2c5b..86867f6 100644 --- a/README.md +++ b/README.md @@ -53,10 +53,32 @@ led-driver/ ## C++ app (ESP-IDF) -The `cpp` branch adds a basic ESP-IDF project for ESP32-S3 at the repo root (`CMakeLists.txt`, `main/`). +The `cpp` branch is an ESP-IDF app for the ESP32-C3 at the repo root (`CMakeLists.txt`, `main/`, `web/`). It drives a 119-LED WS2812 strip on GPIO 10 (set in `main/patterns.cpp`). + +### Web UI, access point and Wi-Fi client + +The firmware runs three things at once: + +- **Access point** `led-XXXXXX` (the last three bytes of the MAC), open, no password. Join it and browse to `http://192.168.4.1/`. +- **Wi-Fi client**: set a network from the Settings tab (scan, pick, enter password). Credentials are saved to NVS, and the client reconnects with backoff after a drop. +- **mDNS**: once on a network, the device answers as `http://led.local/`. + +Patterns: solid, rainbow, chase, breathe, blink, pulse, transition and circle. The web UI is embedded in the firmware from `web/`. + +JSON API (port 80): + +| Method | Path | Purpose | +|--------|------|---------| +| GET | `/api/status` | Current pattern and parameters, AP name, client state and IP | +| POST | `/api/pattern` | `{"mode","c1":[r,g,b],"c2":[r,g,b],"speed_ms","brightness"}` | +| GET | `/api/wifi` | Saved client SSID and connection state | +| POST | `/api/wifi` | `{"ssid","password"}`: save and connect | +| GET | `/api/wifi/scan` | Visible networks | + +Build and flash for the ESP32-C3: ```bash -. ~/.espressif/v6.1/esp-idf/export.sh # or your ESP-IDF install's export.sh -idf.py set-target esp32s3 +. ~/.espressif/v6.1/esp-idf/export.sh +idf.py set-target esp32c3 idf.py build flash monitor ``` diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 9eb7ec4..b9d35b6 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,2 +1,5 @@ -idf_component_register(SRCS "main.cpp" - INCLUDE_DIRS ".") +idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" + PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event + esp_timer nvs_flash esp_http_server cjson mdns esp_hw_support + INCLUDE_DIRS "." + EMBED_TXTFILES "../web/index.html" "../web/app.js" "../web/style.css") diff --git a/main/idf_component.yml b/main/idf_component.yml new file mode 100644 index 0000000..c674b8e --- /dev/null +++ b/main/idf_component.yml @@ -0,0 +1,5 @@ +dependencies: + espressif/mdns: + version: "^1.4.0" + espressif/cjson: + version: "^1.7.19" diff --git a/main/main.cpp b/main/main.cpp index bbbdcd5..565a5f0 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -1,18 +1,30 @@ -#include - +/* + * SPDX-License-Identifier: Apache-2.0 + */ #include "esp_log.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" +#include "nvs_flash.h" -static const char *TAG = "led_driver"; +#include "net.h" +#include "patterns.h" +#include "web.h" + +static const char *TAG = "example"; extern "C" void app_main(void) { - ESP_LOGI(TAG, "LED driver (C++) starting"); - - int tick = 0; - while (true) { - ESP_LOGI(TAG, "alive: %d", tick++); - vTaskDelay(pdMS_TO_TICKS(1000)); + // NVS holds the saved Wi-Fi client credentials + esp_err_t err = nvs_flash_init(); + if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { + ESP_ERROR_CHECK(nvs_flash_erase()); + err = nvs_flash_init(); } + ESP_ERROR_CHECK(err); + + patterns_start(); + ESP_ERROR_CHECK(net_start()); + ESP_ERROR_CHECK(web_start()); + + char ssid[16]; + net_ap_ssid(ssid, sizeof(ssid)); + ESP_LOGI(TAG, "Ready: join Wi-Fi %s and open http://192.168.4.1/, or http://led.local/ on your network", ssid); } diff --git a/main/net.cpp b/main/net.cpp new file mode 100644 index 0000000..3375672 --- /dev/null +++ b/main/net.cpp @@ -0,0 +1,180 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include + +#include "esp_event.h" +#include "esp_log.h" +#include "esp_mac.h" +#include "esp_netif.h" +#include "esp_timer.h" +#include "esp_wifi.h" +#include "mdns.h" +#include "net.h" + +static const char *TAG = "net"; + +#define AP_CHANNEL 1 +#define AP_MAX_CLIENTS 4 +#define MDNS_HOSTNAME "led" +#define RETRY_MAX_MS 30000 + +static esp_netif_t *s_ap_netif; +static esp_netif_t *s_sta_netif; +static esp_timer_handle_t s_retry_timer; +static volatile bool s_sta_up; +static esp_ip4_addr_t s_sta_ip; +static int s_retries; + +// Set the STA config from credentials. Empty password means an open network. +static void apply_sta_config(const wifi_creds_t *c) +{ + wifi_config_t cfg = {}; + strncpy((char *)cfg.sta.ssid, c->ssid, sizeof(cfg.sta.ssid) - 1); + strncpy((char *)cfg.sta.password, c->pass, sizeof(cfg.sta.password) - 1); + cfg.sta.threshold.authmode = c->pass[0] ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN; + esp_wifi_set_config(WIFI_IF_STA, &cfg); +} + +static void retry_cb(void *arg) +{ + (void)arg; + esp_wifi_connect(); +} + +static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *data) +{ + (void)arg; + (void)base; + (void)data; + switch (id) { + case WIFI_EVENT_STA_START: { + wifi_creds_t c; + if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) { + esp_wifi_connect(); + } + break; + } + case WIFI_EVENT_STA_DISCONNECTED: { + // Back off 1 s, 2 s, 4 s ... up to RETRY_MAX_MS + s_sta_up = false; + uint32_t delay_ms = 1000u << (s_retries < 5 ? s_retries : 5); + if (delay_ms > RETRY_MAX_MS) delay_ms = RETRY_MAX_MS; + s_retries++; + esp_timer_stop(s_retry_timer); + esp_timer_start_once(s_retry_timer, (uint64_t)delay_ms * 1000); + break; + } + default: + break; + } +} + +static void on_ip_event(void *arg, esp_event_base_t base, int32_t id, void *data) +{ + (void)arg; + (void)base; + (void)id; + ip_event_got_ip_t *e = (ip_event_got_ip_t *)data; + s_sta_ip = e->ip_info.ip; + s_sta_up = true; + s_retries = 0; + ESP_LOGI(TAG, "Client IP " IPSTR, IP2STR(&e->ip_info.ip)); +} + +void net_ap_ssid(char *buf, size_t len) +{ + uint8_t mac[6]; + esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP); + snprintf(buf, len, "led-%02X%02X%02X", mac[3], mac[4], mac[5]); +} + +esp_err_t net_start(void) +{ + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + s_ap_netif = esp_netif_create_default_wifi_ap(); + s_sta_netif = esp_netif_create_default_wifi_sta(); + + wifi_init_config_t init_cfg = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&init_cfg)); + ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, on_wifi_event, NULL, NULL)); + ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_ip_event, NULL, NULL)); + + const esp_timer_create_args_t timer_args = { + .callback = retry_cb, + .arg = NULL, + .dispatch_method = ESP_TIMER_TASK, + .name = "wifi_retry", + .skip_unhandled_events = false, + }; + ESP_ERROR_CHECK(esp_timer_create(&timer_args, &s_retry_timer)); + + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA)); + + // Open access point named led-XXXXXX + char ssid[16]; + net_ap_ssid(ssid, sizeof(ssid)); + wifi_config_t ap = {}; + strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1); + ap.ap.ssid_len = strlen(ssid); + ap.ap.channel = AP_CHANNEL; + ap.ap.max_connection = AP_MAX_CLIENTS; + ap.ap.authmode = WIFI_AUTH_OPEN; + ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap)); + + // Client credentials, if any were saved + wifi_creds_t c; + if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) { + apply_sta_config(&c); + } + + ESP_ERROR_CHECK(esp_wifi_start()); + ESP_LOGI(TAG, "AP %s started", ssid); + + // mDNS: led.local, with an HTTP service on port 80 + ESP_ERROR_CHECK(mdns_init()); + ESP_ERROR_CHECK(mdns_hostname_set(MDNS_HOSTNAME)); + ESP_ERROR_CHECK(mdns_instance_name_set("LED controller")); + ESP_ERROR_CHECK(mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0)); + ESP_LOGI(TAG, "mDNS: %s.local", MDNS_HOSTNAME); + return ESP_OK; +} + +bool net_sta_status(char *ip, size_t ip_len) +{ + if (ip_len) { + ip[0] = '\0'; + } + if (!s_sta_up) { + return false; + } + snprintf(ip, ip_len, IPSTR, IP2STR(&s_sta_ip)); + return true; +} + +esp_err_t net_sta_connect(const wifi_creds_t *c) +{ + esp_err_t err = settings_save_wifi(c); + if (err != ESP_OK) { + return err; + } + esp_timer_stop(s_retry_timer); + esp_wifi_disconnect(); + s_retries = 0; + apply_sta_config(c); + return esp_wifi_connect(); +} + +esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count) +{ + esp_err_t err = esp_wifi_scan_start(NULL, true); + if (err != ESP_OK) { + return err; + } + uint16_t max = *count; + err = esp_wifi_scan_get_ap_records(&max, recs); + *count = max; + return err; +} diff --git a/main/net.h b/main/net.h new file mode 100644 index 0000000..8cf0146 --- /dev/null +++ b/main/net.h @@ -0,0 +1,26 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include + +#include "esp_err.h" +#include "esp_wifi_types.h" +#include "settings.h" + +/** @brief Start Wi-Fi (AP `led-XXXXXX` plus an optional client), and mDNS as led.local. Needs NVS. */ +esp_err_t net_start(void); + +/** @brief Fill buf with the AP SSID, e.g. "led-A1B2C3". */ +void net_ap_ssid(char *buf, size_t len); + +/** @brief Client link state and its IPv4 address ("" if not connected). */ +bool net_sta_status(char *ip, size_t ip_len); + +/** @brief Save credentials, then connect the client with them. */ +esp_err_t net_sta_connect(const wifi_creds_t *c); + +/** @brief Scan for networks. On entry *count is the array size; on exit, the number found. */ +esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count); diff --git a/main/patterns.cpp b/main/patterns.cpp new file mode 100644 index 0000000..763b57b --- /dev/null +++ b/main/patterns.cpp @@ -0,0 +1,188 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#include + +#include "esp_log.h" +#include "esp_timer.h" +#include "driver/gpio.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" + +#include "patterns.h" +#include "ws2812.h" + +#define RMT_LED_STRIP_GPIO_NUM GPIO_NUM_10 +#define EXAMPLE_LED_NUMBERS 119 +#define FRAME_MS 20 + +static const char *TAG = "patterns"; + +static const char *const s_names[PM_COUNT] = { + "solid", "rainbow", "chase", "breathe", "blink", "pulse", "transition", "circle", +}; + +static WS2812 *s_strip; +static SemaphoreHandle_t s_lock; +static pattern_params_t s_p = { PM_CHASE, { 255, 0, 0 }, { 0, 0, 0 }, 1000, 16 }; + +const char *patterns_mode_name(pattern_mode_t m) +{ + return (m >= 0 && m < PM_COUNT) ? s_names[m] : ""; +} + +pattern_mode_t patterns_mode_from_name(const char *name) +{ + for (int i = 0; i < PM_COUNT; i++) { + if (strcmp(name, s_names[i]) == 0) { + return (pattern_mode_t)i; + } + } + return PM_COUNT; +} + +void patterns_set(const pattern_params_t &p) +{ + pattern_params_t q = p; + if (q.speed_ms < 10) q.speed_ms = 10; + if (q.speed_ms > 10000) q.speed_ms = 10000; + if (q.mode >= PM_COUNT) q.mode = PM_SOLID; + xSemaphoreTake(s_lock, portMAX_DELAY); + s_p = q; + xSemaphoreGive(s_lock); +} + +pattern_params_t patterns_get(void) +{ + xSemaphoreTake(s_lock, portMAX_DELAY); + pattern_params_t p = s_p; + xSemaphoreGive(s_lock); + return p; +} + +// Linear blend from a (k=0) to b (k=255) +static void lerp(const uint8_t *a, const uint8_t *b, uint32_t k, uint8_t *out) +{ + for (int i = 0; i < 3; i++) { + out[i] = (uint8_t)(a[i] + ((int)b[i] - a[i]) * (int)k / 255); + } +} + +// Draw one frame of the pattern at time t (ms since the start of the pattern) +static void render(const pattern_params_t &p, uint32_t t, WS2812 &s) +{ + const size_t n = s.size(); + const uint32_t sp = p.speed_ms; + uint8_t col[3]; + + switch (p.mode) { + case PM_SOLID: + s.fill(p.c1[0], p.c1[1], p.c1[2]); + break; + + case PM_RAINBOW: { + uint32_t off = (t / sp) % 360; + for (size_t i = 0; i < n; i++) { + uint32_t r, g, b; + WS2812::hsv2rgb((i * 360 / n + off) % 360, 100, 100, &r, &g, &b); + s.set(i, r, g, b); + } + break; + } + + case PM_CHASE: { + // Every third LED lit, moving one step per speed_ms; hue shifts each full cycle + uint32_t step = t / sp; + uint32_t phase = step % 3; + uint32_t off = ((step / 3) * 60) % 360; + s.fill(0, 0, 0); + for (size_t j = phase; j < n; j += 3) { + uint32_t r, g, b; + WS2812::hsv2rgb((j * 360 / n + off) % 360, 100, 100, &r, &g, &b); + s.set(j, r, g, b); + } + break; + } + + case PM_BREATHE: { + uint32_t period = sp * 2 < 500 ? 500 : sp * 2; + uint32_t ph = t % period; + uint32_t k = ph * 2 < period ? (ph * 2 * 255) / period : ((period - ph) * 2 * 255) / period; + lerp(p.c2, p.c1, k, col); + s.fill(col[0], col[1], col[2]); + break; + } + + case PM_BLINK: + if ((t / sp) % 2 == 0) { + s.fill(p.c1[0], p.c1[1], p.c1[2]); + } else { + s.fill(p.c2[0], p.c2[1], p.c2[2]); + } + break; + + case PM_PULSE: { + // Attack over the first 10% of the period, then a linear decay back to c2 + uint32_t period = sp * 2 < 200 ? 200 : sp * 2; + uint32_t frac = ((t % period) * 1000) / period; + uint32_t k = frac < 100 ? frac * 255 / 100 : (1000 - frac) * 255 / 900; + lerp(p.c2, p.c1, k, col); + s.fill(col[0], col[1], col[2]); + break; + } + + case PM_TRANSITION: { + // c1 -> c2 over speed_ms, then back again + uint32_t period = 2 * sp; + uint32_t ph = t % period; + uint32_t k = ph < sp ? ph * 255 / sp : (period - ph) * 255 / sp; + lerp(p.c1, p.c2, k, col); + s.fill(col[0], col[1], col[2]); + break; + } + + case PM_CIRCLE: { + // A segment a third of the strip long, moving around the ring + size_t head = (t / sp) % n; + size_t len = n / 3 < 1 ? 1 : n / 3; + for (size_t i = 0; i < n; i++) { + size_t dist = (head + n - i) % n; + if (dist < len) { + s.set(i, p.c1[0], p.c1[1], p.c1[2]); + } else { + s.set(i, p.c2[0], p.c2[1], p.c2[2]); + } + } + break; + } + + default: + break; + } +} + +static void patterns_task(void *arg) +{ + (void)arg; + const uint32_t t0 = (uint32_t)(esp_timer_get_time() / 1000); + while (true) { + pattern_params_t p = patterns_get(); + uint32_t now = (uint32_t)(esp_timer_get_time() / 1000); + s_strip->setBrightness(p.brightness); + render(p, now - t0, *s_strip); + esp_err_t err = s_strip->write(); + if (err != ESP_OK) { + ESP_LOGW(TAG, "LED write failed: %s", esp_err_to_name(err)); + } + vTaskDelay(pdMS_TO_TICKS(FRAME_MS)); + } +} + +void patterns_start(void) +{ + s_lock = xSemaphoreCreateMutex(); + s_strip = new WS2812(RMT_LED_STRIP_GPIO_NUM, EXAMPLE_LED_NUMBERS); + xTaskCreate(patterns_task, "patterns", 4096, NULL, 5, NULL); + ESP_LOGI(TAG, "Started %d LEDs on GPIO %d", EXAMPLE_LED_NUMBERS, (int)RMT_LED_STRIP_GPIO_NUM); +} diff --git a/main/patterns.h b/main/patterns.h new file mode 100644 index 0000000..81ad8f8 --- /dev/null +++ b/main/patterns.h @@ -0,0 +1,42 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include + +// Pattern names (also the strings the web UI uses). Order matters: the index is the mode id. +enum pattern_mode_t { + PM_SOLID, + PM_RAINBOW, + PM_CHASE, + PM_BREATHE, + PM_BLINK, + PM_PULSE, + PM_TRANSITION, + PM_CIRCLE, + PM_COUNT, +}; + +struct pattern_params_t { + pattern_mode_t mode; + uint8_t c1[3]; // main colour (ignored by rainbow and chase) + uint8_t c2[3]; // background / second colour + uint32_t speed_ms; // one step of the pattern, 10-10000 ms + uint8_t brightness; // 0-255 +}; + +/** @brief Start the LED strip and the pattern task. */ +void patterns_start(void); + +/** @brief Replace the running pattern. Values are clamped to valid ranges. */ +void patterns_set(const pattern_params_t &p); + +/** @brief Copy of the running pattern. */ +pattern_params_t patterns_get(void); + +/** @brief Name of a mode, e.g. "rainbow". */ +const char *patterns_mode_name(pattern_mode_t m); + +/** @brief Mode for a name, or PM_COUNT if unknown. */ +pattern_mode_t patterns_mode_from_name(const char *name); diff --git a/main/settings.cpp b/main/settings.cpp new file mode 100644 index 0000000..6357793 --- /dev/null +++ b/main/settings.cpp @@ -0,0 +1,42 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#include "nvs.h" +#include "settings.h" + +static const char *NS = "led"; + +esp_err_t settings_load_wifi(wifi_creds_t *c) +{ + nvs_handle_t h; + esp_err_t err = nvs_open(NS, NVS_READONLY, &h); + if (err != ESP_OK) { + return err; + } + size_t len = sizeof(c->ssid); + err = nvs_get_str(h, "sta_ssid", c->ssid, &len); + if (err == ESP_OK) { + len = sizeof(c->pass); + err = nvs_get_str(h, "sta_pass", c->pass, &len); + if (err == ESP_ERR_NVS_NOT_FOUND) { + c->pass[0] = '\0'; + err = ESP_OK; + } + } + nvs_close(h); + return err; +} + +esp_err_t settings_save_wifi(const wifi_creds_t *c) +{ + nvs_handle_t h; + esp_err_t err = nvs_open(NS, NVS_READWRITE, &h); + if (err != ESP_OK) { + return err; + } + err = nvs_set_str(h, "sta_ssid", c->ssid); + if (err == ESP_OK) err = nvs_set_str(h, "sta_pass", c->pass); + if (err == ESP_OK) err = nvs_commit(h); + nvs_close(h); + return err; +} diff --git a/main/settings.h b/main/settings.h new file mode 100644 index 0000000..633d25a --- /dev/null +++ b/main/settings.h @@ -0,0 +1,17 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "esp_err.h" + +struct wifi_creds_t { + char ssid[33]; + char pass[65]; +}; + +/** @brief Read saved Wi-Fi client credentials. ESP_ERR_NVS_NOT_FOUND if none are saved. */ +esp_err_t settings_load_wifi(wifi_creds_t *c); + +/** @brief Save Wi-Fi client credentials to NVS. */ +esp_err_t settings_save_wifi(const wifi_creds_t *c); diff --git a/main/web.cpp b/main/web.cpp new file mode 100644 index 0000000..1186618 --- /dev/null +++ b/main/web.cpp @@ -0,0 +1,276 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#include + +#include "cJSON.h" +#include "esp_http_server.h" +#include "esp_log.h" +#include "esp_wifi.h" +#include "net.h" +#include "patterns.h" +#include "settings.h" +#include "web.h" + +static const char *TAG = "web"; + +// Files embedded from web/ (see main/CMakeLists.txt EMBED_TXTFILES) +extern const char index_html_start[] asm("_binary_index_html_start"); +extern const char index_html_end[] asm("_binary_index_html_end"); +extern const char app_js_start[] asm("_binary_app_js_start"); +extern const char app_js_end[] asm("_binary_app_js_end"); +extern const char style_css_start[] asm("_binary_style_css_start"); +extern const char style_css_end[] asm("_binary_style_css_end"); + +static httpd_handle_t s_server; + +#define MAX_BODY 512 +#define MAX_SCAN 20 + +static esp_err_t send_embedded(httpd_req_t *req, const char *type, const char *start, const char *end) +{ + httpd_resp_set_type(req, type); + httpd_resp_set_hdr(req, "Cache-Control", "no-cache"); + return httpd_resp_send(req, start, end - start); +} + +static esp_err_t send_json(httpd_req_t *req, cJSON *obj) +{ + char *s = cJSON_PrintUnformatted(obj); + cJSON_Delete(obj); + if (!s) { + return httpd_resp_send_500(req); + } + httpd_resp_set_type(req, "application/json"); + esp_err_t err = httpd_resp_sendstr(req, s); + cJSON_free(s); + return err; +} + +static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg) +{ + httpd_resp_set_status(req, status); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "error", msg); + return send_json(req, o); +} + +// Read the request body into buf (NUL-terminated). False if missing, too big or unreadable. +static bool read_body(httpd_req_t *req, char *buf, size_t cap) +{ + int len = req->content_len; + if (len <= 0 || (size_t)len >= cap) { + return false; + } + int got = 0; + while (got < len) { + int r = httpd_req_recv(req, buf + got, len - got); + if (r <= 0) { + return false; + } + got += r; + } + buf[got] = '\0'; + return true; +} + +static void read_rgb(const cJSON *arr, uint8_t *out) +{ + if (!cJSON_IsArray(arr) || cJSON_GetArraySize(arr) != 3) { + return; + } + for (int i = 0; i < 3; i++) { + cJSON *v = cJSON_GetArrayItem(arr, i); + if (cJSON_IsNumber(v)) { + int x = v->valueint; + out[i] = (uint8_t)(x < 0 ? 0 : x > 255 ? 255 : x); + } + } +} + +static void put_rgb(cJSON *obj, const char *key, const uint8_t *c) +{ + cJSON *a = cJSON_AddArrayToObject(obj, key); + for (int i = 0; i < 3; i++) { + cJSON_AddItemToArray(a, cJSON_CreateNumber(c[i])); + } +} + +// GET / , /app.js , /style.css +static esp_err_t index_get(httpd_req_t *req) +{ + return send_embedded(req, "text/html", index_html_start, index_html_end); +} + +static esp_err_t app_js_get(httpd_req_t *req) +{ + return send_embedded(req, "application/javascript", app_js_start, app_js_end); +} + +static esp_err_t style_css_get(httpd_req_t *req) +{ + return send_embedded(req, "text/css", style_css_start, style_css_end); +} + +// GET /api/status +static esp_err_t status_get(httpd_req_t *req) +{ + pattern_params_t p = patterns_get(); + char ap[16], ip[16]; + net_ap_ssid(ap, sizeof(ap)); + bool up = net_sta_status(ip, sizeof(ip)); + + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "ap_ssid", ap); + cJSON_AddBoolToObject(o, "sta_connected", up); + cJSON_AddStringToObject(o, "sta_ip", ip); + cJSON_AddStringToObject(o, "mode", patterns_mode_name(p.mode)); + cJSON *modes = cJSON_AddArrayToObject(o, "modes"); + for (int i = 0; i < PM_COUNT; i++) { + cJSON_AddItemToArray(modes, cJSON_CreateString(patterns_mode_name((pattern_mode_t)i))); + } + put_rgb(o, "c1", p.c1); + put_rgb(o, "c2", p.c2); + cJSON_AddNumberToObject(o, "speed_ms", p.speed_ms); + cJSON_AddNumberToObject(o, "brightness", p.brightness); + return send_json(req, o); +} + +// POST /api/pattern {"mode","c1":[r,g,b],"c2":[r,g,b],"speed_ms","brightness"} +static esp_err_t pattern_post(httpd_req_t *req) +{ + char body[MAX_BODY]; + if (!read_body(req, body, sizeof(body))) { + return send_error(req, "400 Bad Request", "empty or too large body"); + } + cJSON *in = cJSON_Parse(body); + if (!in) { + return send_error(req, "400 Bad Request", "invalid JSON"); + } + pattern_params_t p = patterns_get(); + cJSON *mode = cJSON_GetObjectItem(in, "mode"); + if (cJSON_IsString(mode)) { + pattern_mode_t m = patterns_mode_from_name(mode->valuestring); + if (m == PM_COUNT) { + cJSON_Delete(in); + return send_error(req, "400 Bad Request", "unknown mode"); + } + p.mode = m; + } + read_rgb(cJSON_GetObjectItem(in, "c1"), p.c1); + read_rgb(cJSON_GetObjectItem(in, "c2"), p.c2); + cJSON *speed = cJSON_GetObjectItem(in, "speed_ms"); + if (cJSON_IsNumber(speed)) p.speed_ms = (uint32_t)speed->valueint; + cJSON *bright = cJSON_GetObjectItem(in, "brightness"); + if (cJSON_IsNumber(bright)) { + int b = bright->valueint; + p.brightness = (uint8_t)(b < 0 ? 0 : b > 255 ? 255 : b); + } + cJSON_Delete(in); + patterns_set(p); + return send_json(req, cJSON_CreateObject()); +} + +// GET /api/wifi : saved client SSID and connection state +static esp_err_t wifi_get(httpd_req_t *req) +{ + wifi_creds_t c = {}; + settings_load_wifi(&c); + char ip[16]; + bool up = net_sta_status(ip, sizeof(ip)); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "ssid", c.ssid); + cJSON_AddBoolToObject(o, "connected", up); + cJSON_AddStringToObject(o, "ip", ip); + return send_json(req, o); +} + +// POST /api/wifi {"ssid","password"} : save and connect +static esp_err_t wifi_post(httpd_req_t *req) +{ + char body[MAX_BODY]; + if (!read_body(req, body, sizeof(body))) { + return send_error(req, "400 Bad Request", "empty or too large body"); + } + cJSON *in = cJSON_Parse(body); + if (!in) { + return send_error(req, "400 Bad Request", "invalid JSON"); + } + cJSON *ssid = cJSON_GetObjectItem(in, "ssid"); + cJSON *pass = cJSON_GetObjectItem(in, "password"); + const char *pw = cJSON_IsString(pass) ? pass->valuestring : ""; + if (!cJSON_IsString(ssid) || !ssid->valuestring[0] || strlen(ssid->valuestring) > 32) { + cJSON_Delete(in); + return send_error(req, "400 Bad Request", "SSID must be 1-32 characters"); + } + size_t plen = strlen(pw); + if (plen > 0 && (plen < 8 || plen > 64)) { + cJSON_Delete(in); + return send_error(req, "400 Bad Request", "password must be empty or 8-64 characters"); + } + wifi_creds_t c = {}; + strncpy(c.ssid, ssid->valuestring, sizeof(c.ssid) - 1); + strncpy(c.pass, pw, sizeof(c.pass) - 1); + cJSON_Delete(in); + + esp_err_t err = net_sta_connect(&c); + if (err != ESP_OK) { + ESP_LOGW(TAG, "Connect to %s failed: %s", c.ssid, esp_err_to_name(err)); + return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "message", "saved; connecting"); + return send_json(req, o); +} + +// GET /api/wifi/scan : visible networks +static esp_err_t wifi_scan_get(httpd_req_t *req) +{ + static wifi_ap_record_t recs[MAX_SCAN]; + uint16_t count = MAX_SCAN; + esp_err_t err = net_scan(recs, &count); + if (err != ESP_OK) { + return send_error(req, "500 Internal Server Error", esp_err_to_name(err)); + } + cJSON *arr = cJSON_CreateArray(); + for (int i = 0; i < count; i++) { + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "ssid", (const char *)recs[i].ssid); + cJSON_AddNumberToObject(o, "rssi", recs[i].rssi); + cJSON_AddBoolToObject(o, "open", recs[i].authmode == WIFI_AUTH_OPEN); + cJSON_AddItemToArray(arr, o); + } + cJSON *root = cJSON_CreateObject(); + cJSON_AddItemToObject(root, "networks", arr); + return send_json(req, root); +} + +static void add_uri(httpd_handle_t srv, const char *uri, httpd_method_t method, esp_err_t (*handler)(httpd_req_t *)) +{ + httpd_uri_t u = { .uri = uri, .method = method, .handler = handler, .user_ctx = NULL }; + httpd_register_uri_handler(srv, &u); +} + +esp_err_t web_start(void) +{ + httpd_config_t cfg = HTTPD_DEFAULT_CONFIG(); + cfg.max_uri_handlers = 12; + cfg.lru_purge_enable = true; + cfg.max_open_sockets = 7; + cfg.backlog_conn = 10; + esp_err_t err = httpd_start(&s_server, &cfg); + if (err != ESP_OK) { + ESP_LOGE(TAG, "HTTP server start failed: %s", esp_err_to_name(err)); + return err; + } + add_uri(s_server, "/", HTTP_GET, index_get); + add_uri(s_server, "/app.js", HTTP_GET, app_js_get); + add_uri(s_server, "/style.css", HTTP_GET, style_css_get); + add_uri(s_server, "/api/status", HTTP_GET, status_get); + add_uri(s_server, "/api/pattern", HTTP_POST, pattern_post); + add_uri(s_server, "/api/wifi", HTTP_GET, wifi_get); + add_uri(s_server, "/api/wifi", HTTP_POST, wifi_post); + add_uri(s_server, "/api/wifi/scan", HTTP_GET, wifi_scan_get); + ESP_LOGI(TAG, "Web UI on port 80"); + return ESP_OK; +} diff --git a/main/web.h b/main/web.h new file mode 100644 index 0000000..4c1b11d --- /dev/null +++ b/main/web.h @@ -0,0 +1,9 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "esp_err.h" + +/** @brief Start the HTTP server on port 80 (UI and JSON API). */ +esp_err_t web_start(void); diff --git a/main/ws2812.cpp b/main/ws2812.cpp new file mode 100644 index 0000000..96e5769 --- /dev/null +++ b/main/ws2812.cpp @@ -0,0 +1,237 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#include "ws2812.h" + +#include +#include "freertos/FreeRTOS.h" +#include "esp_check.h" +#include "esp_log.h" + +static const char *TAG = "ws2812"; + +/* ---- RMT encoder: turns RGB bytes into WS2812 waveform symbols ---- */ + +typedef struct { + rmt_encoder_t base; + rmt_encoder_t *bytes_encoder; + rmt_encoder_t *copy_encoder; + int state; + rmt_symbol_word_t reset_code; +} rmt_ws2812_encoder_t; + +RMT_ENCODER_FUNC_ATTR +static size_t rmt_encode_ws2812(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) +{ + rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base); + rmt_encoder_handle_t bytes_encoder = led_encoder->bytes_encoder; + rmt_encoder_handle_t copy_encoder = led_encoder->copy_encoder; + rmt_encode_state_t session_state = RMT_ENCODING_RESET; + rmt_encode_state_t state = RMT_ENCODING_RESET; + size_t encoded_symbols = 0; + switch (led_encoder->state) { + case 0: // send RGB data + encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, primary_data, data_size, &session_state); + if (session_state & RMT_ENCODING_COMPLETE) { + led_encoder->state = 1; // switch to next state when current encoding session finished + } + if (session_state & RMT_ENCODING_MEM_FULL) { + state = static_cast(state | RMT_ENCODING_MEM_FULL); + goto out; // yield if there's no free space for encoding artifacts + } + // fall-through + case 1: // send reset code + encoded_symbols += copy_encoder->encode(copy_encoder, channel, &led_encoder->reset_code, + sizeof(led_encoder->reset_code), &session_state); + if (session_state & RMT_ENCODING_COMPLETE) { + led_encoder->state = RMT_ENCODING_RESET; // back to the initial encoding session + state = static_cast(state | RMT_ENCODING_COMPLETE); + } + if (session_state & RMT_ENCODING_MEM_FULL) { + state = static_cast(state | RMT_ENCODING_MEM_FULL); + goto out; // yield if there's no free space for encoding artifacts + } + } +out: + *ret_state = state; + return encoded_symbols; +} + +static esp_err_t rmt_del_ws2812_encoder(rmt_encoder_t *encoder) +{ + rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base); + rmt_del_encoder(led_encoder->bytes_encoder); + rmt_del_encoder(led_encoder->copy_encoder); + free(led_encoder); + return ESP_OK; +} + +RMT_ENCODER_FUNC_ATTR +static esp_err_t rmt_ws2812_encoder_reset(rmt_encoder_t *encoder) +{ + rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base); + rmt_encoder_reset(led_encoder->bytes_encoder); + rmt_encoder_reset(led_encoder->copy_encoder); + led_encoder->state = RMT_ENCODING_RESET; + return ESP_OK; +} + +static esp_err_t new_ws2812_encoder(uint32_t resolution, rmt_encoder_handle_t *ret_encoder) +{ + // Declared up front: the error path jumps forward to `err`, which C++ forbids + // across initialised declarations. + esp_err_t ret = ESP_OK; + rmt_ws2812_encoder_t *led_encoder = NULL; + rmt_bytes_encoder_config_t bytes_encoder_config = {}; + rmt_copy_encoder_config_t copy_encoder_config = {}; + uint32_t reset_ticks = 0; + + ESP_GOTO_ON_FALSE(ret_encoder, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument"); + led_encoder = static_cast(rmt_alloc_encoder_mem(sizeof(rmt_ws2812_encoder_t))); + ESP_GOTO_ON_FALSE(led_encoder, ESP_ERR_NO_MEM, err, TAG, "no mem for ws2812 encoder"); + led_encoder->base.encode = rmt_encode_ws2812; + led_encoder->base.del = rmt_del_ws2812_encoder; + led_encoder->base.reset = rmt_ws2812_encoder_reset; + + // WS2812 timing + bytes_encoder_config.bit0.level0 = 1; + bytes_encoder_config.bit0.duration0 = 0.3 * resolution / 1000000; // T0H=0.3us + bytes_encoder_config.bit0.level1 = 0; + bytes_encoder_config.bit0.duration1 = 0.9 * resolution / 1000000; // T0L=0.9us + bytes_encoder_config.bit1.level0 = 1; + bytes_encoder_config.bit1.duration0 = 0.9 * resolution / 1000000; // T1H=0.9us + bytes_encoder_config.bit1.level1 = 0; + bytes_encoder_config.bit1.duration1 = 0.3 * resolution / 1000000; // T1L=0.3us + bytes_encoder_config.flags.msb_first = 1; // WS2812 transfer bit order: G7...G0R7...R0B7...B0 + ESP_GOTO_ON_ERROR(rmt_new_bytes_encoder(&bytes_encoder_config, &led_encoder->bytes_encoder), err, TAG, "create bytes encoder failed"); + ESP_GOTO_ON_ERROR(rmt_new_copy_encoder(©_encoder_config, &led_encoder->copy_encoder), err, TAG, "create copy encoder failed"); + + reset_ticks = resolution / 1000000 * 50 / 2; // reset code duration defaults to 50us + led_encoder->reset_code.level0 = 0; + led_encoder->reset_code.duration0 = reset_ticks; + led_encoder->reset_code.level1 = 0; + led_encoder->reset_code.duration1 = reset_ticks; + + *ret_encoder = &led_encoder->base; + return ESP_OK; +err: + if (led_encoder) { + if (led_encoder->bytes_encoder) { + rmt_del_encoder(led_encoder->bytes_encoder); + } + if (led_encoder->copy_encoder) { + rmt_del_encoder(led_encoder->copy_encoder); + } + free(led_encoder); + } + return ret; +} + +/* ---- WS2812 strip ---- */ + +WS2812::WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz) + : num_leds_(num_leds), pixels_(num_leds * 3, 0), tx_pixels_(num_leds * 3, 0) +{ + rmt_tx_channel_config_t tx_chan_config = {}; + tx_chan_config.clk_src = RMT_CLK_SRC_DEFAULT; + tx_chan_config.gpio_num = gpio; + tx_chan_config.mem_block_symbols = 64; // larger blocks reduce flicker + tx_chan_config.resolution_hz = resolution_hz; + tx_chan_config.trans_queue_depth = 4; + ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &channel_)); + + ESP_ERROR_CHECK(new_ws2812_encoder(resolution_hz, &encoder_)); + + ESP_ERROR_CHECK(rmt_enable(channel_)); + tx_config_.loop_count = 0; // send once per write() + + ESP_LOGI(TAG, "Strip ready: %zu LEDs on GPIO %d", num_leds_, (int)gpio); +} + +WS2812::~WS2812() +{ + if (channel_) { + rmt_tx_wait_all_done(channel_, portMAX_DELAY); + rmt_disable(channel_); + rmt_del_channel(channel_); + } + if (encoder_) { + encoder_->del(encoder_); + } +} + +void WS2812::set(size_t index, uint8_t r, uint8_t g, uint8_t b) +{ + if (index >= num_leds_) { + return; + } + uint8_t *p = &pixels_[index * 3]; + p[0] = g; + p[1] = r; + p[2] = b; +} + +void WS2812::fill(uint8_t r, uint8_t g, uint8_t b) +{ + for (size_t i = 0; i < num_leds_; i++) { + set(i, r, g, b); + } +} + +esp_err_t WS2812::write() +{ + for (size_t i = 0; i < pixels_.size(); i++) { + tx_pixels_[i] = static_cast(pixels_[i] * brightness_ / 255); + } + esp_err_t ret = rmt_transmit(channel_, encoder_, tx_pixels_.data(), tx_pixels_.size(), &tx_config_); + if (ret != ESP_OK) { + return ret; + } + return rmt_tx_wait_all_done(channel_, portMAX_DELAY); +} + +void WS2812::hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b) +{ + h %= 360; // h -> [0,360] + uint32_t rgb_max = v * 2.55f; + uint32_t rgb_min = rgb_max * (100 - s) / 100.0f; + + uint32_t i = h / 60; + uint32_t diff = h % 60; + + // RGB adjustment amount by hue + uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60; + + switch (i) { + case 0: + *r = rgb_max; + *g = rgb_min + rgb_adj; + *b = rgb_min; + break; + case 1: + *r = rgb_max - rgb_adj; + *g = rgb_max; + *b = rgb_min; + break; + case 2: + *r = rgb_min; + *g = rgb_max; + *b = rgb_min + rgb_adj; + break; + case 3: + *r = rgb_min; + *g = rgb_max - rgb_adj; + *b = rgb_max; + break; + case 4: + *r = rgb_min + rgb_adj; + *g = rgb_min; + *b = rgb_max; + break; + default: + *r = rgb_max; + *g = rgb_min; + *b = rgb_max - rgb_adj; + break; + } +} diff --git a/main/ws2812.h b/main/ws2812.h new file mode 100644 index 0000000..94f830c --- /dev/null +++ b/main/ws2812.h @@ -0,0 +1,74 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include +#include + +#include "driver/gpio.h" +#include "driver/rmt_encoder.h" +#include "driver/rmt_tx.h" +#include "esp_err.h" + +/** + * @brief WS2812-style addressable LED strip driven through the RMT peripheral. + * + * Pixel data is kept in a local buffer. set() and fill() only update that buffer; + * call write() to push the buffer out to the strip. + */ +class WS2812 { +public: + /** + * @param gpio GPIO connected to the strip's data input (DI) + * @param num_leds Number of LEDs in the strip + * @param resolution_hz RMT tick resolution; 10 MHz gives 0.1 us ticks, which WS2812 needs + */ + WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz = 10000000); + ~WS2812(); + + WS2812(const WS2812 &) = delete; + WS2812 &operator=(const WS2812 &) = delete; + + /** @brief Set one pixel in the buffer. Out-of-range indices are ignored. */ + void set(size_t index, uint8_t r, uint8_t g, uint8_t b); + + /** @brief Set every pixel in the buffer to the same colour. */ + void fill(uint8_t r, uint8_t g, uint8_t b); + + /** + * @brief Transmit the buffer to the strip and wait until the transfer finishes. + * @return ESP_OK on success, or an error from the RMT driver. + */ + esp_err_t write(); + + /** @brief Number of LEDs in the strip. */ + size_t size() const { return num_leds_; } + + /** + * @brief Set the output brightness, 0 (off) to 255 (full). Applied in write(); + * the pixel buffer keeps its full-colour values. Defaults to 255. + */ + void setBrightness(uint8_t level) { brightness_ = level; } + + /** @brief Current output brightness, 0-255. */ + uint8_t brightness() const { return brightness_; } + + /** + * @brief Convert HSV to RGB. + * + * h is the hue in degrees (wrapped to [0, 360)); s and v are 0-100 percent. + * Wiki: https://en.wikipedia.org/wiki/HSL_and_HSV + */ + static void hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b); + +private: + size_t num_leds_; + std::vector pixels_; // GRB byte order, 3 bytes per LED, as WS2812 expects + std::vector tx_pixels_; // pixels_ scaled by brightness_, sent by write() + uint8_t brightness_ = 255; + rmt_channel_handle_t channel_ = nullptr; + rmt_encoder_handle_t encoder_ = nullptr; + rmt_transmit_config_t tx_config_ = {}; +}; diff --git a/sdkconfig.defaults b/sdkconfig.defaults index b01fdbe..e238287 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -1 +1,3 @@ -CONFIG_IDF_TARGET="esp32s3" +CONFIG_IDF_TARGET="esp32c3" +# The mDNS console CLI needs the console component; the app does not use it. +CONFIG_MDNS_ENABLE_CONSOLE_CLI=n diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..37481af --- /dev/null +++ b/web/app.js @@ -0,0 +1,121 @@ +// LED strip web UI. Talks to the JSON API in main/web.cpp. +(() => { + const $ = (id) => document.getElementById(id); + + async function api(path, opts) { + const r = await fetch(path, opts); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(j.error || r.statusText); + return j; + } + + const post = (path, body) => api(path, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + + const toHex = (rgb) => '#' + rgb.map((v) => v.toString(16).padStart(2, '0')).join(''); + const fromHex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)); + + function updateOutputs() { + $('speedOut').textContent = $('speed').value + ' ms'; + $('brightOut').textContent = $('bright').value; + } + + // Coalesce slider drags into one request + let sendTimer; + function sendPattern() { + updateOutputs(); + clearTimeout(sendTimer); + sendTimer = setTimeout(async () => { + try { + await post('/api/pattern', { + mode: $('mode').value, + c1: fromHex($('c1').value), + c2: fromHex($('c2').value), + speed_ms: Number($('speed').value), + brightness: Number($('bright').value), + }); + $('status').textContent = 'Applied'; + } catch (e) { + $('status').textContent = e.message; + } + }, 150); + } + + async function loadStatus() { + const s = await api('/api/status'); + $('apName').textContent = s.ap_ssid; + $('staState').textContent = s.sta_connected ? 'connected (' + s.sta_ip + ')' : 'not connected'; + if (!$('mode').options.length) { + s.modes.forEach((m) => $('mode').add(new Option(m, m))); + } + $('mode').value = s.mode; + $('c1').value = toHex(s.c1); + $('c2').value = toHex(s.c2); + $('speed').value = s.speed_ms; + $('bright').value = s.brightness; + updateOutputs(); + } + + async function loadWifi() { + const w = await api('/api/wifi'); + if (w.ssid && !$('ssid').value) $('ssid').value = w.ssid; + } + + async function scan() { + const list = $('networks'); + list.textContent = 'Scanning…'; + try { + const { networks } = await api('/api/wifi/scan'); + list.textContent = ''; + networks.sort((a, b) => b.rssi - a.rssi).forEach((n) => { + const li = document.createElement('li'); + const btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'net'; + btn.textContent = `${n.ssid || '(hidden)'} ${n.rssi} dBm${n.open ? '' : ' đź”’'}`; + btn.addEventListener('click', () => { $('ssid').value = n.ssid; $('pass').focus(); }); + li.appendChild(btn); + list.appendChild(li); + }); + if (!networks.length) list.textContent = 'No networks found.'; + } catch (e) { + list.textContent = e.message; + } + } + + // Tabs + document.querySelectorAll('.tab').forEach((btn) => { + btn.addEventListener('click', () => { + document.querySelectorAll('.tab').forEach((b) => b.classList.toggle('active', b === btn)); + $('patterns').hidden = btn.dataset.tab !== 'patterns'; + $('settings').hidden = btn.dataset.tab !== 'settings'; + }); + }); + + ['mode', 'c1', 'c2', 'speed', 'bright'].forEach((id) => { + $(id).addEventListener('input', sendPattern); + $(id).addEventListener('change', sendPattern); + }); + + $('scan').addEventListener('click', scan); + + $('wifiForm').addEventListener('submit', async (ev) => { + ev.preventDefault(); + $('wifiMsg').textContent = 'Saving…'; + try { + const j = await post('/api/wifi', { ssid: $('ssid').value, password: $('pass').value }); + $('wifiMsg').textContent = j.message || 'Saved'; + $('pass').value = ''; + setTimeout(() => loadStatus().catch(() => {}), 4000); + } catch (e) { + $('wifiMsg').textContent = e.message; + } + }); + + loadStatus().catch((e) => { $('status').textContent = e.message; }); + loadWifi().catch(() => {}); + setInterval(() => loadStatus().catch(() => {}), 5000); +})(); diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..5c2dfdb --- /dev/null +++ b/web/index.html @@ -0,0 +1,64 @@ + + + + + + LED strip + + + +
+

LED strip

+ +
+ +
+
+ +
+ + +
+ + +

+
+ + +
+ + + + diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..9fd4feb --- /dev/null +++ b/web/style.css @@ -0,0 +1,121 @@ +:root { + --bg: #f6f6f7; + --fg: #1d1d1f; + --muted: #6e6e73; + --card: #ffffff; + --accent: #2563eb; + --border: #d2d2d7; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #111114; + --fg: #f2f2f5; + --muted: #9a9aa3; + --card: #1c1c21; + --accent: #5b8cff; + --border: #34343c; + } +} + +:root[data-theme="dark"] { + --bg: #111114; + --fg: #f2f2f5; + --muted: #9a9aa3; + --card: #1c1c21; + --accent: #5b8cff; + --border: #34343c; +} + +* { box-sizing: border-box; } + +body { + margin: 0; + padding: 0 16px 32px; + background: var(--bg); + color: var(--fg); + font: 16px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +header { + max-width: 560px; + margin: 0 auto; + padding: 16px 0 8px; +} + +h1 { margin: 0 0 12px; font-size: 1.5rem; } +h2 { font-size: 1.1rem; margin: 20px 0 8px; } + +nav { display: flex; gap: 8px; } + +main { + max-width: 560px; + margin: 0 auto; + background: var(--card); + border: 1px solid var(--border); + border-radius: 12px; + padding: 16px; +} + +section > * + * { margin-top: 12px; } + +label { + display: flex; + flex-direction: column; + gap: 6px; + font-weight: 500; +} + +output { font-weight: 400; color: var(--muted); } + +.row { display: flex; gap: 16px; flex-wrap: wrap; } +.row > label { flex: 1 1 140px; } + +select, input[type="text"], input:not([type]), input[type="password"] { + font: inherit; + padding: 8px 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--bg); + color: var(--fg); + width: 100%; +} + +input[type="color"] { + width: 100%; + height: 44px; + padding: 2px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--bg); +} + +input[type="range"] { width: 100%; accent-color: var(--accent); } + +button { + font: inherit; + padding: 8px 14px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--bg); + color: var(--fg); + cursor: pointer; +} + +button.tab.active, +button[type="submit"] { + background: var(--accent); + border-color: var(--accent); + color: #fff; +} + +.list { list-style: none; padding: 0; margin: 0; } +.list li + li { margin-top: 6px; } +button.net { width: 100%; text-align: left; } + +.muted { color: var(--muted); font-size: 0.9rem; } + +[hidden] { display: none !important; } + +form { display: flex; flex-direction: column; gap: 12px; } +form button { align-self: flex-start; }