// Wi-Fi LED drivers: discovery over mDNS, one WebSocket per driver, and a sender task so the engine // never waits on the network. Requests are sent one at a time per driver, each answered before the next. #include "wifi_drv.h" #include #include #include #include #include #include "engine.h" #include "esp_log.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "store.h" #include "ws_client.h" #if !defined(CONFIG_IDF_TARGET_LINUX) || defined(LED_DESKTOP_MDNS) // the desktop build has its own mDNS browser #include "esp_netif_ip_addr.h" #include "mdns.h" #endif static const char *TAG = "wifi_drv"; #define LINKS_MAX 16 #define QUEUE_LEN 24 #define BODY_MAX 1024 #define REPLY_MAX 1024 #define DISCOVER_MS 30000 typedef struct { char id[WIFI_DRV_ID_MAX + 1]; // "" when the slot is free char ip[16]; // from mDNS; "" when not known (the hostname is used then) int fd; // sender task only bool up; // read by wifi_drv_connected int fails; int64_t retry_us; } link_t; typedef struct { char id[WIFI_DRV_ID_MAX + 1]; char method[8]; char path[40]; char *body; // JSON object text, owned by the job bool ping; // a batch ping of every Wi-Fi driver (no id, no body) } job_t; #define PING_MAX WIFI_DRV_PING_MAX static struct { bool busy; // set while a batch runs, cleared by the sender when it finishes int n; wifi_drv_ping_t r[PING_MAX]; } s_ping; // guarded by s_mu static SemaphoreHandle_t s_ping_done; static link_t s_links[LINKS_MAX]; static QueueHandle_t s_q; static SemaphoreHandle_t s_mu; // guards s_links[].id, .ip and .up // Find or claim the link slot for id. Call with s_mu held. static link_t *link_for(const char *id) { link_t *free_slot = NULL; for (int i = 0; i < LINKS_MAX; i++) { if (s_links[i].id[0] && !strcmp(s_links[i].id, id)) { return &s_links[i]; } if (!s_links[i].id[0] && !free_slot) { free_slot = &s_links[i]; } } if (free_slot) { snprintf(free_slot->id, sizeof(free_slot->id), "%s", id); free_slot->fd = -1; free_slot->up = false; free_slot->fails = 0; free_slot->retry_us = 0; } return free_slot; } static void mark_down(link_t *l) { ws_client_close(l->fd); l->fd = -1; xSemaphoreTake(s_mu, portMAX_DELAY); l->up = false; xSemaphoreGive(s_mu); l->fails++; int64_t backoff_s = 1LL << (l->fails < 5 ? l->fails : 5); // 2 s, 4 s, ... up to 30 s l->retry_us = esp_timer_get_time() + (backoff_s > 30 ? 30 : backoff_s) * 1000000LL; } // One request and its reply on the driver's link: connect if needed, send, wait for the answer. // Returns true with the reply in reply and the round trip in *rtt_ms (when not NULL). static bool exchange(const char *id, const char *method, const char *path, const char *body, char *reply, size_t cap, int *rtt_ms) { char host[80] = ""; store_lock(); const cJSON *dev = cJSON_GetObjectItem(store_coll("device"), id); const cJSON *addr = dev ? cJSON_GetObjectItem(dev, "address") : NULL; if (cJSON_IsString(addr)) { snprintf(host, sizeof(host), "%s", addr->valuestring); } store_unlock(); if (!host[0]) { // the device was removed while the request waited return false; } xSemaphoreTake(s_mu, portMAX_DELAY); link_t *l = link_for(id); char ip[16] = ""; if (l) { snprintf(ip, sizeof(ip), "%s", l->ip); } xSemaphoreGive(s_mu); if (!l) { return false; } if (l->fd < 0) { if (esp_timer_get_time() < l->retry_us) { return false; } l->fd = ws_client_connect(ip[0] ? ip : host, "/ws"); if (l->fd < 0) { mark_down(l); return false; } ESP_LOGI(TAG, "connected to %s", id); } size_t need = strlen(body) + strlen(path) + strlen(method) + 64; char *msg = malloc(need); bool ok = false; int64_t t0 = esp_timer_get_time(); if (msg) { int n = snprintf(msg, need, "{\"method\":\"%s\",\"path\":\"%s\",\"body\":%s}", method, path, body); ok = n > 0 && (size_t)n < need && ws_client_send_text(l->fd, msg, (size_t)n) == ESP_OK && ws_client_recv_text(l->fd, reply, cap) >= 0; free(msg); } if (!ok) { ESP_LOGW(TAG, "request to %s failed", id); mark_down(l); return false; } if (rtt_ms) { *rtt_ms = (int)((esp_timer_get_time() - t0) / 1000); } xSemaphoreTake(s_mu, portMAX_DELAY); l->up = true; xSemaphoreGive(s_mu); l->fails = 0; return true; } static void run_job(job_t *j) { char reply[REPLY_MAX]; exchange(j->id, j->method, j->path, j->body, reply, sizeof(reply), NULL); free(j->body); } // Ask every Wi-Fi driver for its status and record the round trip (-1 when it does not answer) // The driver's MAC from its status reply (an envelope whose body is the status JSON). The MAC is the // same in both modes, so it ties a board's Wi-Fi record to its ESP-NOW record. static void learn_mac(const char *id, const char *reply) { cJSON *env = cJSON_Parse(reply); const cJSON *b = env ? cJSON_GetObjectItem(env, "body") : NULL; cJSON *st = cJSON_IsString(b) ? cJSON_Parse(b->valuestring) : NULL; const cJSON *m = st ? cJSON_GetObjectItem(st, "mac") : NULL; if (cJSON_IsString(m) && strlen(m->valuestring) == 12) { engine_wifi_mac(id, m->valuestring); } cJSON_Delete(st); cJSON_Delete(env); } static void run_ping(void) { char ids[PING_MAX][WIFI_DRV_ID_MAX + 1]; int n = 0; store_lock(); const cJSON *d; cJSON_ArrayForEach(d, store_coll("device")) { const cJSON *tr = cJSON_GetObjectItem(d, "transport"); if (n < PING_MAX && cJSON_IsString(tr) && !strcmp(tr->valuestring, "wifi")) { snprintf(ids[n], sizeof(ids[n]), "%s", d->string); n++; } } store_unlock(); for (int i = 0; i < n; i++) { char reply[REPLY_MAX]; int rtt = -1; bool ok = exchange(ids[i], "GET", "/api/status", "{}", reply, sizeof(reply), &rtt); if (ok) { learn_mac(ids[i], reply); } xSemaphoreTake(s_mu, portMAX_DELAY); memcpy(s_ping.r[i].id, ids[i], sizeof(s_ping.r[i].id)); // both 13 bytes, NUL-terminated s_ping.r[i].rtt_ms = ok ? rtt : -1; s_ping.n = i + 1; xSemaphoreGive(s_mu); } xSemaphoreTake(s_mu, portMAX_DELAY); s_ping.busy = false; xSemaphoreGive(s_mu); xSemaphoreGive(s_ping_done); } static void sender_task(void *arg) { (void)arg; job_t j; for (;;) { if (xQueueReceive(s_q, &j, portMAX_DELAY) == pdTRUE) { if (j.ping) { run_ping(); } else { run_job(&j); } } } } void wifi_drv_init(void) { if (s_q) { return; } s_mu = xSemaphoreCreateMutex(); s_ping_done = xSemaphoreCreateBinary(); s_q = xQueueCreate(QUEUE_LEN, sizeof(job_t)); if (!s_mu || !s_ping_done || !s_q || xTaskCreate(sender_task, "wifi_drv", 6144, NULL, 4, NULL) != pdPASS) { ESP_LOGE(TAG, "cannot start the sender"); } } void wifi_drv_post(const char *id, const char *path, cJSON *body) { wifi_drv_init(); job_t j = {}; snprintf(j.id, sizeof(j.id), "%s", id); snprintf(j.method, sizeof(j.method), "POST"); snprintf(j.path, sizeof(j.path), "%s", path); j.body = cJSON_PrintUnformatted(body); cJSON_Delete(body); if (!j.body) { return; } if (strlen(j.body) > BODY_MAX || !s_q || xQueueSend(s_q, &j, 0) != pdTRUE) { ESP_LOGW(TAG, "dropped a request to %s", id); free(j.body); } } static cJSON *rgb_json(const uint8_t rgb[3]); #define IDENTIFY_MS 2000 static void identify_off_task(void *arg) { char *id = arg; vTaskDelay(pdMS_TO_TICKS(IDENTIFY_MS)); cJSON *body = cJSON_CreateObject(); cJSON_AddStringToObject(body, "pattern", "off"); wifi_drv_post(id, "/api/pattern", body); free(id); vTaskDelete(NULL); } void wifi_drv_identify(const char *id) { static const uint8_t red[3] = { 255, 0, 0 }; cJSON *body = cJSON_CreateObject(); cJSON_AddStringToObject(body, "pattern", "blink"); cJSON *cols = cJSON_AddArrayToObject(body, "colors"); cJSON_AddItemToArray(cols, rgb_json(red)); cJSON_AddNumberToObject(body, "delay", 50); cJSON_AddNumberToObject(body, "brightness", 128); wifi_drv_post(id, "/api/pattern", body); char *copy = strdup(id); if (!copy || xTaskCreate(identify_off_task, "wifi_ident", 3072, copy, 3, NULL) != pdPASS) { ESP_LOGW(TAG, "identify %s: no timer, the blink stays on", id); free(copy); } } int wifi_drv_ping_all(int timeout_ms, wifi_drv_ping_t out[], int max) { if (!s_q) { return 0; } xSemaphoreTake(s_mu, portMAX_DELAY); bool busy = s_ping.busy; if (!busy) { s_ping.busy = true; s_ping.n = 0; } xSemaphoreGive(s_mu); if (!busy) { xSemaphoreTake(s_ping_done, 0); // drop a signal left by an earlier batch that timed out job_t j = {}; j.ping = true; if (xQueueSend(s_q, &j, 0) != pdTRUE) { xSemaphoreTake(s_mu, portMAX_DELAY); s_ping.busy = false; xSemaphoreGive(s_mu); return 0; } } // Wait for the batch; if it runs past the timeout, report the replies that came in so far xSemaphoreTake(s_ping_done, pdMS_TO_TICKS(timeout_ms)); xSemaphoreTake(s_mu, portMAX_DELAY); int n = s_ping.n < max ? s_ping.n : max; for (int i = 0; i < n; i++) { out[i] = s_ping.r[i]; } xSemaphoreGive(s_mu); return n; } bool wifi_drv_connected(const char *id) { bool up = false; if (!s_mu) { return false; } xSemaphoreTake(s_mu, portMAX_DELAY); for (int i = 0; i < LINKS_MAX; i++) { if (s_links[i].id[0] && !strcmp(s_links[i].id, id)) { up = s_links[i].up; } } xSemaphoreGive(s_mu); return up; } /* ------------------------------------------------------------ preset body */ static uint8_t clamp8(int v) { return (uint8_t)(v < 0 ? 0 : (v > 255 ? 255 : v)); } // [r,g,b] or a "#RRGGBB" / "RRGGBB" string static bool read_rgb(const cJSON *v, uint8_t rgb[3]) { if (cJSON_IsArray(v)) { if (cJSON_GetArraySize(v) != 3) { return false; } for (int i = 0; i < 3; i++) { const cJSON *c = cJSON_GetArrayItem(v, i); if (!cJSON_IsNumber(c)) { return false; } rgb[i] = clamp8((int)c->valuedouble); } return true; } if (!cJSON_IsString(v)) { return false; } const char *s = v->valuestring; if (*s == '#') { s++; } if (strlen(s) != 6) { return false; } for (int i = 0; i < 6; i++) { if (!isxdigit((unsigned char)s[i])) { return false; } } unsigned x = (unsigned)strtoul(s, NULL, 16); rgb[0] = (x >> 16) & 0xFF; rgb[1] = (x >> 8) & 0xFF; rgb[2] = x & 0xFF; return true; } static cJSON *rgb_json(const uint8_t rgb[3]) { cJSON *a = cJSON_CreateArray(); for (int i = 0; i < 3; i++) { cJSON_AddItemToArray(a, cJSON_CreateNumber(rgb[i])); } return a; } static void copy_number(cJSON *o, const cJSON *src, const char *from, const char *to) { const cJSON *v = cJSON_GetObjectItem(src, from); if (cJSON_IsNumber(v)) { cJSON_AddNumberToObject(o, to, v->valuedouble); } } cJSON *wifi_drv_preset_body(const cJSON *p) { if (!cJSON_IsObject(p)) { return NULL; } cJSON *o = cJSON_CreateObject(); const cJSON *v = cJSON_GetObjectItem(p, "pattern"); if (cJSON_IsString(v)) { cJSON_AddStringToObject(o, "pattern", v->valuestring); } v = cJSON_GetObjectItem(p, "colors"); if (cJSON_IsArray(v)) { cJSON *cols = cJSON_AddArrayToObject(o, "colors"); const cJSON *c; cJSON_ArrayForEach(c, v) { uint8_t rgb[3]; if (read_rgb(c, rgb)) { cJSON_AddItemToArray(cols, rgb_json(rgb)); } } } uint8_t bg[3]; v = cJSON_GetObjectItem(p, "background"); if (!v) { v = cJSON_GetObjectItem(p, "bg"); } if (v && read_rgb(v, bg)) { cJSON_AddItemToObject(o, "background", rgb_json(bg)); } copy_number(o, p, "delay", "delay"); copy_number(o, p, "brightness", "brightness"); // A selected preset is applied on top of the one the driver is running (POST /api/pattern), so fields it // leaves out carry over: fade and beat timing are always sent, or "off" after "on" would fade for on's 10 s const cJSON *fade = cJSON_GetObjectItem(p, "fade"); if (!cJSON_IsNumber(fade)) { fade = cJSON_GetObjectItem(p, "f"); } cJSON_AddNumberToObject(o, "fade", cJSON_IsNumber(fade) && fade->valuedouble > 0 ? fade->valuedouble : 0); const cJSON *tb = cJSON_GetObjectItem(p, "beat_time"); if (!tb) { tb = cJSON_GetObjectItem(p, "tb"); } cJSON_AddBoolToObject(o, "beat_time", cJSON_IsTrue(tb) || (cJSON_IsNumber(tb) && tb->valuedouble != 0)); copy_number(o, p, "n1", "n1"); copy_number(o, p, "n2", "n2"); copy_number(o, p, "n3", "n3"); copy_number(o, p, "n4", "n4"); copy_number(o, p, "n6", "mode"); // the style mode travels as n6 on the controller v = cJSON_GetObjectItem(p, "reverse"); if (cJSON_IsBool(v)) { cJSON_AddBoolToObject(o, "reverse", cJSON_IsTrue(v)); } return o; } /* ------------------------------------------------------------ discovery */ #if !defined(CONFIG_IDF_TARGET_LINUX) || defined(LED_DESKTOP_MDNS) // A driver seen on mDNS: register it as a wifi device the first time, and remember its address static void note_driver(const char *host, const char *ip) { bool added = false; store_lock(); cJSON *all = store_coll("device"); if (!cJSON_GetObjectItem(all, host)) { char addr[WIFI_DRV_ID_MAX + 8]; snprintf(addr, sizeof(addr), "%s.local", host); cJSON *d = cJSON_CreateObject(); cJSON_AddStringToObject(d, "name", host); cJSON_AddStringToObject(d, "type", "led"); cJSON_AddStringToObject(d, "transport", "wifi"); cJSON_AddStringToObject(d, "address", addr); cJSON_AddItemToObject(d, "zones", cJSON_CreateArray()); cJSON_AddNullToObject(d, "default_pattern"); cJSON_AddStringToObject(d, "id", host); cJSON_AddItemToObject(all, host, d); store_save("device"); added = true; } store_unlock(); if (added) { ESP_LOGI(TAG, "found Wi-Fi driver %s at %s", host, ip); } xSemaphoreTake(s_mu, portMAX_DELAY); link_t *l = link_for(host); if (l) { snprintf(l->ip, sizeof(l->ip), "%s", ip); } xSemaphoreGive(s_mu); } static void discover_task(void *arg) { (void)arg; for (;;) { mdns_result_t *res = NULL; if (mdns_query_ptr("_http", "_tcp", 1500, 30, &res) == ESP_OK && res) { for (mdns_result_t *r = res; r; r = r->next) { if (!r->hostname || strlen(r->hostname) > WIFI_DRV_ID_MAX) { continue; } bool is_strip = false; for (size_t i = 0; i < r->txt_count && r->txt; i++) { if (r->txt[i].key && r->txt[i].value && !strcmp(r->txt[i].key, "app") && !strcmp(r->txt[i].value, "led-strip")) { is_strip = true; } } char ip[16] = ""; for (mdns_ip_addr_t *a = r->addr; is_strip && a && !ip[0]; a = a->next) { if (a->addr.type == ESP_IPADDR_TYPE_V4) { snprintf(ip, sizeof(ip), IPSTR, IP2STR(&a->addr.u_addr.ip4)); } } if (is_strip && ip[0]) { char host[WIFI_DRV_ID_MAX + 1]; snprintf(host, sizeof(host), "%s", r->hostname); note_driver(host, ip); } } } if (res) { mdns_query_results_free(res); } // Ping the drivers too: a board that switched mode is merged by its MAC wifi_drv_ping_t pr[WIFI_DRV_PING_MAX]; wifi_drv_ping_all(2000, pr, WIFI_DRV_PING_MAX); vTaskDelay(pdMS_TO_TICKS(DISCOVER_MS)); } } void wifi_drv_start_discovery(void) { static bool started; if (started) { return; } started = true; wifi_drv_init(); xTaskCreate(discover_task, "wifi_disc", 4096, NULL, 3, NULL); } #else void wifi_drv_start_discovery(void) { } #endif