log_stream.c 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /**
  2. * WebSocket-based log streaming over HTTP.
  3. *
  4. * Intercepts ESP-IDF log output via esp_log_set_vprintf(), stores lines
  5. * in a ring buffer, and broadcasts them to any connected WebSocket
  6. * client on /ws/logs. UART output is preserved.
  7. */
  8. #include "log_stream.h"
  9. #include "spiram_task.h"
  10. #include "esp_heap_caps.h"
  11. #include "esp_log.h"
  12. #include "esp_http_server.h"
  13. #include "freertos/FreeRTOS.h"
  14. #include "freertos/semphr.h"
  15. #include "freertos/task.h"
  16. #include <stdarg.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. /* Ring buffer size — must be power of two for masking. */
  20. #define LOG_RING_SIZE 8192
  21. #define LOG_RING_MASK (LOG_RING_SIZE - 1)
  22. #define MAX_WS_CLIENTS 3
  23. #define BROADCAST_TASK_STACK 4096
  24. #define BROADCAST_INTERVAL_MS 100
  25. #define MAX_SEND_CHUNK 1024
  26. static char *s_ring;
  27. static volatile size_t s_head; /* next write position */
  28. static volatile size_t s_tail; /* next read position */
  29. static SemaphoreHandle_t s_mutex;
  30. static httpd_handle_t s_server;
  31. static int s_clients[MAX_WS_CLIENTS];
  32. static int s_client_count;
  33. static SemaphoreHandle_t s_client_mutex;
  34. static vprintf_like_t s_orig_vprintf;
  35. /* ------------------------------------------------------------------ */
  36. /* Ring buffer helpers (protected by s_mutex) */
  37. /* ------------------------------------------------------------------ */
  38. static inline size_t ring_used(void) {
  39. return (s_head - s_tail) & LOG_RING_MASK;
  40. }
  41. static void ring_write(const char *data, size_t len) {
  42. for (size_t i = 0; i < len; i++) {
  43. /* If head is about to overwrite tail, discard oldest byte. */
  44. if (((s_head + 1) & LOG_RING_MASK) == (s_tail & LOG_RING_MASK)) {
  45. s_tail = (s_tail + 1) & LOG_RING_MASK;
  46. }
  47. s_ring[s_head & LOG_RING_MASK] = data[i];
  48. s_head = (s_head + 1) & LOG_RING_MASK;
  49. }
  50. }
  51. static size_t ring_read(char *buf, size_t max) {
  52. size_t avail = ring_used();
  53. if (avail > max) {
  54. avail = max;
  55. }
  56. for (size_t i = 0; i < avail; i++) {
  57. buf[i] = s_ring[s_tail & LOG_RING_MASK];
  58. s_tail = (s_tail + 1) & LOG_RING_MASK;
  59. }
  60. return avail;
  61. }
  62. /* ------------------------------------------------------------------ */
  63. /* Log hook — called from any task/ISR-safe context by esp_log */
  64. /* ------------------------------------------------------------------ */
  65. static int log_vprintf_hook(const char *fmt, va_list args) {
  66. /* Always print to UART first. */
  67. int ret = s_orig_vprintf(fmt, args);
  68. /* Format into a stack buffer and push to ring. */
  69. char buf[256];
  70. va_list copy;
  71. va_copy(copy, args);
  72. int len = vsnprintf(buf, sizeof(buf), fmt, copy);
  73. va_end(copy);
  74. if (len > 0) {
  75. if ((size_t)len >= sizeof(buf)) {
  76. len = sizeof(buf) - 1;
  77. }
  78. if (xSemaphoreTake(s_mutex, 0) == pdTRUE) {
  79. ring_write(buf, (size_t)len);
  80. xSemaphoreGive(s_mutex);
  81. }
  82. /* If the mutex is held we silently drop — better than blocking a log call.
  83. */
  84. }
  85. return ret;
  86. }
  87. /* ------------------------------------------------------------------ */
  88. /* WebSocket handler */
  89. /* ------------------------------------------------------------------ */
  90. static esp_err_t ws_log_handler(httpd_req_t *req) {
  91. if (req->method == HTTP_GET) {
  92. /* Handshake — register this socket. */
  93. int fd = httpd_req_to_sockfd(req);
  94. if (xSemaphoreTake(s_client_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
  95. if (s_client_count < MAX_WS_CLIENTS) {
  96. s_clients[s_client_count++] = fd;
  97. xSemaphoreGive(s_client_mutex);
  98. ESP_LOGI("log_stream", "WebSocket client connected (fd=%d, total=%d)",
  99. fd, s_client_count);
  100. } else {
  101. xSemaphoreGive(s_client_mutex);
  102. ESP_LOGW("log_stream", "Max WebSocket clients reached, rejecting fd=%d",
  103. fd);
  104. return ESP_FAIL;
  105. }
  106. } else {
  107. ESP_LOGW("log_stream", "Client mutex timeout, rejecting fd=%d", fd);
  108. return ESP_FAIL;
  109. }
  110. return ESP_OK;
  111. }
  112. /* We only stream logs out; ignore any incoming frames. */
  113. httpd_ws_frame_t frame = {.type = HTTPD_WS_TYPE_TEXT};
  114. return httpd_ws_recv_frame(req, &frame, 0);
  115. }
  116. /* ------------------------------------------------------------------ */
  117. /* Broadcast task */
  118. /* ------------------------------------------------------------------ */
  119. static void remove_client(int index) {
  120. if (index < s_client_count - 1) {
  121. s_clients[index] = s_clients[s_client_count - 1];
  122. }
  123. s_client_count--;
  124. }
  125. static void broadcast_task(void *arg) {
  126. (void)arg;
  127. char buf[MAX_SEND_CHUNK];
  128. while (1) {
  129. vTaskDelay(pdMS_TO_TICKS(BROADCAST_INTERVAL_MS));
  130. if (s_client_count == 0) {
  131. continue;
  132. }
  133. size_t len = 0;
  134. if (xSemaphoreTake(s_mutex, pdMS_TO_TICKS(50)) == pdTRUE) {
  135. len = ring_read(buf, sizeof(buf));
  136. xSemaphoreGive(s_mutex);
  137. }
  138. if (len == 0) {
  139. continue;
  140. }
  141. httpd_ws_frame_t frame = {
  142. .type = HTTPD_WS_TYPE_TEXT,
  143. .payload = (uint8_t *)buf,
  144. .len = len,
  145. };
  146. if (xSemaphoreTake(s_client_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
  147. for (int i = s_client_count - 1; i >= 0; i--) {
  148. esp_err_t err =
  149. httpd_ws_send_frame_async(s_server, s_clients[i], &frame);
  150. if (err != ESP_OK) {
  151. ESP_LOGW("log_stream", "Dropping WebSocket client fd=%d: %s",
  152. s_clients[i], esp_err_to_name(err));
  153. remove_client(i);
  154. }
  155. }
  156. xSemaphoreGive(s_client_mutex);
  157. }
  158. }
  159. }
  160. /* ------------------------------------------------------------------ */
  161. /* Public API */
  162. /* ------------------------------------------------------------------ */
  163. esp_err_t log_stream_init(void) {
  164. s_mutex = xSemaphoreCreateMutex();
  165. if (!s_mutex) {
  166. return ESP_ERR_NO_MEM;
  167. }
  168. #ifdef CONFIG_SPIRAM
  169. s_ring = heap_caps_malloc(LOG_RING_SIZE, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  170. #endif
  171. if (!s_ring) {
  172. s_ring = malloc(LOG_RING_SIZE);
  173. }
  174. if (!s_ring) {
  175. return ESP_ERR_NO_MEM;
  176. }
  177. s_head = s_tail = 0;
  178. s_client_count = 0;
  179. s_client_mutex = xSemaphoreCreateMutex();
  180. if (!s_client_mutex) {
  181. return ESP_ERR_NO_MEM;
  182. }
  183. /* Hook into esp_log — keep the original so UART output continues. */
  184. s_orig_vprintf = esp_log_set_vprintf(log_vprintf_hook);
  185. return ESP_OK;
  186. }
  187. esp_err_t log_stream_register(httpd_handle_t server) {
  188. s_server = server;
  189. httpd_uri_t ws_uri = {
  190. .uri = "/ws/logs",
  191. .method = HTTP_GET,
  192. .handler = ws_log_handler,
  193. .is_websocket = true,
  194. };
  195. esp_err_t err = httpd_register_uri_handler(server, &ws_uri);
  196. if (err != ESP_OK) {
  197. ESP_LOGE("log_stream", "Failed to register /ws/logs: %s",
  198. esp_err_to_name(err));
  199. return err;
  200. }
  201. task_create_spiram(broadcast_task, "log_ws", BROADCAST_TASK_STACK, NULL, 3,
  202. NULL, NULL);
  203. ESP_LOGI("log_stream", "Log streaming on /ws/logs");
  204. return ESP_OK;
  205. }