From 3239eaf9c8160933ee07a7ffe933cb4dadae8f77 Mon Sep 17 00:00:00 2001 From: jess Date: Fri, 3 Apr 2026 03:48:42 -0700 Subject: [PATCH] implement UDP zombie reaper task --- main/wifi_transport.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/main/wifi_transport.c b/main/wifi_transport.c index 47c9d04..7a9df04 100644 --- a/main/wifi_transport.c +++ b/main/wifi_transport.c @@ -20,6 +20,9 @@ #define UDP_PORT 5941 #define UDP_BUF_SIZE 128 #define UDP_CLIENTS_MAX 16 +#define REAP_THRESHOLD 10 +#define REAP_WINDOW_MS 200 +#define REAP_INTERVAL_MS 5000 static int udp_sock = -1; static esp_netif_t *ap_netif; @@ -236,6 +239,39 @@ static void udp_rx_task(void *param) } } +static void udp_reaper_task(void *arg) +{ + (void)arg; + for (;;) { + vTaskDelay(pdMS_TO_TICKS(REAP_INTERVAL_MS)); + + xSemaphoreTake(client_mutex, portMAX_DELAY); + if (client_count < REAP_THRESHOLD) { + xSemaphoreGive(client_mutex); + continue; + } + + uint32_t cutoff = xTaskGetTickCount() * portTICK_PERIOD_MS; + printf("REAP: cycle start, %d clients\n", client_count); + xSemaphoreGive(client_mutex); + + send_keepalive(); + vTaskDelay(pdMS_TO_TICKS(REAP_WINDOW_MS)); + + xSemaphoreTake(client_mutex, portMAX_DELAY); + int reaped = 0; + for (int i = client_count - 1; i >= 0; i--) { + if (clients[i].last_touch_ms < cutoff) { + client_remove_by_index(i); + reaped++; + } + } + xSemaphoreGive(client_mutex); + + if (reaped) printf("REAP: removed %d zombie(s), %d remain\n", reaped, client_count); + } +} + int wifi_send_sysex(const uint8_t *sysex, uint16_t len) { if (udp_sock < 0 || client_count == 0) @@ -384,5 +420,6 @@ int wifi_transport_init(void) } xTaskCreate(udp_rx_task, "udp_rx", 4096, NULL, 5, NULL); + xTaskCreate(udp_reaper_task, "reaper", 2048, NULL, 4, NULL); return 0; }