From 71fd317229dc2c4bc1b4f566bd3ee364b28d575d Mon Sep 17 00:00:00 2001 From: Bob Date: Sun, 14 Dec 2025 14:29:56 -0800 Subject: [PATCH] start, stop and pps work. status does not --- components/iperf/iperf.c | 184 ++++++++++++++++++--------------------- components/iperf/iperf.h | 65 ++++---------- control_iperf.py | 58 ++++++------ 3 files changed, 131 insertions(+), 176 deletions(-) diff --git a/components/iperf/iperf.c b/components/iperf/iperf.c index 9492066..2375808 100644 --- a/components/iperf/iperf.c +++ b/components/iperf/iperf.c @@ -29,9 +29,6 @@ static EventGroupHandle_t s_iperf_event_group = NULL; #define RATE_CHECK_INTERVAL_US 500000 #define MIN_PACING_INTERVAL_US 100 -// --- REMOVED DUPLICATE STRUCT DEFINITION --- -// We rely on the definition in iperf.h - typedef struct { iperf_cfg_t cfg; bool finish; @@ -41,9 +38,38 @@ typedef struct { static iperf_ctrl_t s_iperf_ctrl = {0}; static TaskHandle_t s_iperf_task_handle = NULL; + +// Global Stats Tracker +static iperf_stats_t s_stats = {0}; + static esp_event_handler_instance_t instance_any_id; static esp_event_handler_instance_t instance_got_ip; +// --- Status Reporting --- +void iperf_get_stats(iperf_stats_t *stats) { + if (stats) { + // Calculate config PPS on the fly + s_stats.config_pps = (s_iperf_ctrl.cfg.pacing_period_us > 0) ? + (1000000 / s_iperf_ctrl.cfg.pacing_period_us) : 0; + *stats = s_stats; + } +} + +void iperf_print_status(void) { + iperf_get_stats(&s_stats); + float err = 0.0f; + if (s_stats.running && s_stats.config_pps > 0) { + // Error = (Target - Actual) / Target + int32_t diff = (int32_t)s_stats.config_pps - (int32_t)s_stats.actual_pps; + err = (float)diff * 100.0f / (float)s_stats.config_pps; + } + + // Format expected by Python regex + printf("IPERF_STATUS: Running=%d, Config=%" PRIu32 ", Actual=%" PRIu32 ", Err=%.1f%%\n", + s_stats.running, s_stats.config_pps, s_stats.actual_pps, err); +} + +// --- Network Events --- static void iperf_network_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { if (s_iperf_event_group == NULL) return; if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { @@ -58,7 +84,6 @@ static void iperf_network_event_handler(void* arg, esp_event_base_t event_base, static bool iperf_wait_for_ip(void) { if (!s_iperf_event_group) s_iperf_event_group = xEventGroupCreate(); - // Check if we already have IP esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); if (netif) { esp_netif_ip_info_t ip_info; @@ -85,10 +110,7 @@ static void trim_whitespace(char *str) { static void iperf_read_nvs_config(iperf_cfg_t *cfg) { nvs_handle_t my_handle; - if (nvs_open("storage", NVS_READONLY, &my_handle) != ESP_OK) { - ESP_LOGW(TAG, "No NVS config found, using defaults"); - return; - } + if (nvs_open("storage", NVS_READONLY, &my_handle) != ESP_OK) return; uint32_t val; if (nvs_get_u32(my_handle, NVS_KEY_IPERF_PERIOD, &val) == ESP_OK) cfg->pacing_period_us = val; @@ -96,33 +118,20 @@ static void iperf_read_nvs_config(iperf_cfg_t *cfg) { if (nvs_get_u32(my_handle, NVS_KEY_IPERF_LEN, &val) == ESP_OK) cfg->send_len = val; if (nvs_get_u32(my_handle, NVS_KEY_IPERF_PORT, &val) == ESP_OK) cfg->dport = (uint16_t)val; - // Read Role size_t req; char buf[16]; req = sizeof(buf); if (nvs_get_str(my_handle, NVS_KEY_IPERF_ROLE, buf, &req) == ESP_OK) { - if (strcmp(buf, "SERVER") == 0) { - cfg->flag |= IPERF_FLAG_SERVER; - cfg->flag &= ~IPERF_FLAG_CLIENT; - } else { - cfg->flag |= IPERF_FLAG_CLIENT; - cfg->flag &= ~IPERF_FLAG_SERVER; - } + if (strcmp(buf, "SERVER") == 0) cfg->flag |= IPERF_FLAG_SERVER; + else cfg->flag |= IPERF_FLAG_CLIENT; } - // Read Proto req = sizeof(buf); if (nvs_get_str(my_handle, NVS_KEY_IPERF_PROTO, buf, &req) == ESP_OK) { - if (strcmp(buf, "TCP") == 0) { - cfg->flag |= IPERF_FLAG_TCP; - cfg->flag &= ~IPERF_FLAG_UDP; - } else { - cfg->flag |= IPERF_FLAG_UDP; - cfg->flag &= ~IPERF_FLAG_TCP; - } + if (strcmp(buf, "TCP") == 0) cfg->flag |= IPERF_FLAG_TCP; + else cfg->flag |= IPERF_FLAG_UDP; } - // Read Dest IP if (nvs_get_str(my_handle, NVS_KEY_IPERF_DST_IP, NULL, &req) == ESP_OK) { char *ip_str = malloc(req); if (ip_str) { @@ -142,7 +151,7 @@ void iperf_set_pps(uint32_t pps) { if (s_iperf_task_handle != NULL) { s_iperf_ctrl.cfg.pacing_period_us = period_us; - ESP_LOGI(TAG, "Runtime pacing updated to %" PRIu32 " PPS", pps); + printf("IPERF_PPS_UPDATED: %" PRIu32 "\n", pps); } else { s_iperf_ctrl.cfg.pacing_period_us = period_us; } @@ -161,29 +170,23 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) { addr.sin_port = htons(ctrl->cfg.dport > 0 ? ctrl->cfg.dport : 5001); addr.sin_addr.s_addr = ctrl->cfg.dip; - // Log the actual destination we are about to use - char ip_str[32]; - inet_ntop(AF_INET, &addr.sin_addr, ip_str, sizeof(ip_str)); - ESP_LOGI(TAG, "Starting UDP Traffic to %s:%d (Period=%luus, Burst=%lu)", - ip_str, ntohs(addr.sin_port), ctrl->cfg.pacing_period_us, ctrl->cfg.burst_count); - int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sockfd < 0) { status_led_set_state(LED_STATE_FAILED); - ESP_LOGE(TAG, "Failed to create socket: errno %d", errno); return ESP_FAIL; } + // Indicate Running status_led_set_state(LED_STATE_TRANSMITTING_SLOW); + s_stats.running = true; + printf("IPERF_STARTED\n"); int64_t next_send_time = esp_timer_get_time(); int64_t end_time = (ctrl->cfg.time == 0) ? INT64_MAX : esp_timer_get_time() + (int64_t)ctrl->cfg.time * 1000000LL; int64_t last_rate_check = esp_timer_get_time(); uint32_t packets_since_check = 0; - int64_t enomem_start_time = 0; - // --- Sequence Counter --- int32_t packet_id = 0; while (!ctrl->finish && esp_timer_get_time() < end_time) { @@ -194,109 +197,85 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) { else while (esp_timer_get_time() < next_send_time) taskYIELD(); for (int k = 0; k < ctrl->cfg.burst_count; k++) { - - // --- Populate Iperf Header --- udp_datagram *hdr = (udp_datagram *)ctrl->buffer; - - // 1. Sequence ID (Big Endian) hdr->id = htonl(packet_id++); - - // 2. Timestamp (Big Endian) struct timeval tv; gettimeofday(&tv, NULL); hdr->tv_sec = htonl(tv.tv_sec); hdr->tv_usec = htonl(tv.tv_usec); - // ---------------------------------- - - int sent = sendto(sockfd, ctrl->buffer, ctrl->cfg.send_len, 0, (struct sockaddr *)&addr, sizeof(addr)); - - if (sent > 0) { + if (sendto(sockfd, ctrl->buffer, ctrl->cfg.send_len, 0, (struct sockaddr *)&addr, sizeof(addr)) > 0) { packets_since_check++; - enomem_start_time = 0; - - if (now - last_rate_check > RATE_CHECK_INTERVAL_US) { - int64_t interval = now - last_rate_check; - double cycles = (double)interval / (double)ctrl->cfg.pacing_period_us; - uint32_t expected_pkts = (uint32_t)(cycles * ctrl->cfg.burst_count); - uint32_t threshold = (expected_pkts * 3) / 4; - - led_state_t target = (packets_since_check >= threshold) - ? LED_STATE_TRANSMITTING - : LED_STATE_TRANSMITTING_SLOW; - - if (status_led_get_state() != target) status_led_set_state(target); - - last_rate_check = now; - packets_since_check = 0; - } } else { - if (errno == 12) { // ENOMEM - if (status_led_get_state() != LED_STATE_STALLED) status_led_set_state(LED_STATE_STALLED); - if (enomem_start_time == 0) enomem_start_time = now; - else if (now - enomem_start_time > 10000000) { - status_led_set_state(LED_STATE_FAILED); goto exit; - } - vTaskDelay(pdMS_TO_TICKS(10)); - } else { - ESP_LOGE(TAG, "Send failed: errno %d", errno); - status_led_set_state(LED_STATE_FAILED); goto exit; - } + if (errno != 12) { // Not ENOMEM + ESP_LOGE(TAG, "Send failed: %d", errno); + status_led_set_state(LED_STATE_FAILED); + goto exit; + } + vTaskDelay(pdMS_TO_TICKS(10)); } } + + // --- Stats & LED Update --- + now = esp_timer_get_time(); + if (now - last_rate_check > RATE_CHECK_INTERVAL_US) { + uint32_t interval_us = (uint32_t)(now - last_rate_check); + + // Calculate actual PPS + if (interval_us > 0) { + s_stats.actual_pps = (uint32_t)((uint64_t)packets_since_check * 1000000 / interval_us); + } + + // LED Feedback + uint32_t config_pps = iperf_get_pps(); + uint32_t threshold = (config_pps * 3) / 4; + led_state_t target = (s_stats.actual_pps >= threshold) ? LED_STATE_TRANSMITTING : LED_STATE_TRANSMITTING_SLOW; + if (status_led_get_state() != target) status_led_set_state(target); + + last_rate_check = now; + packets_since_check = 0; + } + next_send_time += ctrl->cfg.pacing_period_us; } exit: close(sockfd); + // Cleanup State + s_stats.running = false; + s_stats.actual_pps = 0; + // Reset LED to Green (Connected) + status_led_set_state(LED_STATE_CONNECTED); + printf("IPERF_STOPPED\n"); return ESP_OK; } static void iperf_task(void *arg) { iperf_ctrl_t *ctrl = (iperf_ctrl_t *)arg; - // Simple logic dispatch - if (ctrl->cfg.flag & IPERF_FLAG_UDP) { - if (ctrl->cfg.flag & IPERF_FLAG_CLIENT) { - iperf_start_udp_client(ctrl); - } else { - ESP_LOGW(TAG, "UDP Server mode not implemented in this snippet"); - } - } else { - ESP_LOGW(TAG, "TCP mode not implemented in this snippet"); + if (ctrl->cfg.flag & IPERF_FLAG_UDP && ctrl->cfg.flag & IPERF_FLAG_CLIENT) { + iperf_start_udp_client(ctrl); } free(ctrl->buffer); + // CRITICAL: Clear handle so start() can run again + s_iperf_task_handle = NULL; vTaskDelete(NULL); } void iperf_start(iperf_cfg_t *cfg) { - if (s_iperf_task_handle) return; + if (s_iperf_task_handle) { + ESP_LOGW(TAG, "Iperf already running"); + return; + } s_iperf_ctrl.cfg = *cfg; - - // 1. Read Overrides from NVS iperf_read_nvs_config(&s_iperf_ctrl.cfg); - // 2. Apply Defaults if NVS/Args were missing if (s_iperf_ctrl.cfg.send_len == 0) s_iperf_ctrl.cfg.send_len = 1470; if (s_iperf_ctrl.cfg.pacing_period_us == 0) s_iperf_ctrl.cfg.pacing_period_us = 10000; if (s_iperf_ctrl.cfg.burst_count == 0) s_iperf_ctrl.cfg.burst_count = 1; - // 3. Log the Final Config - char ip_str[32] = "0.0.0.0"; - struct in_addr ip_addr; - ip_addr.s_addr = s_iperf_ctrl.cfg.dip; - inet_ntop(AF_INET, &ip_addr, ip_str, sizeof(ip_str)); - - ESP_LOGI(TAG, "--- IPERF CONFIG ---"); - ESP_LOGI(TAG, "Role: %s", (s_iperf_ctrl.cfg.flag & IPERF_FLAG_CLIENT) ? "CLIENT" : "SERVER"); - ESP_LOGI(TAG, "Proto: %s", (s_iperf_ctrl.cfg.flag & IPERF_FLAG_UDP) ? "UDP" : "TCP"); - ESP_LOGI(TAG, "Dest IP: %s", ip_str); - ESP_LOGI(TAG, "Dest Port: %d", s_iperf_ctrl.cfg.dport); - ESP_LOGI(TAG, "Period: %lu us", s_iperf_ctrl.cfg.pacing_period_us); - ESP_LOGI(TAG, "--------------------"); - s_iperf_ctrl.finish = false; s_iperf_ctrl.buffer_len = s_iperf_ctrl.cfg.send_len + 128; s_iperf_ctrl.buffer = calloc(1, s_iperf_ctrl.buffer_len); @@ -309,5 +288,8 @@ void iperf_stop(void) { if (s_iperf_task_handle) { s_iperf_ctrl.finish = true; if (s_iperf_event_group) xEventGroupSetBits(s_iperf_event_group, IPERF_STOP_REQ_BIT); + } else { + // If already stopped, just print to satisfy controller + printf("IPERF_STOPPED\n"); } } diff --git a/components/iperf/iperf.h b/components/iperf/iperf.h index 9a5ef23..23c3d99 100644 --- a/components/iperf/iperf.h +++ b/components/iperf/iperf.h @@ -3,7 +3,7 @@ #include #include -#include "led_strip.h" // Needed for the handle type +#include "led_strip.h" // --- Configuration Flags --- #define IPERF_FLAG_CLIENT (1 << 0) @@ -18,14 +18,7 @@ #define IPERF_TRAFFIC_TASK_PRIORITY 4 #define IPERF_REPORT_TASK_PRIORITY 5 -#define IPERF_SOCKET_RX_TIMEOUT 10 -#define IPERF_SOCKET_ACCEPT_TIMEOUT 5 - -// --- Buffer Sizes --- #define IPERF_UDP_TX_LEN (1470) -#define IPERF_UDP_RX_LEN (16 << 10) -#define IPERF_TCP_TX_LEN (16 << 10) -#define IPERF_TCP_RX_LEN (16 << 10) // --- NVS Keys --- #define NVS_KEY_IPERF_ENABLE "iperf_enabled" @@ -39,32 +32,23 @@ typedef struct { uint32_t flag; - uint8_t type; uint32_t dip; uint16_t dport; - uint16_t sport; - uint32_t interval; uint32_t time; - - // Pacing uint32_t pacing_period_us; uint32_t burst_count; - uint32_t send_len; - uint32_t buffer_len; } iperf_cfg_t; +// --- Stats Structure --- typedef struct { - uint64_t total_len; - uint32_t buffer_len; - uint32_t sockfd; - uint32_t actual_len; - uint32_t packet_count; - uint8_t *buffer; - uint32_t udp_lost_counter; - uint32_t udp_packet_counter; -} iperf_traffic_t; + bool running; + uint32_t config_pps; + uint32_t actual_pps; + float error_rate; +} iperf_stats_t; +// --- Header --- typedef struct { int32_t id; uint32_t tv_sec; @@ -72,37 +56,18 @@ typedef struct { uint32_t id2; } udp_datagram; -typedef struct { - int32_t flags; - int32_t numThreads; - int32_t mPort; - int32_t mBufLen; - int32_t mWinBand; - int32_t mAmount; -} client_hdr_v1; +// --- API --- -#define HEADER_VERSION1 0x80000000 - -// --- Public API --- - -/** - * @brief Initialize the LED for Iperf status indication. - * @param handle The LED strip handle (created in main/status_led). - */ void iperf_init_led(led_strip_handle_t handle); - -/** - * @brief Set the target pacing rate in Packets Per Second (PPS). - * Converts PPS to microsecond interval internally. - * @param pps Target rate (e.g., 100 = 100 packets/sec) - */ void iperf_set_pps(uint32_t pps); - -/** - * @brief Get the current target rate in PPS. - */ uint32_t iperf_get_pps(void); +// New: Get snapshot of current stats +void iperf_get_stats(iperf_stats_t *stats); + +// New: Print formatted status to stdout (for CLI/Python) +void iperf_print_status(void); + void iperf_start(iperf_cfg_t *cfg); void iperf_stop(void); diff --git a/control_iperf.py b/control_iperf.py index 171a5d0..3682c34 100755 --- a/control_iperf.py +++ b/control_iperf.py @@ -14,20 +14,22 @@ class SerialController(asyncio.Protocol): self.buffer = "" self.completion_future = completion_future - # Determine command string if args.action == 'pps': self.cmd_str = f"iperf pps {args.value}\n" self.target_key = "IPERF_PPS_UPDATED" elif args.action == 'status': self.cmd_str = "iperf status\n" self.target_key = "IPERF_STATUS" - else: - self.cmd_str = f"iperf {args.action}\n" - self.target_key = f"IPERF_{args.action.upper()}ED" # STARTED / STOPPED + elif args.action == 'start': + self.cmd_str = "iperf start\n" + self.target_key = "IPERF_STARTED" + elif args.action == 'stop': + self.cmd_str = "iperf stop\n" + self.target_key = "IPERF_STOPPED" def connection_made(self, transport): self.transport = transport - transport.write(b'\n') # Clear noise + transport.write(b'\n') self.loop.create_task(self.send_command()) async def send_command(self): @@ -37,15 +39,27 @@ class SerialController(asyncio.Protocol): def data_received(self, data): self.buffer += data.decode(errors='ignore') - if self.target_key in self.buffer: - if not self.completion_future.done(): - if self.args.action == 'status': - m = re.search(r'PPS=(\d+)', self.buffer) - val = m.group(1) if m else "Unknown" - self.completion_future.set_result(val) - else: - self.completion_future.set_result(True) - self.transport.close() + # FIX: Process complete lines only to avoid partial regex matching + while '\n' in self.buffer: + line, self.buffer = self.buffer.split('\n', 1) + line = line.strip() + + if self.target_key in line: + if not self.completion_future.done(): + if self.args.action == 'status': + # FIX: Added [-]? to allow negative error rates (overshoot) + # Regex: Err=([-\d\.]+)% + m = re.search(r'Running=(\d+), Config=(\d+), Actual=(\d+), Err=([-\d\.]+)%', line) + if m: + state = "Running" if m.group(1) == '1' else "Stopped" + self.completion_future.set_result(f"{state}, Cfg: {m.group(2)}, Act: {m.group(3)}, Err: {m.group(4)}%") + else: + # Now if it fails, it's a true format mismatch, not fragmentation + self.completion_future.set_result(f"Parse Error on line: {line}") + else: + self.completion_future.set_result(True) + self.transport.close() + return def connection_lost(self, exc): if not self.completion_future.done(): @@ -78,20 +92,14 @@ def expand_devices(device_str): async def main(): parser = argparse.ArgumentParser() parser.add_argument('action', choices=['start', 'stop', 'pps', 'status']) - # NEW: Add optional positional argument for value (e.g. 'pps 200') - parser.add_argument('value_arg', nargs='?', type=int, help='Value for PPS (positional)') - # KEEP: Optional flag support - parser.add_argument('--value', type=int, help='Value for PPS command (flag)') + parser.add_argument('value_arg', nargs='?', type=int, help='Value for PPS') + parser.add_argument('--value', type=int, help='Value for PPS') parser.add_argument('--devices', required=True, help="/dev/ttyUSB0-29") args = parser.parse_args() - - # Logic: Prefer positional arg if present, otherwise fall back to flag - if args.value_arg is not None: - args.value = args.value_arg - + if args.value_arg is not None: args.value = args.value_arg if args.action == 'pps' and args.value is None: - print("Error: 'pps' action requires a value (e.g. 'pps 200' or '--value 200')") + print("Error: 'pps' action requires a value") sys.exit(1) if sys.platform == 'win32': asyncio.set_event_loop(asyncio.ProactorEventLoop()) @@ -105,7 +113,7 @@ async def main(): print("\nResults:") for dev, res in zip(devs, results): if args.action == 'status': - print(f"{dev}: {res if res else 'TIMEOUT'} PPS") + print(f"{dev}: {res if res else 'TIMEOUT'}") else: status = "OK" if res is True else "FAIL" print(f"{dev}: {status}")