// Patterns: the v1 app's controllers/pattern.py. Pattern metadata lives in the "pattern" collection, // keyed by name. Pattern sources (.py) come from led-driver/src/patterns, embedded in the firmware // (see tools/build_web.sh), and from uploads stored under /db/patterns, which take precedence. #include #include #include #include #include #include #include #include "api_util.h" #include "drv_ota.h" #include "esp_log.h" #include "store.h" #include "web.h" static const char *TAG = "patterns"; #define PAT_DIR "/db/patterns" #define CODE_MAX (64 * 1024) #define NAME_MAX_LEN 64 // on and off are built into the driver firmware; there is no file to serve or send static bool builtin(const char *name) { return !strcmp(name, "on") || !strcmp(name, "off"); } // "blink", "blink.py" or "blink.py.py" -> "blink"; false for anything that is not a plain file name static bool base_name(const char *in, char out[NAME_MAX_LEN + 1]) { size_t n = strlen(in); while (n >= 3 && !strncmp(in + n - 3, ".py", 3)) { n -= 3; } if (n == 0 || n > NAME_MAX_LEN) { return false; } for (size_t i = 0; i < n; i++) { char c = in[i]; if (!(isalnum((unsigned char)c) || c == '_' || c == '-')) { return false; } } memcpy(out, in, n); out[n] = 0; return true; } static void file_path(const char *base, char *path, size_t len) { snprintf(path, len, PAT_DIR "/%s.py", base); } // Pattern source: an upload, else the copy in the firmware. *heap says whether the caller frees *data. static bool load(const char *base, const uint8_t **data, size_t *len, bool *heap) { char path[96]; file_path(base, path, sizeof(path)); FILE *f = fopen(path, "rb"); if (f) { fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET); uint8_t *buf = size >= 0 ? malloc(size + 1) : NULL; bool ok = buf && fread(buf, 1, size, f) == (size_t)size; fclose(f); if (ok) { *data = buf; *len = size; *heap = true; return true; } free(buf); } char name[NAME_MAX_LEN + 16]; snprintf(name, sizeof(name), "patterns/%s.py", base); uint32_t n; if (web_file(name, data, &n)) { *len = n; *heap = false; return true; } return false; } static bool exists(const char *base) { const uint8_t *d; size_t n; bool heap; if (!load(base, &d, &n, &heap)) { return false; } if (heap) { free((void *)d); } return true; } static void add_name(const char *file, void *ctx) { char base[NAME_MAX_LEN + 1]; if (base_name(file, base) && strcmp(base, "__init__") && !cJSON_GetObjectItem(ctx, base)) { cJSON_AddItemToObject(ctx, base, cJSON_CreateObject()); } } // Every pattern with a source file, as {name: {}} static cJSON *file_names(void) { cJSON *o = cJSON_CreateObject(); web_each("patterns/", add_name, o); DIR *dir = opendir(PAT_DIR); struct dirent *e; while (dir && (e = readdir(dir))) { add_name(e->d_name, o); } if (dir) { closedir(dir); } return o; } static esp_err_t write_file(const char *base, const char *code, size_t len) { if (mkdir(PAT_DIR, 0775) != 0 && errno != EEXIST) { return ESP_FAIL; } char path[96]; file_path(base, path, sizeof(path)); FILE *f = fopen(path, "wb"); if (!f) { return ESP_FAIL; } bool ok = fwrite(code, 1, len, f) == len; ok = fclose(f) == 0 && ok; return ok ? ESP_OK : ESP_FAIL; } // Definitions used when the pattern collection has none: the driver's built-ins (no .py file, the seed // presets use them) and the animation patterns (field patterns span the rig, see led-driver/src/rig.py) static const struct { const char *name, *json; } BUILTIN[] = { { "on", "{\"min_delay\":10,\"max_delay\":10000,\"max_colors\":1}" }, { "off", "{\"min_delay\":10,\"max_delay\":10000,\"max_colors\":0}" }, { "rainbow", "{\"n1\":\"Step Rate\",\"min_delay\":10,\"max_delay\":10000,\"max_colors\":0}" }, { "hit", "{\"n1\":\"Attack (ms / ¼ beats)\",\"n2\":\"Hold\",\"n3\":\"Decay\",\"n4\":\"End: 0 background, 1 stay lit\",\"min_delay\":0,\"max_delay\":10000,\"max_colors\":10}" }, { "keyframes", "{\"n1\":\"Easing: 0 linear, 1 in-out, 2 step, 3 in, 4 out\",\"n2\":\"End: 0 last colour, 1 background, 2 off\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" }, { "sweep", "{\"n1\":\"Direction (degrees)\",\"n2\":\"Band width (‰ of rig)\",\"n3\":\"Trail (‰)\",\"n4\":\"1 = leave lit (wipe)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" }, { "ripple", "{\"n1\":\"Ring width (‰)\",\"n2\":\"Rings at once\",\"n3\":\"1 = from the edge in\",\"n4\":\"Fade with distance (‰)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" }, { "spin", "{\"n1\":\"Arms\",\"n2\":\"Arm width (degrees)\",\"n3\":\"Tail (degrees)\",\"n4\":\"1 = clockwise\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" }, { "grow", "{\"n1\":\"From: 0 centre, 1 edges, 2 round, 3 across\",\"n2\":\"Then: 0 stay, 1 empty back, 2 empty on, 3 off\",\"n3\":\"Direction (degrees, from = 3)\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" }, { "field_wave", "{\"n1\":\"Direction (degrees)\",\"n2\":\"Wavelength (‰ of rig)\",\"n3\":\"Kind: 0 linear, 1 rings, 2 swirl, 3 plasma\",\"min_delay\":10,\"max_delay\":60000,\"max_colors\":10}" }, }; // Stored metadata plus the built-ins and {} for every other pattern file, as {name: {...}} static cJSON *all_patterns(void) { cJSON *o = cJSON_Duplicate(store_coll("pattern"), true); for (size_t i = 0; i < sizeof(BUILTIN) / sizeof(BUILTIN[0]); i++) { if (!cJSON_GetObjectItem(o, BUILTIN[i].name)) { cJSON_AddItemToObject(o, BUILTIN[i].name, cJSON_Parse(BUILTIN[i].json)); } } cJSON *files = file_names(), *it; cJSON_ArrayForEach(it, files) { if (!cJSON_GetObjectItem(o, it->string)) { cJSON_AddItemToObject(o, it->string, cJSON_CreateObject()); } } cJSON_Delete(files); return o; } // GET /patterns and /patterns/definitions: every pattern with its definition static esp_err_t list_patterns(httpd_req_t *req) { return api_json(req, "200 OK", all_patterns(), true); } // GET /patterns/names: just the names, for a pattern picker that loads definitions one at a time static esp_err_t list_pattern_names(httpd_req_t *req) { cJSON *all = all_patterns(), *names = cJSON_CreateArray(), *it; cJSON_ArrayForEach(it, all) { cJSON_AddItemToArray(names, cJSON_CreateString(it->string)); } cJSON_Delete(all); return api_json(req, "200 OK", names, true); } // GET /patterns/: one pattern's definition ({} when it has none) static esp_err_t get_pattern(httpd_req_t *req, const char *name) { const cJSON *rec = cJSON_GetObjectItem(store_coll("pattern"), name); for (size_t i = 0; !rec && i < sizeof(BUILTIN) / sizeof(BUILTIN[0]); i++) { if (!strcmp(BUILTIN[i].name, name)) { cJSON *o = cJSON_Parse(BUILTIN[i].json); return api_json(req, "200 OK", o, true); } } return api_json(req, "200 OK", rec ? (cJSON *)rec : cJSON_CreateObject(), !rec); } // POST /patterns {name, data: {...}, ...}: data (plus any other keys) becomes the record under name static esp_err_t create_pattern(httpd_req_t *req) { cJSON *body = api_body(req); if (!body) { return ESP_OK; } const cJSON *name = cJSON_GetObjectItem(body, "name"); const cJSON *data = cJSON_GetObjectItem(body, "data"); char key[NAME_MAX_LEN + 1]; if (cJSON_IsString(name) && name->valuestring[0]) { snprintf(key, sizeof(key), "%s", name->valuestring); } else { store_next_id("pattern", key, sizeof(key)); } cJSON *rec = cJSON_IsObject(data) ? cJSON_Duplicate(data, true) : cJSON_CreateObject(); cJSON_DeleteItemFromObject(body, "data"); cJSON_DeleteItemFromObject(body, "name"); api_merge(rec, body); cJSON_Delete(body); cJSON *all = store_coll("pattern"); cJSON_DeleteItemFromObject(all, key); cJSON_AddItemToObject(all, key, rec); store_save("pattern"); return api_json(req, "201 Created", rec, false); } static esp_err_t serve_file(httpd_req_t *req, const char *name) { char base[NAME_MAX_LEN + 1]; if (!base_name(name, base)) { return api_error(req, "400 Bad Request", "Invalid pattern file name"); } if (builtin(base)) { return api_error(req, "400 Bad Request", "on and off are built into the driver firmware"); } const uint8_t *data; size_t len; bool heap; if (!load(base, &data, &len, &heap)) { return api_error(req, "404 Not Found", "Pattern file not found"); } httpd_resp_set_type(req, "text/plain; charset=utf-8"); esp_err_t r = httpd_resp_send(req, (const char *)data, len); if (heap) { free((void *)data); } return r; } static esp_err_t manifest(httpd_req_t *req) { char host[64]; if (httpd_req_get_hdr_value_str(req, "Host", host, sizeof(host)) != ESP_OK || !host[0]) { return api_error(req, "400 Bad Request", "Host header required"); } cJSON *o = cJSON_CreateObject(), *files = cJSON_AddArrayToObject(o, "files"); cJSON *names = file_names(), *it; cJSON_ArrayForEach(it, names) { char url[192]; cJSON *f = cJSON_CreateObject(); snprintf(url, sizeof(url), "%s.py", it->string); cJSON_AddStringToObject(f, "name", url); snprintf(url, sizeof(url), "http://%s/patterns/ota/file/%s.py", host, it->string); cJSON_AddStringToObject(f, "url", url); cJSON_AddItemToArray(files, f); } cJSON_Delete(names); return api_json(req, "200 OK", o, true); } // The name and code of an upload; on error a response has been sent and false returned static bool upload_args(httpd_req_t *req, cJSON *body, char base[NAME_MAX_LEN + 1], const char **code, bool *overwrite, esp_err_t *ret) { const cJSON *name = cJSON_GetObjectItem(body, "name"); if (!cJSON_IsString(name)) { name = cJSON_GetObjectItem(body, "filename"); } const cJSON *c = cJSON_GetObjectItem(body, "code"); const cJSON *ow = cJSON_GetObjectItem(body, "overwrite"); const char *err = !cJSON_IsString(name) || !base_name(name->valuestring, base) ? "a valid name is required" : builtin(base) ? "on and off are built into the driver firmware" : !cJSON_IsString(c) || !c->valuestring[0] ? "code is required" : strlen(c->valuestring) > CODE_MAX ? "code must be at most 64 KB" : NULL; if (err) { *ret = api_error(req, "400 Bad Request", err); return false; } *code = c->valuestring; *overwrite = !cJSON_IsFalse(ow); if (!*overwrite && exists(base)) { *ret = api_error(req, "409 Conflict", "Pattern already exists"); return false; } return true; } // POST /patterns/upload {name, code, overwrite}: store a pattern source static esp_err_t upload(httpd_req_t *req) { cJSON *body = api_body(req); if (!body) { return ESP_OK; } char base[NAME_MAX_LEN + 1]; const char *code; bool overwrite; esp_err_t ret; if (!upload_args(req, body, base, &code, &overwrite, &ret)) { cJSON_Delete(body); return ret; } bool had = exists(base); if (write_file(base, code, strlen(code)) != ESP_OK) { cJSON_Delete(body); return api_error(req, "500 Internal Server Error", "could not save the pattern"); } cJSON_Delete(body); char fname[NAME_MAX_LEN + 4]; snprintf(fname, sizeof(fname), "%s.py", base); cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "Pattern uploaded"); cJSON_AddStringToObject(o, "name", fname); cJSON_AddBoolToObject(o, "overwrote", had); return api_json(req, "201 Created", o, true); } // POST /patterns/driver {name, code, overwrite, min_delay, max_delay, max_colors, n1..n8}: store the // source and its metadata (n1..n8 are the parameter labels) static esp_err_t create_driver_pattern(httpd_req_t *req) { cJSON *body = api_body(req); if (!body) { return ESP_OK; } char base[NAME_MAX_LEN + 1]; const char *code; bool overwrite; esp_err_t ret; if (!upload_args(req, body, base, &code, &overwrite, &ret)) { cJSON_Delete(body); return ret; } if (!isalpha((unsigned char)base[0]) && base[0] != '_') { cJSON_Delete(body); return api_error(req, "400 Bad Request", "name must start with a letter or _"); } for (const char *c = base; *c; c++) { if (*c == '-') { cJSON_Delete(body); return api_error(req, "400 Bad Request", "name may only hold letters, digits and _"); } } cJSON *meta = cJSON_CreateObject(); static const char *const INTS[] = { "min_delay", "max_delay", "max_colors" }; for (size_t i = 0; i < sizeof(INTS) / sizeof(INTS[0]); i++) { const cJSON *v = cJSON_GetObjectItem(body, INTS[i]); if (!v || cJSON_IsNull(v) || (cJSON_IsString(v) && !v->valuestring[0])) { continue; } double d = cJSON_IsNumber(v) ? v->valuedouble : (cJSON_IsString(v) ? strtod(v->valuestring, NULL) : 0.5); if (d != (int)d) { cJSON_Delete(meta); cJSON_Delete(body); return api_error(req, "400 Bad Request", "min_delay, max_delay and max_colors must be integers"); } cJSON_AddNumberToObject(meta, INTS[i], (int)d); } for (int i = 1; i <= 8; i++) { char key[4]; snprintf(key, sizeof(key), "n%d", i); const cJSON *v = cJSON_GetObjectItem(body, key); if (cJSON_IsString(v) && v->valuestring[0]) { cJSON_AddStringToObject(meta, key, v->valuestring); } } if (write_file(base, code, strlen(code)) != ESP_OK) { cJSON_Delete(meta); cJSON_Delete(body); return api_error(req, "500 Internal Server Error", "could not save the pattern"); } cJSON_Delete(body); cJSON *all = store_coll("pattern"); cJSON *rec = cJSON_GetObjectItem(all, base); if (!cJSON_IsObject(rec)) { cJSON_DeleteItemFromObject(all, base); rec = cJSON_AddObjectToObject(all, base); } api_merge(rec, meta); store_save("pattern"); char fname[NAME_MAX_LEN + 4]; snprintf(fname, sizeof(fname), "%s.py", base); cJSON *o = cJSON_CreateObject(); cJSON_AddStringToObject(o, "message", "Pattern created"); cJSON_AddStringToObject(o, "name", base); cJSON_AddStringToObject(o, "file", fname); cJSON_AddItemToObject(o, "metadata", meta); return api_json(req, "201 Created", o, true); } // POST /patterns//send {device_id?}: push the source to one driver or every ESP-NOW driver // (patterns/.py on the driver), which then resets to load it static esp_err_t send_pattern(httpd_req_t *req, const char *name) { char base[NAME_MAX_LEN + 1]; if (!base_name(name, base)) { return api_error(req, "400 Bad Request", "Invalid pattern name"); } if (builtin(base)) { return api_error(req, "400 Bad Request", "on and off are built into the driver firmware"); } cJSON *body = api_body_opt(req); if (!body) { return ESP_OK; } char macs[16] = "all"; const cJSON *did = cJSON_GetObjectItem(body, "device_id"); if (cJSON_IsString(did) && did->valuestring[0]) { const cJSON *dev = cJSON_GetObjectItem(store_coll("device"), did->valuestring); const cJSON *tr = cJSON_GetObjectItem(dev, "transport"), *addr = cJSON_GetObjectItem(dev, "address"); if (!dev) { cJSON_Delete(body); return api_error(req, "404 Not Found", "Device not found"); } if (!cJSON_IsString(tr) || strcmp(tr->valuestring, "espnow") || !cJSON_IsString(addr) || strlen(addr->valuestring) != 12) { cJSON_Delete(body); return api_error(req, "400 Bad Request", "Device is not an ESP-NOW driver"); } snprintf(macs, sizeof(macs), "%s", addr->valuestring); } cJSON_Delete(body); const uint8_t *data; size_t len; bool heap; if (!load(base, &data, &len, &heap)) { return api_error(req, "404 Not Found", "Pattern file not found"); } char path[NAME_MAX_LEN + 16]; snprintf(path, sizeof(path), "patterns/%s.py", base); esp_err_t err; store_unlock(); // the transfer takes seconds; the sequencer must keep running cJSON *results = drv_ota_send(macs, path, data, len, true, &err); store_lock(); if (heap) { free((void *)data); } if (!results) { return err == ESP_ERR_INVALID_STATE ? api_error(req, "409 Conflict", "a driver update is already running") : err == ESP_ERR_NOT_FOUND ? api_error(req, "404 Not Found", "No ESP-NOW drivers") : api_error(req, "400 Bad Request", "Pattern cannot be sent"); } cJSON *o = cJSON_CreateObject(), *ids = cJSON_CreateArray(), *it; cJSON_ArrayForEach(it, results) { const cJSON *res = cJSON_GetObjectItem(it, "result"); if (cJSON_IsString(res) && strcmp(res->valuestring, "error")) { cJSON_AddItemToArray(ids, cJSON_CreateString(it->string)); } } int sent = cJSON_GetArraySize(ids); ESP_LOGI(TAG, "%s sent to %d driver(s)", path, sent); cJSON_AddStringToObject(o, sent ? "message" : "error", sent ? "Pattern sent" : "No driver accepted the pattern"); cJSON_AddStringToObject(o, "pattern", path + strlen("patterns/")); cJSON_AddItemToObject(o, "device_ids", ids); cJSON_AddNumberToObject(o, "sent_count", sent); cJSON_AddItemToObject(o, "results", results); return api_json(req, sent ? "200 OK" : "503 Service Unavailable", o, true); } bool patterns_route(httpd_req_t *req, int n, api_seg_t seg, esp_err_t *ret) { static const char FILE_PREFIX[] = "/patterns/ota/file/"; const int method = req->method; if (method == HTTP_GET && !strncmp(req->uri, FILE_PREFIX, sizeof(FILE_PREFIX) - 1)) { char name[NAME_MAX_LEN + 8]; const char *s = req->uri + sizeof(FILE_PREFIX) - 1; size_t len = strcspn(s, "?"); if (len >= sizeof(name)) { *ret = api_error(req, "400 Bad Request", "Invalid pattern file name"); return true; } memcpy(name, s, len); name[len] = 0; *ret = serve_file(req, name); return true; } if (n == 3 && method == HTTP_GET && !strcmp(seg[1], "ota") && !strcmp(seg[2], "manifest")) { *ret = manifest(req); return true; } if (method == HTTP_GET && (n == 1 || (n == 2 && !strcmp(seg[1], "definitions")))) { *ret = list_patterns(req); return true; } if (method == HTTP_GET && n == 2 && !strcmp(seg[1], "names")) { *ret = list_pattern_names(req); return true; } if (method == HTTP_GET && n == 2 && strcmp(seg[1], "ota") && strcmp(seg[1], "upload") && strcmp(seg[1], "driver")) { *ret = get_pattern(req, seg[1]); return true; } if (method != HTTP_POST) { return false; } if (n == 1) { *ret = create_pattern(req); } else if (n == 2 && !strcmp(seg[1], "upload")) { *ret = upload(req); } else if (n == 2 && !strcmp(seg[1], "driver")) { *ret = create_driver_pattern(req); } else if (n == 3 && !strcmp(seg[2], "send")) { *ret = send_pattern(req, seg[1]); } else { return false; } return true; }