#include "auth.h" #include "ws.h" #include #include #include "cJSON.h" #include "engine.h" #include "esp_log.h" #include "store.h" static const char *TAG = "ws"; #define FRAME_MAX 4096 static void send_text(httpd_req_t *req, const char *text) { httpd_ws_frame_t f = { .type = HTTPD_WS_TYPE_TEXT, .payload = (uint8_t *)text, .len = strlen(text) }; httpd_ws_send_frame_async(req->handle, httpd_req_to_sockfd(req), &f); } // One v1 driver message from the browser: "to" (a MAC) addresses one driver, otherwise it is broadcast static void forward(httpd_req_t *req, const char *text) { cJSON *msg = cJSON_Parse(text); if (!cJSON_IsObject(msg)) { cJSON_Delete(msg); send_text(req, "{\"error\":\"JSON object required\"}"); return; } cJSON *to = cJSON_DetachItemFromObject(msg, "to"), *targets = NULL; if (cJSON_IsString(to)) { targets = cJSON_CreateArray(); cJSON_AddItemToArray(targets, to); } else { cJSON_Delete(to); } cJSON *messages = cJSON_CreateArray(); cJSON_AddItemToArray(messages, msg); store_lock(); esp_err_t err = engine_push(messages, targets); store_unlock(); cJSON_Delete(messages); cJSON_Delete(targets); if (err != ESP_OK) { send_text(req, "{\"error\":\"Send failed\"}"); } } // Right after the upgrade: the v1 greeting. The controller keeps no Wi-Fi driver connections, so the // snapshot is always empty. static esp_err_t on_open(httpd_req_t *req) { if (auth_ws_admit(req, "devices", AUTH_CONTROL) != ESP_OK) { return ESP_FAIL; // closes the socket: driving drivers needs devices control } send_text(req, "{\"type\":\"device_tcp_snapshot\",\"connected_ips\":[]}"); return ESP_OK; } static esp_err_t ws_handler(httpd_req_t *req) { if (req->method == HTTP_GET) { // only a plain GET reaches the handler; the upgrade is answered by httpd httpd_resp_set_status(req, "426 Upgrade Required"); httpd_resp_set_hdr(req, "Upgrade", "websocket"); return httpd_resp_sendstr(req, "websocket only"); } httpd_ws_frame_t f = { 0 }; esp_err_t err = httpd_ws_recv_frame(req, &f, 0); if (err != ESP_OK) { return err; } if (f.type != HTTPD_WS_TYPE_TEXT || f.len == 0) { return ESP_OK; } if (f.len > FRAME_MAX) { ESP_LOGW(TAG, "frame of %u bytes dropped", (unsigned)f.len); return ESP_FAIL; // closes the connection } char *buf = malloc(f.len + 1); if (!buf) { return ESP_ERR_NO_MEM; } f.payload = (uint8_t *)buf; err = httpd_ws_recv_frame(req, &f, f.len); if (err == ESP_OK) { buf[f.len] = 0; if (auth_ws_allowed(httpd_req_to_sockfd(req), "devices", AUTH_CONTROL)) { forward(req, buf); } else { send_text(req, "{\"error\":\"not allowed\"}"); } } free(buf); return err; } esp_err_t ws_register(httpd_handle_t server) { const httpd_uri_t u = { .uri = "/ws", .method = HTTP_GET, .handler = ws_handler, .is_websocket = true, .ws_post_handshake_cb = on_open }; return httpd_register_uri_handler(server, &u); }