Add ESP32-S3 VGA firmware with web interface

800x600 RGB332 VGA output for the XIAO ESP32S3 Plus, double buffered in
PSRAM. Includes content modes (test pattern, plasma, stars, clock,
Mandelbrot, message, images, Halloween, Haunting), a flash image gallery,
WiFi AP+STA web UI and OTA updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-29 22:05:32 +13:00
1 parent 961af1c486
commit c307f08de8
17 files changed
+7461

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
idf_component_register(SRCS "main.c" "display.c" "content.c" "gallery.c" "web.c"
EMBED_FILES "index.html"
REQUIRES esp_lcd esp_driver_gpio esp_wifi esp_netif esp_event esp_http_server
esp_timer esp_partition app_update nvs_flash json lwip)
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
typedef enum {
CONTENT_TEST,
CONTENT_PLASMA,
CONTENT_STARS,
CONTENT_CLOCK,
CONTENT_MANDEL,
CONTENT_MESSAGE,
CONTENT_IMAGE,
CONTENT_HALLOWEEN, // new modes go at the end: the index is saved in NVS
CONTENT_HAUNT,
CONTENT_COUNT,
} content_id_t;
#define MSG_MAX 256
#define MSG_SIZE_FILL 4 // as large as fits the screen
typedef struct {
char text[MSG_MAX + 1];
uint8_t fg, bg; // RGB332
uint8_t size; // 0 small .. 3 huge, or MSG_SIZE_FILL
} message_t;
// Slot number for an image held in RAM only (not saved to flash)
#define SLOT_LIVE (-1)
// What the screen should show. Changed by the web server, read by the
// display task.
typedef struct {
content_id_t content;
int slot;
message_t msg;
} show_t;
const char *content_key(content_id_t c);
const char *content_name(content_id_t c);
int content_from_key(const char *key); // -1 if unknown
// Thread-safe; any task may call these
void app_get_show(show_t *out);
void app_show(content_id_t c, int slot);
void app_set_message(const message_t *m);
void app_refresh(void); // redraw the current content (e.g. network info changed)
// Image shown for SLOT_LIVE; take the lock while reading or writing it
extern uint8_t *live_image;
void live_image_lock(void);
void live_image_unlock(void);
// Network status for on-screen info (implemented in web.c)
typedef struct {
char ap_ssid[33], ap_pass[65], ap_ip[16];
char sta_ssid[33], sta_ip[16];
bool sta_connected;
} net_info_t;
void net_get_info(net_info_t *out);
// Image gallery in the "gallery" flash partition (implemented in gallery.c)
#define GALLERY_NAME_MAX 31
void gallery_init(void);
int gallery_slots(void);
bool gallery_name(int slot, char *name); // false if the slot is empty
bool gallery_read(int slot, uint8_t *dst); // W*H bytes
bool gallery_write(int slot, const char *name, const uint8_t *data);
bool gallery_delete(int slot);
void web_start(void);
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "app.h"
// The display task calls enter() once when the content is selected (the whole
// canvas is then copied to both buffers), then every frame tick() followed by
// draw() on the buffer being prepared. Any of them may be NULL.
typedef struct {
void (*enter)(const show_t *s); // draw static parts into the canvas
void (*tick)(void); // update the canvas; mark changes with canvas_dirty()
bool (*draw)(uint8_t *fb, int buf); // draw into the frame buffer; true if it changed
} content_ops_t;
const content_ops_t *content_ops(content_id_t c);
+272
View File
@@ -0,0 +1,272 @@
// VGA output for XIAO ESP32S3 Plus, 8-bit RGB332, double buffered.
//
// Wiring (resistors go from the XIAO pin to the VGA pin):
// D0 GPIO1 B0 820R -> VGA 3 D5 GPIO6 R0 2k -> VGA 1
// D1 GPIO2 B1 430R -> VGA 3 D6 GPIO43 R1 1k -> VGA 1
// D2 GPIO3 G0 2k -> VGA 2 D7 GPIO44 R2 510R -> VGA 1
// D3 GPIO4 G1 1k -> VGA 2 D8 GPIO7 HSYNC 100R -> VGA 13
// D4 GPIO5 G2 510R -> VGA 2 D9 GPIO8 VSYNC 100R -> VGA 14
// GND -> VGA 5, 6, 7, 8, 10
#include <string.h>
#include <sys/param.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_heap_caps.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lcd_panel_rgb.h"
#include "esp_log.h"
#include "display.h"
#define PIN_HSYNC 7 // D8
#define PIN_VSYNC 8 // D9
static const char *TAG = "display";
static const int data_pins[8] = {1, 2, 3, 4, 5, 6, 43, 44}; // D0..D7 = bit 0..7
uint8_t *canvas;
static esp_lcd_panel_handle_t panel;
static uint8_t *fbs[2];
static TaskHandle_t waiter;
static volatile uint32_t frames_started;
static volatile int front; // buffer currently on screen
static uint8_t *volatile snapshot_dst;
static SemaphoreHandle_t snapshot_done;
// Changed canvas area not yet copied to each buffer; empty when x1 <= x0
typedef struct {
int x0, y0, x1, y1;
} box_t;
static box_t dirty[2];
// Called from the ISR when the driver starts scanning out a frame. Any buffer
// swap requested before this point has now taken effect.
static bool IRAM_ATTR on_frame_start(esp_lcd_panel_handle_t p, const esp_lcd_rgb_panel_event_data_t *edata, void *ctx)
{
BaseType_t woken = pdFALSE;
frames_started++;
if (waiter) {
vTaskNotifyGiveFromISR(waiter, &woken);
}
return woken == pdTRUE;
}
void display_init(void)
{
esp_lcd_rgb_panel_config_t cfg = {
// Integer division of 240 MHz. A fractional divider (e.g. for
// 25.175 MHz) jitters, which blurs vertical edges on LCD monitors.
.clk_src = LCD_CLK_SRC_PLL240M,
.timings = {
.pclk_hz = PCLK_HZ,
.h_res = W,
.v_res = H,
.hsync_pulse_width = H_SYNC,
.hsync_back_porch = H_BACK,
.hsync_front_porch = H_FRONT,
.vsync_pulse_width = V_SYNC,
.vsync_back_porch = V_BACK,
.vsync_front_porch = V_FRONT,
// Active-high syncs idle low; active-low syncs idle high
.flags.hsync_idle_low = SYNC_POS,
.flags.vsync_idle_low = SYNC_POS,
},
.data_width = 8,
.bits_per_pixel = 8,
.num_fbs = 2,
.bounce_buffer_size_px = W * 10,
.dma_burst_size = 64,
.hsync_gpio_num = PIN_HSYNC,
.vsync_gpio_num = PIN_VSYNC,
.de_gpio_num = -1,
.pclk_gpio_num = -1,
.disp_gpio_num = -1,
.flags.fb_in_psram = 1,
};
for (int i = 0; i < 8; i++) {
cfg.data_gpio_nums[i] = data_pins[i];
}
waiter = xTaskGetCurrentTaskHandle();
ESP_ERROR_CHECK(esp_lcd_new_rgb_panel(&cfg, &panel));
esp_lcd_rgb_panel_event_callbacks_t cbs = {
.on_frame_buf_complete = on_frame_start,
};
ESP_ERROR_CHECK(esp_lcd_rgb_panel_register_event_callbacks(panel, &cbs, NULL));
ESP_ERROR_CHECK(esp_lcd_panel_reset(panel));
ESP_ERROR_CHECK(esp_lcd_panel_init(panel));
ESP_ERROR_CHECK(esp_lcd_rgb_panel_get_frame_buffer(panel, 2, (void **)&fbs[0], (void **)&fbs[1]));
// Strongest drive so the pin's own resistance doesn't skew the DAC levels
for (int i = 0; i < 8; i++) {
gpio_set_drive_capability(data_pins[i], GPIO_DRIVE_CAP_3);
}
snapshot_done = xSemaphoreCreateBinary();
canvas = heap_caps_calloc(1, W * H, MALLOC_CAP_SPIRAM);
assert(canvas);
ESP_LOGI(TAG, "%dx%d @ %.1f Hz, double buffered", W, H, REFRESH_HZ);
}
uint8_t *display_fb(int buf)
{
return fbs[buf];
}
// Clip a rectangle to the screen; returns false if nothing is left
static bool clip(int *x, int *y, int *w, int *h)
{
if (*x < 0) {
*w += *x;
*x = 0;
}
if (*y < 0) {
*h += *y;
*y = 0;
}
if (*x + *w > W) {
*w = W - *x;
}
if (*y + *h > H) {
*h = H - *y;
}
return *w > 0 && *h > 0;
}
void canvas_dirty(int x, int y, int w, int h)
{
if (!clip(&x, &y, &w, &h)) {
return;
}
for (int b = 0; b < 2; b++) {
box_t *d = &dirty[b];
if (d->x1 <= d->x0) {
*d = (box_t){x, y, x + w, y + h};
} else {
d->x0 = MIN(d->x0, x);
d->y0 = MIN(d->y0, y);
d->x1 = MAX(d->x1, x + w);
d->y1 = MAX(d->y1, y + h);
}
}
}
void canvas_dirty_all(void)
{
canvas_dirty(0, 0, W, H);
}
bool display_sync(int buf)
{
box_t *d = &dirty[buf];
if (d->x1 <= d->x0) {
return false;
}
if (d->x0 == 0 && d->x1 == W) {
memcpy(fbs[buf] + d->y0 * W, canvas + d->y0 * W, (d->y1 - d->y0) * W);
} else {
gfx_restore(fbs[buf], d->x0, d->y0, d->x1 - d->x0, d->y1 - d->y0);
}
d->x1 = d->x0;
return true;
}
static void wait_frame(void)
{
uint32_t n = frames_started;
while (frames_started == n) {
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(100));
}
}
// Runs in the display task between frames, when the front buffer can't change
static void serve_snapshot(void)
{
if (snapshot_dst) {
memcpy(snapshot_dst, fbs[front], W * H);
snapshot_dst = NULL;
xSemaphoreGive(snapshot_done);
}
}
void display_wait_frame(void)
{
wait_frame();
serve_snapshot();
}
void display_present(int buf)
{
// Ask the driver to show this buffer from the next frame, then wait for
// that frame to start before the caller draws into the other one
esp_lcd_panel_draw_bitmap(panel, 0, 0, W, H, fbs[buf]);
wait_frame();
front = buf;
serve_snapshot();
}
bool display_snapshot(uint8_t *dst)
{
if (!snapshot_done) {
return false;
}
xSemaphoreTake(snapshot_done, 0); // clear any stale give
snapshot_dst = dst;
if (xSemaphoreTake(snapshot_done, pdMS_TO_TICKS(1000)) != pdTRUE) {
snapshot_dst = NULL;
return false;
}
return true;
}
void gfx_fill(uint8_t *s, int x, int y, int w, int h, uint8_t c)
{
if (!clip(&x, &y, &w, &h)) {
return;
}
for (int j = y; j < y + h; j++) {
memset(s + j * W + x, c, w);
}
}
void gfx_restore(uint8_t *dst, int x, int y, int w, int h)
{
if (!clip(&x, &y, &w, &h)) {
return;
}
for (int j = y; j < y + h; j++) {
memcpy(dst + j * W + x, canvas + j * W + x, w);
}
}
int gfx_text_width(const font_t *f, int scale, const char *str)
{
return strlen(str) * f->w * scale;
}
int gfx_text(uint8_t *s, const font_t *f, int scale, int x, int y, const char *str, uint8_t fg, int bg)
{
for (; *str; str++, x += f->w * scale) {
int ch = (uint8_t)*str;
if (ch < FONT_FIRST || ch > FONT_LAST) {
ch = '?';
}
if (bg >= 0) {
gfx_fill(s, x, y, f->w * scale, f->h * scale, bg);
}
const uint8_t *g = f->bits + (ch - FONT_FIRST) * f->h * f->stride;
for (int row = 0; row < f->h; row++, g += f->stride) {
for (int col = 0; col < f->w; col++) {
if (g[col >> 3] & (0x80 >> (col & 7))) {
gfx_fill(s, x + col * scale, y + row * scale, scale, scale, fg);
}
}
}
}
return x;
}
+85
View File
@@ -0,0 +1,85 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "font_data.h"
// Pick one. Both pixel clocks divide 240 MHz exactly, so there's no jitter.
#define MODE_800x600 1
#if MODE_800x600
// VESA 800x600@60: 40 MHz, 37.9 kHz, 60.3 Hz, positive syncs
#define W 800
#define H 600
#define PCLK_HZ 40000000
#define H_FRONT 40
#define H_SYNC 128
#define H_BACK 88
#define V_FRONT 1
#define V_SYNC 4
#define V_BACK 23
#define SYNC_POS 1
#else
// 640x480 at 24 MHz (VGA timing, slightly slow): 30.0 kHz, 57.1 Hz, negative syncs
#define W 640
#define H 480
#define PCLK_HZ 24000000
#define H_FRONT 16
#define H_SYNC 96
#define H_BACK 48
#define V_FRONT 10
#define V_SYNC 2
#define V_BACK 33
#define SYNC_POS 0
#endif
#define REFRESH_HZ ((double)PCLK_HZ / ((W + H_FRONT + H_SYNC + H_BACK) * (H + V_FRONT + V_SYNC + V_BACK)))
// r, g: 0-7, b: 0-3
static inline uint8_t rgb332(int r, int g, int b)
{
return (r << 5) | (g << 2) | b;
}
// From 8-bit-per-channel colour, rounded to the nearest DAC level
static inline uint8_t rgb888_to_332(uint8_t r, uint8_t g, uint8_t b)
{
return rgb332((r * 7 + 127) / 255, (g * 7 + 127) / 255, (b * 3 + 127) / 255);
}
// Static content is drawn into the canvas; the display loop copies changed
// areas into each frame buffer. Animated content draws into the frame buffer
// directly and uses the canvas as the background to erase with.
extern uint8_t *canvas;
// Must be called from the task that will drive the display; the LCD
// interrupt runs on that task's core.
void display_init(void);
uint8_t *display_fb(int buf);
// Mark part of the canvas as changed, so both frame buffers pick it up
void canvas_dirty(int x, int y, int w, int h);
void canvas_dirty_all(void);
// Copy any changed canvas areas into frame buffer `buf`. Returns true if
// anything was copied.
bool display_sync(int buf);
// Show frame buffer `buf` from the next frame, and return once that frame
// has started (the other buffer is then free to draw into).
void display_present(int buf);
// Wait for the next frame to start without changing buffers
void display_wait_frame(void);
// Copy what's on screen into dst (W*H bytes). Any task may call this; the
// display task does the copy between frames. False if it isn't running.
bool display_snapshot(uint8_t *dst);
// Drawing on any W x H surface (canvas or frame buffer); all calls clip
void gfx_fill(uint8_t *s, int x, int y, int w, int h, uint8_t c);
void gfx_restore(uint8_t *dst, int x, int y, int w, int h); // copy from canvas
// bg < 0 draws transparent. Returns the x just past the text.
int gfx_text(uint8_t *s, const font_t *f, int scale, int x, int y, const char *str, uint8_t fg, int bg);
int gfx_text_width(const font_t *f, int scale, const char *str);
File diff suppressed because it is too large. Load diff
+97
View File
@@ -0,0 +1,97 @@
// Image gallery: raw W x H RGB332 images in fixed slots of the "gallery"
// partition. Each slot is a 4 KB header sector followed by the pixels.
#include <string.h>
#include "esp_log.h"
#include "esp_partition.h"
#include "app.h"
#include "display.h"
#define SLOT_SIZE 0x80000
#define HEADER_SIZE 0x1000
#define MAGIC 0x56474131 // "VGA1"
_Static_assert(HEADER_SIZE + W * H <= SLOT_SIZE, "image doesn't fit in a gallery slot");
typedef struct {
uint32_t magic;
uint16_t w, h;
char name[GALLERY_NAME_MAX + 1];
} header_t;
static const char *TAG = "gallery";
static const esp_partition_t *part;
void gallery_init(void)
{
part = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, 0x40, "gallery");
if (part) {
ESP_LOGI(TAG, "%d slots of %dx%d", gallery_slots(), W, H);
} else {
ESP_LOGE(TAG, "no gallery partition");
}
}
int gallery_slots(void)
{
return part ? part->size / SLOT_SIZE : 0;
}
static bool read_header(int slot, header_t *hdr)
{
if (slot < 0 || slot >= gallery_slots()) {
return false;
}
if (esp_partition_read(part, slot * SLOT_SIZE, hdr, sizeof(*hdr)) != ESP_OK) {
return false;
}
// An image saved in the other video mode won't fit, so treat it as empty
return hdr->magic == MAGIC && hdr->w == W && hdr->h == H;
}
bool gallery_name(int slot, char *name)
{
header_t hdr;
if (!read_header(slot, &hdr)) {
return false;
}
hdr.name[GALLERY_NAME_MAX] = 0;
strcpy(name, hdr.name);
return true;
}
bool gallery_read(int slot, uint8_t *dst)
{
header_t hdr;
if (!read_header(slot, &hdr)) {
return false;
}
return esp_partition_read(part, slot * SLOT_SIZE + HEADER_SIZE, dst, W * H) == ESP_OK;
}
bool gallery_write(int slot, const char *name, const uint8_t *data)
{
if (slot < 0 || slot >= gallery_slots()) {
return false;
}
size_t base = slot * SLOT_SIZE;
size_t used = (HEADER_SIZE + W * H + 0xfff) & ~0xfff;
if (esp_partition_erase_range(part, base, used) != ESP_OK) {
return false;
}
// Pixels first, header last, so a half-written slot reads as empty
if (esp_partition_write(part, base + HEADER_SIZE, data, W * H) != ESP_OK) {
return false;
}
header_t hdr = {.magic = MAGIC, .w = W, .h = H};
strlcpy(hdr.name, name, sizeof(hdr.name));
return esp_partition_write(part, base, &hdr, sizeof(hdr)) == ESP_OK;
}
bool gallery_delete(int slot)
{
if (slot < 0 || slot >= gallery_slots()) {
return false;
}
return esp_partition_erase_range(part, slot * SLOT_SIZE, HEADER_SIZE) == ESP_OK;
}
+386
View File
@@ -0,0 +1,386 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 VGA</title>
<style>
:root {
--bg: #f4f5f7; --card: #fff; --text: #1d2026; --muted: #667085; --line: #e1e4ea;
--accent: #2563eb; --accent-text: #fff; --danger: #c0352b; --input: #fff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111318; --card: #1b1e25; --text: #e6e8ec; --muted: #9aa1ad; --line: #2c313b;
--accent: #5b8cff; --accent-text: #0b1020; --danger: #ff6b5e; --input: #14171d;
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text);
font: 15px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
header { padding: 18px 16px 6px; max-width: 760px; margin: 0 auto; }
h1 { font-size: 22px; margin: 0; }
#status { color: var(--muted); font-size: 13px; margin-top: 2px; }
main { max-width: 760px; margin: 0 auto; padding: 8px 16px 40px; display: grid; gap: 14px; }
section { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 16px; }
h2 { font-size: 16px; margin: 0 0 12px; }
label { display: block; font-size: 13px; color: var(--muted); margin: 10px 0 4px; }
input[type=text], input[type=password], textarea, select {
width: 100%; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px;
background: var(--input); color: var(--text); font: inherit; }
textarea { min-height: 80px; resize: vertical; }
input[type=color] { width: 56px; height: 36px; padding: 2px; border: 1px solid var(--line);
border-radius: 8px; background: var(--input); }
input[type=file] { font: inherit; color: var(--muted); max-width: 100%; }
button { font: inherit; padding: 8px 14px; border-radius: 8px; border: 1px solid var(--line);
background: var(--input); color: var(--text); cursor: pointer; }
button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
button.danger { color: var(--danger); }
button:disabled { opacity: .5; cursor: default; }
.row { display: flex; gap: 10px; flex-wrap: wrap; align-items: end; }
.row > .grow { flex: 1 1 160px; }
.actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 12px; }
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 8px; }
.tiles button { padding: 14px 8px; }
.tiles button.on { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
canvas#preview, canvas.shot { width: 100%; height: auto; border-radius: 8px; border: 1px solid var(--line);
background: #000; image-rendering: pixelated; margin-top: 12px; display: none; }
.check { display: flex; align-items: center; gap: 6px; color: var(--text); font-size: 14px; margin: 0; }
.gallery { display: grid; gap: 6px; }
.slot { display: flex; align-items: center; gap: 8px; padding: 6px 0; border-top: 1px solid var(--line); }
.slot:first-child { border-top: 0; }
.slot .n { width: 26px; color: var(--muted); font-variant-numeric: tabular-nums; }
.slot .name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.slot .name.empty { color: var(--muted); }
.slot.on .name { font-weight: 600; color: var(--accent); }
.note { color: var(--muted); font-size: 13px; margin: 8px 0 0; }
#toast { position: fixed; left: 50%; bottom: 20px; transform: translateX(-50%); background: var(--text);
color: var(--bg); padding: 10px 16px; border-radius: 8px; font-size: 14px; opacity: 0;
transition: opacity .2s; pointer-events: none; max-width: calc(100% - 32px); }
#toast.show { opacity: 1; }
</style>
</head>
<body>
<header>
<h1>ESP32 VGA</h1>
<div id="status">Connecting…</div>
</header>
<main>
<section>
<h2>Show</h2>
<div class="tiles" id="tiles"></div>
<div class="actions"><button id="shot">Preview screen</button></div>
<canvas id="screen" class="shot"></canvas>
</section>
<section>
<h2>Message</h2>
<textarea id="msgText" maxlength="256"></textarea>
<div class="row">
<div><label for="msgFg">Text</label><input type="color" id="msgFg"></div>
<div><label for="msgBg">Background</label><input type="color" id="msgBg"></div>
<div class="grow"><label for="msgSize">Size</label>
<select id="msgSize">
<option value="0">Small</option><option value="1">Medium</option>
<option value="2">Large</option><option value="3">Huge</option>
<option value="4">Fill screen</option>
</select></div>
</div>
<div class="actions"><button class="primary" id="msgShow">Show message</button></div>
</section>
<section>
<h2>Image</h2>
<input type="file" id="imgFile" accept="image/*">
<div class="row">
<div class="grow"><label for="imgFit">Fit</label>
<select id="imgFit">
<option value="contain">Fit inside (black bars)</option>
<option value="cover">Fill screen (crop)</option>
<option value="stretch">Stretch</option>
</select></div>
<div><label>&nbsp;</label><label class="check"><input type="checkbox" id="imgDither" checked> Dither</label></div>
</div>
<canvas id="preview"></canvas>
<div class="row">
<div class="grow"><label for="imgName">Name</label><input type="text" id="imgName" maxlength="31"></div>
<div class="grow"><label for="imgSlot">Gallery slot</label><select id="imgSlot"></select></div>
</div>
<div class="actions">
<button class="primary" id="imgShow" disabled>Show now</button>
<button id="imgSave" disabled>Save to gallery</button>
</div>
<p class="note" id="imgNote">The browser converts the picture to the display's 256 colours before sending it.</p>
</section>
<section>
<h2>Gallery</h2>
<div class="gallery" id="gallery"></div>
</section>
<section>
<h2>Settings</h2>
<label for="ssid">Home WiFi name</label>
<input type="text" id="ssid" autocomplete="off">
<label for="pass">Password</label>
<input type="password" id="pass" autocomplete="off">
<div class="actions"><button id="wifiSave">Save WiFi</button></div>
<p class="note" id="wifiNote"></p>
<label for="tz">Time zone</label>
<div class="row">
<div class="grow"><select id="tzPreset">
<option value="NZST-12NZDT,M9.5.0,M4.1.0/3">New Zealand</option>
<option value="AEST-10AEDT,M10.1.0,M4.1.0/3">Sydney / Melbourne</option>
<option value="AEST-10">Brisbane</option>
<option value="AWST-8">Perth</option>
<option value="GMT0BST,M3.5.0/1,M10.5.0">UK</option>
<option value="CET-1CEST,M3.5.0,M10.5.0/3">Central Europe</option>
<option value="EST5EDT,M3.2.0,M11.1.0">US Eastern</option>
<option value="PST8PDT,M3.2.0,M11.1.0">US Pacific</option>
<option value="UTC0">UTC</option>
<option value="">Custom…</option>
</select></div>
<div class="grow"><input type="text" id="tz" placeholder="POSIX TZ string"></div>
</div>
<div class="actions"><button id="timeSave">Save time zone and sync clock</button></div>
<label for="fwFile">Firmware update (.bin)</label>
<input type="file" id="fwFile" accept=".bin">
<div class="actions"><button id="fwUpload" disabled>Upload and restart</button></div>
<p class="note" id="fwNote"></p>
</section>
</main>
<div id="toast"></div>
<script>
const $ = id => document.getElementById(id);
let state = null, converted = null, sourceImage = null;
function toast(msg) {
const t = $('toast');
t.textContent = msg;
t.classList.add('show');
clearTimeout(toast.timer);
toast.timer = setTimeout(() => t.classList.remove('show'), 2500);
}
async function api(path, opts = {}) {
const r = await fetch(path, opts);
if (!r.ok) throw new Error(await r.text() || r.statusText);
return r.headers.get('content-type')?.includes('json') ? r.json() : r.text();
}
const post = (path, body) => api(path, {
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)
});
async function run(btn, fn, done) {
if (btn) btn.disabled = true;
try { await fn(); if (done) toast(done); await refresh(); }
catch (e) { toast('Error: ' + e.message); }
finally { if (btn) btn.disabled = false; }
}
async function refresh() {
state = await api('/api/state');
render();
}
function render() {
const s = state, n = s.net;
let net = `${s.w}×${s.h} @ ${s.hz.toFixed(1)} Hz`;
net += n.sta_connected ? ` · on ${n.sta_ssid} at ${n.sta_ip}` : n.sta_ssid ? ` · connecting to ${n.sta_ssid}…` : '';
$('status').textContent = net;
const tiles = $('tiles');
tiles.replaceChildren(...s.contents.filter(c => c.key !== 'image').map(c => {
const b = document.createElement('button');
b.textContent = c.name;
b.className = c.key === s.content ? 'on' : '';
b.onclick = () => run(null, () => post('/api/show', {content: c.key}));
return b;
}));
if (!render.msgLoaded) {
$('msgText').value = s.msg.text;
$('msgFg').value = s.msg.fg;
$('msgBg').value = s.msg.bg;
$('msgSize').value = s.msg.size;
$('ssid').value = n.sta_ssid;
setTz(s.tz);
render.msgLoaded = true;
}
const sel = $('imgSlot'), prev = sel.value;
sel.replaceChildren(...s.slots.map((name, i) => {
const o = document.createElement('option');
o.value = i;
o.textContent = `${i + 1}: ${name ?? '(empty)'}`;
return o;
}));
sel.value = prev !== '' ? prev : Math.max(0, s.slots.indexOf(null));
const g = $('gallery');
g.replaceChildren(...s.slots.map((name, i) => {
const row = document.createElement('div');
const showing = s.content === 'image' && s.slot === i;
row.className = 'slot' + (showing ? ' on' : '');
row.innerHTML = `<span class="n">${i + 1}</span><span class="name"></span>`;
const label = row.querySelector('.name');
label.textContent = name ?? 'empty';
if (name === null) label.classList.add('empty');
else {
const show = document.createElement('button');
show.textContent = 'Show';
show.onclick = () => run(show, () => post('/api/show', {content: 'image', slot: i}));
const del = document.createElement('button');
del.textContent = 'Delete';
del.className = 'danger';
del.onclick = () => confirm(`Delete "${name}"?`) &&
run(del, () => api('/api/image?slot=' + i, {method: 'DELETE'}), 'Deleted');
row.append(show, del);
}
return row;
}));
$('wifiNote').textContent = n.sta_connected
? `Connected. You can also reach this page at http://${n.sta_ip}`
: `The board's own network "${n.ap_ssid}" (http://${n.ap_ip}) always stays on.`;
$('fwNote').textContent = `Running ${s.version} from ${s.partition}, built ${s.built}.`;
}
// Screenshot of what the VGA output is showing
$('shot').onclick = e => run(e.target, async () => {
const r = await fetch('/api/screenshot');
if (!r.ok) throw new Error(r.statusText);
const px = new Uint8Array(await r.arrayBuffer()), W = state.w, H = state.h;
const c = $('screen');
c.width = W; c.height = H;
c.style.display = 'block';
const ctx = c.getContext('2d'), id = ctx.createImageData(W, H);
for (let i = 0; i < W * H; i++) {
const v = px[i];
id.data[i * 4] = (v >> 5) * 255 / 7;
id.data[i * 4 + 1] = ((v >> 2) & 7) * 255 / 7;
id.data[i * 4 + 2] = (v & 3) * 255 / 3;
id.data[i * 4 + 3] = 255;
}
ctx.putImageData(id, 0, 0);
});
// Message
$('msgShow').onclick = e => run(e.target, () => post('/api/message', {
text: $('msgText').value, fg: $('msgFg').value, bg: $('msgBg').value, size: +$('msgSize').value
}));
// Image conversion: scale to the display, then quantise to RGB332
// (8 red, 8 green, 4 blue levels), optionally with Floyd-Steinberg dithering.
function convert() {
if (!sourceImage) return;
const W = state.w, H = state.h, img = sourceImage;
const c = $('preview');
c.width = W; c.height = H;
c.style.display = 'block';
const ctx = c.getContext('2d', {willReadFrequently: true});
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, W, H);
const fit = $('imgFit').value, iw = img.naturalWidth, ih = img.naturalHeight;
let dw = W, dh = H;
if (fit !== 'stretch') {
const k = (fit === 'cover' ? Math.max : Math.min)(W / iw, H / ih);
dw = iw * k; dh = ih * k;
}
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, (W - dw) / 2, (H - dh) / 2, dw, dh);
const id = ctx.getImageData(0, 0, W, H), px = id.data;
const buf = new Float32Array(W * H * 3);
for (let i = 0, j = 0; i < px.length; i += 4, j += 3) {
buf[j] = px[i]; buf[j + 1] = px[i + 1]; buf[j + 2] = px[i + 2];
}
const levels = [7, 7, 3], dither = $('imgDither').checked;
const out = new Uint8Array(W * H);
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
const p = y * W + x, q = [0, 0, 0];
for (let ch = 0; ch < 3; ch++) {
const old = Math.min(255, Math.max(0, buf[p * 3 + ch]));
const L = levels[ch], v = Math.round(old * L / 255), val = v * 255 / L;
q[ch] = v;
px[p * 4 + ch] = val;
if (dither) {
const err = old - val;
if (x + 1 < W) buf[(p + 1) * 3 + ch] += err * 7 / 16;
if (y + 1 < H) {
if (x > 0) buf[(p + W - 1) * 3 + ch] += err * 3 / 16;
buf[(p + W) * 3 + ch] += err * 5 / 16;
if (x + 1 < W) buf[(p + W + 1) * 3 + ch] += err / 16;
}
}
}
out[p] = (q[0] << 5) | (q[1] << 2) | q[2];
}
}
ctx.putImageData(id, 0, 0);
converted = out;
$('imgShow').disabled = $('imgSave').disabled = false;
}
$('imgFile').onchange = e => {
const f = e.target.files[0];
if (!f) return;
const img = new Image();
img.onload = () => { sourceImage = img; convert(); URL.revokeObjectURL(img.src); };
img.onerror = () => toast('Could not read that image');
img.src = URL.createObjectURL(f);
$('imgName').value = f.name.replace(/\.[^.]+$/, '').slice(0, 31);
};
$('imgFit').onchange = $('imgDither').onchange = convert;
function upload(btn, slot) {
const name = encodeURIComponent($('imgName').value || 'Image');
return run(btn, () => api(`/api/image?slot=${slot}&name=${name}`, {
method: 'POST', headers: {'Content-Type': 'application/octet-stream'}, body: converted
}), slot < 0 ? 'Showing' : 'Saved to slot ' + (slot + 1));
}
$('imgShow').onclick = e => upload(e.target, -1);
$('imgSave').onclick = e => {
const slot = +$('imgSlot').value;
if (state.slots[slot] !== null && !confirm(`Replace "${state.slots[slot]}" in slot ${slot + 1}?`)) return;
upload(e.target, slot);
};
// Settings
$('wifiSave').onclick = e => run(e.target, () => post('/api/wifi', {ssid: $('ssid').value, pass: $('pass').value}),
$('ssid').value ? 'Saved, connecting…' : 'Home WiFi removed');
function setTz(tz) {
const preset = [...$('tzPreset').options].find(o => o.value === tz);
$('tzPreset').value = preset ? tz : '';
$('tz').value = tz;
}
$('tzPreset').onchange = () => { if ($('tzPreset').value) $('tz').value = $('tzPreset').value; };
$('tz').oninput = () => setTz($('tz').value);
const syncTime = tz => post('/api/time', {epoch: Math.round(Date.now() / 1000), ...(tz ? {tz} : {})});
$('timeSave').onclick = e => run(e.target, () => syncTime($('tz').value), 'Clock updated');
$('fwFile').onchange = e => $('fwUpload').disabled = !e.target.files[0];
$('fwUpload').onclick = e => {
const f = $('fwFile').files[0];
if (!f || !confirm(`Install ${f.name}? The board will restart.`)) return;
$('fwNote').textContent = 'Uploading…';
run(e.target, async () => {
await api('/api/ota', {method: 'POST', body: f});
$('fwNote').textContent = 'Installed. Restarting…';
setTimeout(() => location.reload(), 8000);
});
};
// Give the board the time straight away, so the clock works without internet
syncTime().catch(() => {});
refresh().catch(e => $('status').textContent = 'Error: ' + e.message);
setInterval(() => document.hidden || refresh().catch(() => {}), 5000);
</script>
</body>
</html>
+181
View File
@@ -0,0 +1,181 @@
// VGA display with web interface for XIAO ESP32S3 Plus.
// Display and content run on core 1; WiFi and the web server on core 0.
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "app.h"
#include "content.h"
#include "display.h"
static const char *TAG = "app";
uint8_t *live_image;
static SemaphoreHandle_t live_lock;
static SemaphoreHandle_t show_lock;
static show_t show;
static uint32_t show_seq; // bumped on every change, so the display task notices
void live_image_lock(void)
{
xSemaphoreTake(live_lock, portMAX_DELAY);
}
void live_image_unlock(void)
{
xSemaphoreGive(live_lock);
}
void app_get_show(show_t *out)
{
xSemaphoreTake(show_lock, portMAX_DELAY);
*out = show;
xSemaphoreGive(show_lock);
}
static uint32_t get_seq(void)
{
xSemaphoreTake(show_lock, portMAX_DELAY);
uint32_t s = show_seq;
xSemaphoreGive(show_lock);
return s;
}
static void save_show(void)
{
nvs_handle_t h;
if (nvs_open("vga", NVS_READWRITE, &h) != ESP_OK) {
return;
}
nvs_set_u8(h, "content", show.content);
nvs_set_i8(h, "slot", show.slot);
nvs_set_str(h, "msg_text", show.msg.text);
nvs_set_u8(h, "msg_fg", show.msg.fg);
nvs_set_u8(h, "msg_bg", show.msg.bg);
nvs_set_u8(h, "msg_size", show.msg.size);
nvs_commit(h);
nvs_close(h);
}
static void load_show(void)
{
show = (show_t){
.content = CONTENT_TEST,
.slot = 0,
.msg = {.text = "Hello from the ESP32-S3!", .fg = rgb332(7, 7, 3), .bg = rgb332(0, 0, 2), .size = MSG_SIZE_FILL},
};
nvs_handle_t h;
if (nvs_open("vga", NVS_READONLY, &h) != ESP_OK) {
return;
}
uint8_t u;
int8_t i;
size_t len = sizeof(show.msg.text);
if (nvs_get_u8(h, "content", &u) == ESP_OK && u < CONTENT_COUNT) {
show.content = u;
}
if (nvs_get_i8(h, "slot", &i) == ESP_OK) {
show.slot = i;
}
nvs_get_str(h, "msg_text", show.msg.text, &len);
nvs_get_u8(h, "msg_fg", &show.msg.fg);
nvs_get_u8(h, "msg_bg", &show.msg.bg);
nvs_get_u8(h, "msg_size", &show.msg.size);
nvs_close(h);
// The live image is lost on reboot
if (show.content == CONTENT_IMAGE && show.slot == SLOT_LIVE) {
show.content = CONTENT_TEST;
}
}
void app_show(content_id_t c, int slot)
{
xSemaphoreTake(show_lock, portMAX_DELAY);
show.content = c;
show.slot = slot;
show_seq++;
save_show();
xSemaphoreGive(show_lock);
ESP_LOGI(TAG, "show %s (slot %d)", content_key(c), slot);
}
void app_set_message(const message_t *m)
{
xSemaphoreTake(show_lock, portMAX_DELAY);
show.msg = *m;
show.content = CONTENT_MESSAGE;
show_seq++;
save_show();
xSemaphoreGive(show_lock);
}
void app_refresh(void)
{
xSemaphoreTake(show_lock, portMAX_DELAY);
show_seq++;
xSemaphoreGive(show_lock);
}
static void display_task(void *arg)
{
display_init();
uint32_t seq = get_seq() - 1; // force the first enter()
const content_ops_t *c = NULL;
show_t cur;
int back = 1;
while (1) {
uint32_t now = get_seq();
if (now != seq) {
seq = now;
app_get_show(&cur);
c = content_ops(cur.content);
if (c->enter) {
c->enter(&cur);
}
canvas_dirty_all();
}
if (c->tick) {
c->tick();
}
uint8_t *fb = display_fb(back);
bool changed = display_sync(back);
if (c->draw) {
changed |= c->draw(fb, back);
}
if (changed) {
display_present(back);
back ^= 1;
} else {
display_wait_frame();
}
}
}
void app_main(void)
{
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);
show_lock = xSemaphoreCreateMutex();
live_lock = xSemaphoreCreateMutex();
load_show();
gallery_init();
xTaskCreatePinnedToCore(display_task, "display", 8192, NULL, 10, NULL, 1);
web_start();
}
+599
View File
@@ -0,0 +1,599 @@
// WiFi (own access point + optional home network), clock sync, and the web
// interface / JSON API.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/time.h>
#include <time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "cJSON.h"
#include "esp_app_desc.h"
#include "esp_event.h"
#include "esp_heap_caps.h"
#include "esp_http_server.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_netif_sntp.h"
#include "esp_ota_ops.h"
#include "esp_timer.h"
#include "esp_wifi.h"
#include "nvs.h"
#include "app.h"
#include "display.h"
#define AP_SSID "ESP32-VGA"
#define AP_PASS "esp32vga"
#define DEFAULT_TZ "NZST-12NZDT,M9.5.0,M4.1.0/3"
static const char *TAG = "web";
extern const char index_html_start[] asm("_binary_index_html_start");
extern const char index_html_end[] asm("_binary_index_html_end");
static SemaphoreHandle_t net_lock;
static net_info_t net;
static char tz[64] = DEFAULT_TZ;
static esp_netif_t *sta_netif;
static esp_timer_handle_t reconnect_timer;
static bool sntp_started;
static uint8_t *upload_buf;
// ---------------------------------------------------------------------------
// Settings
static void nvs_get_string(const char *key, char *out, size_t size)
{
nvs_handle_t h;
if (nvs_open("vga", NVS_READONLY, &h) == ESP_OK) {
nvs_get_str(h, key, out, &size);
nvs_close(h);
}
}
static void nvs_set_string(const char *key, const char *val)
{
nvs_handle_t h;
if (nvs_open("vga", NVS_READWRITE, &h) == ESP_OK) {
nvs_set_str(h, key, val);
nvs_commit(h);
nvs_close(h);
}
}
static void apply_tz(void)
{
setenv("TZ", tz, 1);
tzset();
}
// ---------------------------------------------------------------------------
// WiFi
void net_get_info(net_info_t *out)
{
if (!net_lock) {
// WiFi isn't up yet; web_start() redraws once it is
memset(out, 0, sizeof(*out));
return;
}
xSemaphoreTake(net_lock, portMAX_DELAY);
*out = net;
xSemaphoreGive(net_lock);
}
static void reconnect(void *arg)
{
esp_wifi_connect();
}
static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) {
if (net.sta_ssid[0]) {
esp_wifi_connect();
}
} else if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
bool was = net.sta_connected;
xSemaphoreTake(net_lock, portMAX_DELAY);
net.sta_connected = false;
net.sta_ip[0] = 0;
bool have_ssid = net.sta_ssid[0];
xSemaphoreGive(net_lock);
if (was) {
app_refresh();
}
// Retry slowly: each attempt scans, which briefly disturbs the access point
if (have_ssid && !esp_timer_is_active(reconnect_timer)) {
esp_timer_start_once(reconnect_timer, 10 * 1000000);
}
} else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t *e = data;
xSemaphoreTake(net_lock, portMAX_DELAY);
net.sta_connected = true;
snprintf(net.sta_ip, sizeof(net.sta_ip), IPSTR, IP2STR(&e->ip_info.ip));
xSemaphoreGive(net_lock);
ESP_LOGI(TAG, "home WiFi connected: http://%s", net.sta_ip);
if (!sntp_started) {
esp_sntp_config_t cfg = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
esp_netif_sntp_init(&cfg);
sntp_started = true;
}
app_refresh();
}
}
static void set_sta(const char *ssid, const char *pass)
{
wifi_config_t sta = {0};
strlcpy((char *)sta.sta.ssid, ssid, sizeof(sta.sta.ssid));
strlcpy((char *)sta.sta.password, pass, sizeof(sta.sta.password));
sta.sta.threshold.authmode = pass[0] ? WIFI_AUTH_WPA_PSK : WIFI_AUTH_OPEN;
esp_wifi_set_config(WIFI_IF_STA, &sta);
}
static void wifi_init(void)
{
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_ap();
sta_netif = esp_netif_create_default_wifi_sta();
wifi_init_config_t init = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&init));
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, on_wifi_event, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_wifi_event, NULL));
const esp_timer_create_args_t targs = {.callback = reconnect, .name = "reconnect"};
esp_timer_create(&targs, &reconnect_timer);
wifi_config_t ap = {
.ap = {
.ssid = AP_SSID,
.ssid_len = strlen(AP_SSID),
.password = AP_PASS,
.channel = 6,
.max_connection = 4,
.authmode = WIFI_AUTH_WPA2_PSK,
},
};
char pass[65] = "";
nvs_get_string("sta_ssid", net.sta_ssid, sizeof(net.sta_ssid));
nvs_get_string("sta_pass", pass, sizeof(pass));
strcpy(net.ap_ssid, AP_SSID);
strcpy(net.ap_pass, AP_PASS);
strcpy(net.ap_ip, "192.168.4.1");
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap));
set_sta(net.sta_ssid, pass);
// net is complete; from here on the event handler and display share it
net_lock = xSemaphoreCreateMutex();
ESP_ERROR_CHECK(esp_wifi_start());
// Modem sleep adds up to ~200 ms latency and slows uploads; this is mains powered
esp_wifi_set_ps(WIFI_PS_NONE);
ESP_LOGI(TAG, "access point \"%s\" up: http://%s", AP_SSID, net.ap_ip);
}
// ---------------------------------------------------------------------------
// HTTP helpers
static esp_err_t send_json(httpd_req_t *req, cJSON *root)
{
char *s = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
httpd_resp_set_type(req, "application/json");
esp_err_t err = httpd_resp_sendstr(req, s);
free(s);
return err;
}
static esp_err_t send_ok(httpd_req_t *req)
{
httpd_resp_set_type(req, "application/json");
return httpd_resp_sendstr(req, "{\"ok\":true}");
}
static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg)
{
httpd_resp_set_status(req, status);
httpd_resp_set_type(req, "text/plain");
return httpd_resp_sendstr(req, msg);
}
// Read a small JSON body. Caller frees with cJSON_Delete.
static cJSON *read_json(httpd_req_t *req)
{
if (req->content_len <= 0 || req->content_len > 2048) {
return NULL;
}
char *buf = malloc(req->content_len + 1);
int got = 0;
while (got < req->content_len) {
int n = httpd_req_recv(req, buf + got, req->content_len - got);
if (n <= 0) {
free(buf);
return NULL;
}
got += n;
}
buf[got] = 0;
cJSON *root = cJSON_Parse(buf);
free(buf);
return root;
}
static const char *json_str(cJSON *root, const char *key, const char *def)
{
cJSON *v = cJSON_GetObjectItem(root, key);
return cJSON_IsString(v) ? v->valuestring : def;
}
static int json_int(cJSON *root, const char *key, int def)
{
cJSON *v = cJSON_GetObjectItem(root, key);
return cJSON_IsNumber(v) ? v->valueint : def;
}
static void url_decode(char *s)
{
char *o = s;
for (; *s; s++) {
if (*s == '+') {
*o++ = ' ';
} else if (*s == '%' && s[1] && s[2]) {
char hex[3] = {s[1], s[2], 0};
*o++ = strtol(hex, NULL, 16);
s += 2;
} else {
*o++ = *s;
}
}
*o = 0;
}
static bool query_param(httpd_req_t *req, const char *key, char *out, size_t size)
{
char q[256];
if (httpd_req_get_url_query_str(req, q, sizeof(q)) != ESP_OK ||
httpd_query_key_value(q, key, out, size) != ESP_OK) {
return false;
}
url_decode(out);
return true;
}
static void colour_hex(uint8_t c, char out[8])
{
snprintf(out, 8, "#%02x%02x%02x", (c >> 5) * 255 / 7, ((c >> 2) & 7) * 255 / 7, (c & 3) * 255 / 3);
}
static uint8_t parse_colour(const char *hex, uint8_t def)
{
if (!hex || hex[0] != '#' || strlen(hex) != 7) {
return def;
}
unsigned long v = strtoul(hex + 1, NULL, 16);
return rgb888_to_332(v >> 16, (v >> 8) & 255, v & 255);
}
// ---------------------------------------------------------------------------
// Handlers
static esp_err_t h_index(httpd_req_t *req)
{
httpd_resp_set_type(req, "text/html");
return httpd_resp_send(req, index_html_start, index_html_end - index_html_start);
}
static esp_err_t h_state(httpd_req_t *req)
{
show_t s;
net_info_t n;
app_get_show(&s);
net_get_info(&n);
cJSON *root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, "w", W);
cJSON_AddNumberToObject(root, "h", H);
cJSON_AddNumberToObject(root, "hz", REFRESH_HZ);
cJSON_AddStringToObject(root, "content", content_key(s.content));
cJSON_AddNumberToObject(root, "slot", s.slot);
cJSON *list = cJSON_AddArrayToObject(root, "contents");
for (int i = 0; i < CONTENT_COUNT; i++) {
cJSON *c = cJSON_CreateObject();
cJSON_AddStringToObject(c, "key", content_key(i));
cJSON_AddStringToObject(c, "name", content_name(i));
cJSON_AddItemToArray(list, c);
}
char hex[8];
cJSON *msg = cJSON_AddObjectToObject(root, "msg");
cJSON_AddStringToObject(msg, "text", s.msg.text);
colour_hex(s.msg.fg, hex);
cJSON_AddStringToObject(msg, "fg", hex);
colour_hex(s.msg.bg, hex);
cJSON_AddStringToObject(msg, "bg", hex);
cJSON_AddNumberToObject(msg, "size", s.msg.size);
cJSON *slots = cJSON_AddArrayToObject(root, "slots");
for (int i = 0; i < gallery_slots(); i++) {
char name[GALLERY_NAME_MAX + 1];
cJSON_AddItemToArray(slots, gallery_name(i, name) ? cJSON_CreateString(name) : cJSON_CreateNull());
}
cJSON *jn = cJSON_AddObjectToObject(root, "net");
cJSON_AddStringToObject(jn, "ap_ssid", n.ap_ssid);
cJSON_AddStringToObject(jn, "ap_ip", n.ap_ip);
cJSON_AddStringToObject(jn, "sta_ssid", n.sta_ssid);
cJSON_AddStringToObject(jn, "sta_ip", n.sta_ip);
cJSON_AddBoolToObject(jn, "sta_connected", n.sta_connected);
cJSON_AddStringToObject(root, "tz", tz);
cJSON_AddNumberToObject(root, "time", (double)time(NULL));
cJSON_AddStringToObject(root, "version", esp_app_get_description()->version);
cJSON_AddStringToObject(root, "built", esp_app_get_description()->date);
cJSON_AddStringToObject(root, "partition", esp_ota_get_running_partition()->label);
return send_json(req, root);
}
// Raw W*H RGB332 of what's on screen
static esp_err_t h_screenshot(httpd_req_t *req)
{
// Reuses the upload buffer: handlers run one at a time
if (!upload_buf) {
upload_buf = heap_caps_malloc(W * H, MALLOC_CAP_SPIRAM);
}
if (!display_snapshot(upload_buf)) {
return send_error(req, "503 Service Unavailable", "display not running");
}
const uint8_t *fb = upload_buf;
httpd_resp_set_type(req, "application/octet-stream");
for (int off = 0; off < W * H; off += 8192) {
if (httpd_resp_send_chunk(req, (const char *)fb + off, MIN(8192, W * H - off)) != ESP_OK) {
return ESP_FAIL;
}
}
return httpd_resp_send_chunk(req, NULL, 0);
}
static esp_err_t h_show(httpd_req_t *req)
{
cJSON *root = read_json(req);
if (!root) {
return send_error(req, "400 Bad Request", "bad JSON");
}
int c = content_from_key(json_str(root, "content", ""));
int slot = json_int(root, "slot", 0);
cJSON_Delete(root);
if (c < 0) {
return send_error(req, "400 Bad Request", "unknown content");
}
if (c == CONTENT_IMAGE && (slot < SLOT_LIVE || slot >= gallery_slots())) {
return send_error(req, "400 Bad Request", "bad slot");
}
if (c != CONTENT_IMAGE) {
show_t s;
app_get_show(&s);
slot = s.slot; // remember the last image slot
}
app_show(c, slot);
return send_ok(req);
}
static esp_err_t h_message(httpd_req_t *req)
{
cJSON *root = read_json(req);
if (!root) {
return send_error(req, "400 Bad Request", "bad JSON");
}
show_t s;
app_get_show(&s);
message_t m = s.msg;
strlcpy(m.text, json_str(root, "text", m.text), sizeof(m.text));
m.fg = parse_colour(json_str(root, "fg", NULL), m.fg);
m.bg = parse_colour(json_str(root, "bg", NULL), m.bg);
m.size = MIN(json_int(root, "size", m.size), MSG_SIZE_FILL);
cJSON_Delete(root);
app_set_message(&m);
return send_ok(req);
}
// Body: exactly W*H bytes of RGB332, converted in the browser
static esp_err_t h_image_upload(httpd_req_t *req)
{
char arg[48];
int slot = query_param(req, "slot", arg, sizeof(arg)) ? atoi(arg) : SLOT_LIVE;
char name[GALLERY_NAME_MAX + 1] = "Image";
if (query_param(req, "name", arg, sizeof(arg)) && arg[0]) {
strlcpy(name, arg, sizeof(name));
}
if (slot < SLOT_LIVE || slot >= gallery_slots()) {
return send_error(req, "400 Bad Request", "bad slot");
}
if (req->content_len != W * H) {
char msg[64];
snprintf(msg, sizeof(msg), "expected %d bytes for %dx%d", W * H, W, H);
return send_error(req, "400 Bad Request", msg);
}
if (!upload_buf) {
upload_buf = heap_caps_malloc(W * H, MALLOC_CAP_SPIRAM);
}
int got = 0;
while (got < W * H) {
int n = httpd_req_recv(req, (char *)upload_buf + got, W * H - got);
if (n == HTTPD_SOCK_ERR_TIMEOUT) {
continue;
}
if (n <= 0) {
return ESP_FAIL;
}
got += n;
}
if (slot == SLOT_LIVE) {
// Swap buffers rather than copy; the old live image becomes the next upload buffer
live_image_lock();
uint8_t *old = live_image;
live_image = upload_buf;
upload_buf = old;
live_image_unlock();
} else if (!gallery_write(slot, name, upload_buf)) {
return send_error(req, "500 Internal Server Error", "flash write failed");
}
app_show(CONTENT_IMAGE, slot);
return send_ok(req);
}
static esp_err_t h_image_delete(httpd_req_t *req)
{
char arg[8];
int slot = query_param(req, "slot", arg, sizeof(arg)) ? atoi(arg) : -2;
if (!gallery_delete(slot)) {
return send_error(req, "400 Bad Request", "bad slot");
}
show_t s;
app_get_show(&s);
if (s.content == CONTENT_IMAGE && s.slot == slot) {
app_refresh();
}
return send_ok(req);
}
static esp_err_t h_wifi(httpd_req_t *req)
{
cJSON *root = read_json(req);
if (!root) {
return send_error(req, "400 Bad Request", "bad JSON");
}
char ssid[33], pass[65];
strlcpy(ssid, json_str(root, "ssid", ""), sizeof(ssid));
strlcpy(pass, json_str(root, "pass", ""), sizeof(pass));
cJSON_Delete(root);
nvs_set_string("sta_ssid", ssid);
nvs_set_string("sta_pass", pass);
xSemaphoreTake(net_lock, portMAX_DELAY);
strcpy(net.sta_ssid, ssid);
xSemaphoreGive(net_lock);
// Reply before reconnecting: the scan can briefly interrupt the access point
send_ok(req);
esp_timer_stop(reconnect_timer);
esp_wifi_disconnect();
set_sta(ssid, pass);
if (ssid[0]) {
esp_wifi_connect();
}
app_refresh();
return ESP_OK;
}
static esp_err_t h_time(httpd_req_t *req)
{
cJSON *root = read_json(req);
if (!root) {
return send_error(req, "400 Bad Request", "bad JSON");
}
cJSON *epoch = cJSON_GetObjectItem(root, "epoch");
const char *new_tz = json_str(root, "tz", NULL);
if (new_tz && new_tz[0]) {
strlcpy(tz, new_tz, sizeof(tz));
nvs_set_string("tz", tz);
apply_tz();
}
// Browser time is only a fallback; prefer NTP once on the home network
if (cJSON_IsNumber(epoch) && !(sntp_started && time(NULL) > 1700000000)) {
struct timeval tv = {.tv_sec = (time_t)epoch->valuedouble};
settimeofday(&tv, NULL);
}
cJSON_Delete(root);
return send_ok(req);
}
static void restart_task(void *arg)
{
vTaskDelay(pdMS_TO_TICKS(1000));
esp_restart();
}
// Body: the firmware .bin
static esp_err_t h_ota(httpd_req_t *req)
{
const esp_partition_t *part = esp_ota_get_next_update_partition(NULL);
if (!part || req->content_len <= 0 || req->content_len > part->size) {
return send_error(req, "400 Bad Request", "firmware too big or missing");
}
esp_ota_handle_t ota;
if (esp_ota_begin(part, OTA_WITH_SEQUENTIAL_WRITES, &ota) != ESP_OK) {
return send_error(req, "500 Internal Server Error", "OTA begin failed");
}
char *buf = malloc(4096);
int left = req->content_len;
esp_err_t err = ESP_OK;
while (left > 0 && err == ESP_OK) {
int n = httpd_req_recv(req, buf, MIN(left, 4096));
if (n == HTTPD_SOCK_ERR_TIMEOUT) {
continue;
}
if (n <= 0) {
err = ESP_FAIL;
break;
}
err = esp_ota_write(ota, buf, n);
left -= n;
}
free(buf);
if (err != ESP_OK) {
esp_ota_abort(ota);
return send_error(req, "500 Internal Server Error", "OTA write failed");
}
if (esp_ota_end(ota) != ESP_OK || esp_ota_set_boot_partition(part) != ESP_OK) {
return send_error(req, "400 Bad Request", "firmware image is invalid");
}
ESP_LOGI(TAG, "firmware written to %s, restarting", part->label);
send_ok(req);
xTaskCreate(restart_task, "restart", 2048, NULL, 5, NULL);
return ESP_OK;
}
// ---------------------------------------------------------------------------
void web_start(void)
{
nvs_get_string("tz", tz, sizeof(tz));
apply_tz();
wifi_init();
app_refresh(); // show the network info
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
cfg.stack_size = 8192;
cfg.max_uri_handlers = 16;
cfg.core_id = 0;
cfg.recv_wait_timeout = 30;
cfg.lru_purge_enable = true;
httpd_handle_t server;
ESP_ERROR_CHECK(httpd_start(&server, &cfg));
const httpd_uri_t uris[] = {
{.uri = "/", .method = HTTP_GET, .handler = h_index},
{.uri = "/api/state", .method = HTTP_GET, .handler = h_state},
{.uri = "/api/show", .method = HTTP_POST, .handler = h_show},
{.uri = "/api/screenshot", .method = HTTP_GET, .handler = h_screenshot},
{.uri = "/api/message", .method = HTTP_POST, .handler = h_message},
{.uri = "/api/image", .method = HTTP_POST, .handler = h_image_upload},
{.uri = "/api/image", .method = HTTP_DELETE, .handler = h_image_delete},
{.uri = "/api/wifi", .method = HTTP_POST, .handler = h_wifi},
{.uri = "/api/time", .method = HTTP_POST, .handler = h_time},
{.uri = "/api/ota", .method = HTTP_POST, .handler = h_ota},
};
for (int i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) {
httpd_register_uri_handler(server, &uris[i]);
}
}