initial runtime control of iperf
This commit is contained in:
parent
cab824265d
commit
a8cef0f1a7
|
|
@ -26,11 +26,12 @@ static EventGroupHandle_t s_iperf_event_group = NULL;
|
|||
#define IPERF_IP_READY_BIT (1 << 0)
|
||||
#define IPERF_STOP_REQ_BIT (1 << 1)
|
||||
|
||||
// Check rate every 500ms
|
||||
#define RATE_CHECK_INTERVAL_US 500000
|
||||
// Minimum gap (Safety Limit)
|
||||
#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;
|
||||
|
|
@ -50,15 +51,14 @@ static void iperf_network_event_handler(void* arg, esp_event_base_t event_base,
|
|||
}
|
||||
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
|
||||
xEventGroupClearBits(s_iperf_event_group, IPERF_IP_READY_BIT);
|
||||
status_led_set_state(LED_STATE_NO_CONFIG); // Yellow
|
||||
status_led_set_state(LED_STATE_NO_CONFIG);
|
||||
}
|
||||
}
|
||||
|
||||
static bool iperf_wait_for_ip(void) {
|
||||
if (!s_iperf_event_group) s_iperf_event_group = xEventGroupCreate();
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &iperf_network_event_handler, NULL, &instance_any_id));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &iperf_network_event_handler, NULL, &instance_got_ip));
|
||||
|
||||
// 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;
|
||||
|
|
@ -66,7 +66,12 @@ static bool iperf_wait_for_ip(void) {
|
|||
xEventGroupSetBits(s_iperf_event_group, IPERF_IP_READY_BIT);
|
||||
}
|
||||
}
|
||||
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &iperf_network_event_handler, NULL, &instance_any_id));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &iperf_network_event_handler, NULL, &instance_got_ip));
|
||||
|
||||
EventBits_t bits = xEventGroupWaitBits(s_iperf_event_group, IPERF_IP_READY_BIT | IPERF_STOP_REQ_BIT, pdFALSE, pdFALSE, portMAX_DELAY);
|
||||
|
||||
esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id);
|
||||
esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip);
|
||||
return !(bits & IPERF_STOP_REQ_BIT);
|
||||
|
|
@ -80,7 +85,10 @@ 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) return;
|
||||
if (nvs_open("storage", NVS_READONLY, &my_handle) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "No NVS config found, using defaults");
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t val;
|
||||
if (nvs_get_u32(my_handle, NVS_KEY_IPERF_PERIOD, &val) == ESP_OK) cfg->pacing_period_us = val;
|
||||
|
|
@ -88,7 +96,33 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
|
|
@ -104,11 +138,7 @@ static void iperf_read_nvs_config(iperf_cfg_t *cfg) {
|
|||
void iperf_set_pps(uint32_t pps) {
|
||||
if (pps == 0) pps = 1;
|
||||
uint32_t period_us = 1000000 / pps;
|
||||
|
||||
if (period_us < MIN_PACING_INTERVAL_US) {
|
||||
period_us = MIN_PACING_INTERVAL_US;
|
||||
ESP_LOGW(TAG, "PPS %" PRIu32 " clamped to max safe rate", pps);
|
||||
}
|
||||
if (period_us < MIN_PACING_INTERVAL_US) period_us = MIN_PACING_INTERVAL_US;
|
||||
|
||||
if (s_iperf_task_handle != NULL) {
|
||||
s_iperf_ctrl.cfg.pacing_period_us = period_us;
|
||||
|
|
@ -131,13 +161,20 @@ 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;
|
||||
}
|
||||
|
||||
status_led_set_state(LED_STATE_TRANSMITTING_SLOW); // Default state
|
||||
status_led_set_state(LED_STATE_TRANSMITTING_SLOW);
|
||||
|
||||
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;
|
||||
|
|
@ -146,6 +183,9 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) {
|
|||
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) {
|
||||
int64_t now = esp_timer_get_time();
|
||||
int64_t wait = next_send_time - now;
|
||||
|
|
@ -154,41 +194,52 @@ 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) {
|
||||
packets_since_check++;
|
||||
enomem_start_time = 0;
|
||||
|
||||
// --- DYNAMIC RATE HEALTH CHECK ---
|
||||
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);
|
||||
|
||||
// Threshold: 75% of expected rate
|
||||
uint32_t threshold = (expected_pkts * 3) / 4;
|
||||
|
||||
led_state_t target = (packets_since_check >= threshold)
|
||||
? LED_STATE_TRANSMITTING // Busy (Fast Flash)
|
||||
: LED_STATE_TRANSMITTING_SLOW; // Slow (Slow Pulse)
|
||||
? 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -197,28 +248,55 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) {
|
|||
}
|
||||
|
||||
exit:
|
||||
if (status_led_get_state() != LED_STATE_FAILED) {
|
||||
EventBits_t bits = xEventGroupGetBits(s_iperf_event_group);
|
||||
status_led_set_state((bits & IPERF_IP_READY_BIT) ? LED_STATE_CONNECTED : LED_STATE_NO_CONFIG);
|
||||
}
|
||||
close(sockfd);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void iperf_task(void *arg) {
|
||||
iperf_start_udp_client((iperf_ctrl_t *)arg);
|
||||
free(((iperf_ctrl_t *)arg)->buffer);
|
||||
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");
|
||||
}
|
||||
|
||||
free(ctrl->buffer);
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void iperf_start(iperf_cfg_t *cfg) {
|
||||
if (s_iperf_task_handle) 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;
|
||||
|
||||
iperf_read_nvs_config(&s_iperf_ctrl.cfg);
|
||||
// 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);
|
||||
|
|
|
|||
|
|
@ -78,12 +78,20 @@ def expand_devices(device_str):
|
|||
async def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=['start', 'stop', 'pps', 'status'])
|
||||
parser.add_argument('--value', type=int, help='Value for PPS command')
|
||||
# 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('--devices', required=True, help="/dev/ttyUSB0-29")
|
||||
|
||||
args = parser.parse_args()
|
||||
if args.action == 'pps' and not args.value:
|
||||
print("Error: 'pps' action requires --value")
|
||||
|
||||
# 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.action == 'pps' and args.value is None:
|
||||
print("Error: 'pps' action requires a value (e.g. 'pps 200' or '--value 200')")
|
||||
sys.exit(1)
|
||||
|
||||
if sys.platform == 'win32': asyncio.set_event_loop(asyncio.ProactorEventLoop())
|
||||
|
|
|
|||
|
|
@ -3,10 +3,9 @@
|
|||
ESP32 Unified Deployment Tool (esp32_deploy)
|
||||
Combines firmware flashing and device configuration with full control.
|
||||
Updates:
|
||||
- FIXED: Reset logic (DTR=False) to ensure App boot instead of Bootloader
|
||||
- AUTO-DETECT: Prioritizes /dev/esp_port_* (udev rules)
|
||||
- ROBUSTNESS: Merged "poking" and "retry" logic
|
||||
- 'target all' support
|
||||
- ADDED: --ip-device-based support (IP = Start_IP + Port_Number)
|
||||
- FIXED: Robust IP calculation logic
|
||||
- PRESERVED: Existing flash/monitor/config workflow
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
|
@ -252,7 +251,7 @@ class UnifiedDeployWorker:
|
|||
is_configured = await self._verify_configuration(reader)
|
||||
|
||||
if is_configured:
|
||||
self.log.info(f"{Colors.GREEN}Config verified.{Colors.RESET}")
|
||||
self.log.info(f"{Colors.GREEN}Config verified. IP: {self.target_ip}{Colors.RESET}")
|
||||
# Final Reset to apply
|
||||
writer.transport.serial.dtr = False
|
||||
writer.transport.serial.rts = True
|
||||
|
|
@ -313,6 +312,7 @@ class UnifiedDeployWorker:
|
|||
iperf_enable_val = '0' if self.args.no_iperf else '1'
|
||||
period_us = int(self.args.iperf_period * 1000000)
|
||||
|
||||
# Build list of commands using args (which have robust defaults)
|
||||
config_lines = [
|
||||
"CFG",
|
||||
f"SSID:{self.args.ssid}",
|
||||
|
|
@ -374,7 +374,12 @@ def parse_args():
|
|||
parser.add_argument('-b', '--baud', type=int, default=460800)
|
||||
parser.add_argument('--devices', type=str)
|
||||
parser.add_argument('--max-concurrent', type=int, default=None)
|
||||
|
||||
# --- IP Configuration ---
|
||||
parser.add_argument('--start-ip', help='Start IP (Required unless --target all)')
|
||||
parser.add_argument('--ip-device-based', action='store_true', help="Use /dev/ttyUSBx number as IP offset")
|
||||
|
||||
# --- Network Defaults (Robustness) ---
|
||||
parser.add_argument('-s', '--ssid', default='ClubHouse2G')
|
||||
parser.add_argument('-P', '--password', default='ez2remember')
|
||||
parser.add_argument('-g', '--gateway', default='192.168.1.1')
|
||||
|
|
@ -382,6 +387,8 @@ def parse_args():
|
|||
parser.add_argument('--band', default='2.4G')
|
||||
parser.add_argument('-B', '--bandwidth', default='HT20')
|
||||
parser.add_argument('-ps', '--powersave', default='NONE')
|
||||
|
||||
# --- Iperf Defaults (Robustness) ---
|
||||
parser.add_argument('--iperf-period', type=float, default=0.01)
|
||||
parser.add_argument('--iperf-burst', type=int, default=1)
|
||||
parser.add_argument('--iperf-len', type=int, default=1470)
|
||||
|
|
@ -391,11 +398,14 @@ def parse_args():
|
|||
parser.add_argument('--no-iperf', action='store_true')
|
||||
parser.add_argument('--iperf-client', action='store_true')
|
||||
parser.add_argument('--iperf-server', action='store_true')
|
||||
|
||||
# --- Monitor Mode Defaults ---
|
||||
parser.add_argument('-M', '--mode', default='STA')
|
||||
parser.add_argument('-mc', '--monitor-channel', type=int, default=36)
|
||||
parser.add_argument('--csi', dest='csi_enable', action='store_true')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.target != 'all' and not args.start_ip:
|
||||
parser.error("the following arguments are required: --start-ip")
|
||||
if args.config_only and args.flash_only: parser.error("Conflicting modes")
|
||||
|
|
@ -405,6 +415,11 @@ def parse_args():
|
|||
return args
|
||||
|
||||
def extract_device_number(device_path):
|
||||
"""
|
||||
Extracts the integer number from a device path.
|
||||
e.g. /dev/ttyUSB14 -> 14
|
||||
/dev/esp_port_14 -> 14
|
||||
"""
|
||||
match = re.search(r'(\d+)$', device_path)
|
||||
return int(match.group(1)) if match else 0
|
||||
|
||||
|
|
@ -566,8 +581,6 @@ async def run_deployment(args):
|
|||
if not devs: print("No devices found"); return
|
||||
|
||||
# Sort naturally (esp_port_01 before esp_port_10)
|
||||
# We rely on the internal sort of auto_detect or detect_esp32,
|
||||
# but a final sort by string length/digits helps with mixing types.
|
||||
devs.sort(key=lambda d: [int(c) if c.isdigit() else c for c in re.split(r'(\d+)', d.device)])
|
||||
|
||||
print(f"\n{Colors.GREEN}Found {len(devs)} devices{Colors.RESET}")
|
||||
|
|
@ -577,7 +590,16 @@ async def run_deployment(args):
|
|||
|
||||
tasks = []
|
||||
for i, dev in enumerate(devs):
|
||||
offset = extract_device_number(dev.device) if args.devices else i
|
||||
# --- ROBUST IP CALCULATION LOGIC ---
|
||||
if args.ip_device_based:
|
||||
# Mode A: Offset based on physical port number (e.g. 14 for ttyUSB14)
|
||||
offset = extract_device_number(dev.device)
|
||||
print(f" [{dev.device}] Using device-based IP offset: +{offset}")
|
||||
else:
|
||||
# Mode B: Sequential offset based on loop index
|
||||
offset = i
|
||||
print(f" [{dev.device}] Using sequential IP offset: +{offset}")
|
||||
|
||||
target_ip = str(start_ip + offset)
|
||||
tasks.append(UnifiedDeployWorker(dev.device, target_ip, args, project_dir, flash_sem).run())
|
||||
|
||||
|
|
|
|||
|
|
@ -43,6 +43,8 @@ static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_
|
|||
}
|
||||
}
|
||||
}
|
||||
// In event_handler function inside main.c
|
||||
|
||||
else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
|
||||
if (wifi_ctl_get_mode() != WIFI_CTL_MODE_STA) return;
|
||||
|
||||
|
|
@ -61,7 +63,8 @@ static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_
|
|||
}
|
||||
#endif
|
||||
|
||||
iperf_cfg_t cfg = { .flag = IPERF_FLAG_SERVER | IPERF_FLAG_TCP, .sport = 5001 };
|
||||
// iperf_start() will fill this from NVS (including Dest IP and Role)
|
||||
iperf_cfg_t cfg = { 0 };
|
||||
iperf_start(&cfg);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue