Compare commits
No commits in common. "feature/generic-shell" and "master" have entirely different histories.
feature/ge
...
master
|
|
@ -1,3 +1,3 @@
|
|||
idf_component_register(SRCS "app_console.c"
|
||||
INCLUDE_DIRS "."
|
||||
PRIV_REQUIRES console wifi_cfg wifi_controller iperf nvs_flash)
|
||||
PRIV_REQUIRES console wifi_cfg iperf)
|
||||
|
|
|
|||
|
|
@ -4,136 +4,16 @@
|
|||
#include "argtable3/argtable3.h"
|
||||
#include "wifi_cfg.h"
|
||||
#include "iperf.h"
|
||||
#include "wifi_controller.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "nvs.h"
|
||||
#include "nvs_flash.h"
|
||||
#include <string.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
// --- Helper: Prompt Update ---
|
||||
// Updates the "esp32>" vs "esp32*>" prompt based on dirty state
|
||||
static void end_cmd(void) {
|
||||
app_console_update_prompt();
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// COMMAND: nvs (Storage Management)
|
||||
// ============================================================================
|
||||
static struct {
|
||||
struct arg_lit *dump;
|
||||
struct arg_lit *clear_all;
|
||||
struct arg_lit *help;
|
||||
struct arg_end *end;
|
||||
} nvs_args;
|
||||
|
||||
static void print_nvs_key_str(nvs_handle_t h, const char *key, const char *label) {
|
||||
char buf[64] = {0};
|
||||
size_t len = sizeof(buf);
|
||||
if (nvs_get_str(h, key, buf, &len) == ESP_OK) {
|
||||
printf(" %-12s : %s\n", label, buf);
|
||||
} else {
|
||||
printf(" %-12s : <empty>\n", label);
|
||||
}
|
||||
}
|
||||
|
||||
static void print_nvs_key_u32(nvs_handle_t h, const char *key, const char *label) {
|
||||
uint32_t val = 0;
|
||||
if (nvs_get_u32(h, key, &val) == ESP_OK) {
|
||||
printf(" %-12s : %" PRIu32 "\n", label, val);
|
||||
} else {
|
||||
printf(" %-12s : <empty>\n", label);
|
||||
}
|
||||
}
|
||||
|
||||
static void print_nvs_key_u8(nvs_handle_t h, const char *key, const char *label) {
|
||||
uint8_t val = 0;
|
||||
if (nvs_get_u8(h, key, &val) == ESP_OK) {
|
||||
printf(" %-12s : %u\n", label, val);
|
||||
} else {
|
||||
printf(" %-12s : <empty>\n", label);
|
||||
}
|
||||
}
|
||||
|
||||
static int cmd_nvs(int argc, char **argv) {
|
||||
int nerrors = arg_parse(argc, argv, (void **)&nvs_args);
|
||||
if (nerrors > 0) {
|
||||
arg_print_errors(stderr, nvs_args.end, argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (nvs_args.help->count > 0) {
|
||||
printf("Usage: nvs [--dump] [--clear-all]\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// --- CLEAR ALL ---
|
||||
if (nvs_args.clear_all->count > 0) {
|
||||
printf("Erasing ALL settings from NVS...\n");
|
||||
wifi_cfg_clear_credentials();
|
||||
wifi_cfg_clear_monitor_channel();
|
||||
iperf_param_clear();
|
||||
printf("Done. Please reboot.\n");
|
||||
end_cmd();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// --- DUMP ---
|
||||
printf("\n--- [WiFi Config (netcfg)] ---\n");
|
||||
nvs_handle_t h;
|
||||
if (nvs_open("netcfg", NVS_READONLY, &h) == ESP_OK) {
|
||||
print_nvs_key_str(h, "ssid", "SSID");
|
||||
print_nvs_key_str(h, "pass", "Password");
|
||||
print_nvs_key_str(h, "ip", "Static IP");
|
||||
print_nvs_key_str(h, "mask", "Netmask");
|
||||
print_nvs_key_str(h, "gw", "Gateway");
|
||||
print_nvs_key_u8 (h, "dhcp", "DHCP");
|
||||
print_nvs_key_u8 (h, "mon_ch", "Monitor Ch");
|
||||
nvs_close(h);
|
||||
} else {
|
||||
printf("Failed to open 'netcfg' namespace.\n");
|
||||
}
|
||||
|
||||
printf("\n--- [iPerf Config (storage)] ---\n");
|
||||
if (nvs_open("storage", NVS_READONLY, &h) == ESP_OK) {
|
||||
print_nvs_key_str(h, "iperf_dst_ip", "Dest IP");
|
||||
print_nvs_key_u32(h, "iperf_port", "Port");
|
||||
print_nvs_key_u32(h, "iperf_pps", "Target PPS");
|
||||
print_nvs_key_u32(h, "iperf_len", "Packet Len");
|
||||
print_nvs_key_u32(h, "iperf_burst", "Burst");
|
||||
nvs_close(h);
|
||||
} else {
|
||||
printf("Failed to open 'storage' namespace.\n");
|
||||
}
|
||||
printf("\n");
|
||||
end_cmd();
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void register_nvs_cmd(void) {
|
||||
nvs_args.dump = arg_lit0(NULL, "dump", "Show all");
|
||||
nvs_args.clear_all = arg_lit0(NULL, "clear-all", "Factory Reset");
|
||||
nvs_args.help = arg_lit0("h", "help", "Help");
|
||||
nvs_args.end = arg_end(1);
|
||||
|
||||
const esp_console_cmd_t cmd = {
|
||||
.command = "nvs",
|
||||
.help = "Storage Management",
|
||||
.func = &cmd_nvs,
|
||||
.argtable = &nvs_args
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// COMMAND: iperf
|
||||
// ============================================================================
|
||||
static struct {
|
||||
struct arg_lit *start, *stop, *status, *save, *reload;
|
||||
struct arg_lit *clear_nvs;
|
||||
struct arg_str *ip;
|
||||
struct arg_int *port, *pps, *len, *burst;
|
||||
struct arg_lit *start;
|
||||
struct arg_lit *stop;
|
||||
struct arg_lit *status;
|
||||
struct arg_int *pps;
|
||||
struct arg_lit *help;
|
||||
struct arg_end *end;
|
||||
} iperf_args;
|
||||
|
|
@ -146,222 +26,55 @@ static int cmd_iperf(int argc, char **argv) {
|
|||
}
|
||||
|
||||
if (iperf_args.help->count > 0) {
|
||||
printf("Usage: iperf [options]\n");
|
||||
printf(" --start Start traffic\n");
|
||||
printf(" --stop Stop traffic\n");
|
||||
printf(" --save Save config to NVS\n");
|
||||
printf(" --clear-nvs Reset to defaults\n");
|
||||
printf(" -c <ip> Set Dest IP\n");
|
||||
printf(" --pps <n> Set Packets Per Sec\n");
|
||||
printf("Usage: iperf [start|stop|status] [--pps <n>]\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (iperf_args.clear_nvs->count > 0) {
|
||||
iperf_param_clear();
|
||||
printf("iPerf Configuration cleared (Reset to defaults).\n");
|
||||
end_cmd();
|
||||
if (iperf_args.stop->count > 0) {
|
||||
iperf_stop();
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (iperf_args.reload->count > 0) {
|
||||
iperf_param_init();
|
||||
printf("Configuration reloaded from NVS.\n");
|
||||
}
|
||||
|
||||
bool config_changed = false;
|
||||
iperf_cfg_t cfg;
|
||||
iperf_param_get(&cfg);
|
||||
|
||||
if (iperf_args.ip->count > 0) { cfg.dip = inet_addr(iperf_args.ip->sval[0]); config_changed = true; }
|
||||
if (iperf_args.port->count > 0) { cfg.dport = (uint16_t)iperf_args.port->ival[0]; config_changed = true; }
|
||||
if (iperf_args.len->count > 0) { cfg.send_len = (uint32_t)iperf_args.len->ival[0]; config_changed = true; }
|
||||
if (iperf_args.burst->count > 0) { cfg.burst_count = (uint32_t)iperf_args.burst->ival[0]; config_changed = true; }
|
||||
if (iperf_args.pps->count > 0) {
|
||||
if (iperf_args.pps->ival[0] > 0) {
|
||||
cfg.target_pps = (uint32_t)iperf_args.pps->ival[0];
|
||||
config_changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (config_changed) {
|
||||
iperf_param_set(&cfg);
|
||||
printf("RAM configuration updated.\n");
|
||||
}
|
||||
|
||||
if (iperf_args.save->count > 0) {
|
||||
bool changed = false;
|
||||
if (iperf_param_save(&changed) == ESP_OK) {
|
||||
printf(changed ? "Configuration saved to NVS.\n" : "No changes to save (NVS matches RAM).\n");
|
||||
int val = iperf_args.pps->ival[0];
|
||||
if (val > 0) {
|
||||
iperf_set_pps((uint32_t)val);
|
||||
} else {
|
||||
printf("Error saving to NVS.\n");
|
||||
printf("Error: PPS must be > 0\n");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (iperf_args.stop->count > 0) iperf_stop();
|
||||
if (iperf_args.start->count > 0) iperf_start();
|
||||
if (iperf_args.status->count > 0) iperf_print_status();
|
||||
if (iperf_args.status->count > 0) {
|
||||
iperf_print_status();
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (iperf_args.start->count > 0) {
|
||||
// Start using saved NVS config
|
||||
iperf_cfg_t cfg = { .time = 0 };
|
||||
iperf_start(&cfg);
|
||||
return 0;
|
||||
}
|
||||
|
||||
end_cmd();
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void register_iperf_cmd(void) {
|
||||
iperf_args.start = arg_lit0(NULL, "start", "Start");
|
||||
iperf_args.stop = arg_lit0(NULL, "stop", "Stop");
|
||||
iperf_args.status = arg_lit0(NULL, "status", "Status");
|
||||
iperf_args.save = arg_lit0(NULL, "save", "Save");
|
||||
iperf_args.reload = arg_lit0(NULL, "reload", "Reload");
|
||||
iperf_args.clear_nvs = arg_lit0(NULL, "clear-nvs", "Clear NVS");
|
||||
iperf_args.ip = arg_str0("c", "client", "<ip>", "IP");
|
||||
iperf_args.port = arg_int0("p", "port", "<port>", "Port");
|
||||
iperf_args.pps = arg_int0(NULL, "pps", "<n>", "PPS");
|
||||
iperf_args.len = arg_int0(NULL, "len", "<bytes>", "Len");
|
||||
iperf_args.burst = arg_int0(NULL, "burst", "<count>", "Burst");
|
||||
iperf_args.help = arg_lit0("h", "help", "Help");
|
||||
iperf_args.start = arg_lit0(NULL, "start", "Start iperf traffic");
|
||||
iperf_args.stop = arg_lit0(NULL, "stop", "Stop iperf traffic");
|
||||
iperf_args.status = arg_lit0(NULL, "status", "Show current statistics");
|
||||
iperf_args.pps = arg_int0(NULL, "pps", "<n>", "Set packets per second");
|
||||
iperf_args.help = arg_lit0(NULL, "help", "Show help");
|
||||
iperf_args.end = arg_end(20);
|
||||
|
||||
const esp_console_cmd_t cmd = { .command = "iperf", .help = "Traffic Gen", .func = &cmd_iperf, .argtable = &iperf_args };
|
||||
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// COMMAND: monitor
|
||||
// ============================================================================
|
||||
static struct {
|
||||
struct arg_lit *start, *stop, *status, *save, *reload;
|
||||
struct arg_lit *clear_nvs;
|
||||
struct arg_int *channel;
|
||||
struct arg_lit *help;
|
||||
struct arg_end *end;
|
||||
} mon_args;
|
||||
|
||||
static int cmd_monitor(int argc, char **argv) {
|
||||
int nerrors = arg_parse(argc, argv, (void **)&mon_args);
|
||||
if (nerrors > 0) {
|
||||
arg_print_errors(stderr, mon_args.end, argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (mon_args.help->count > 0) {
|
||||
printf("Usage: monitor [--start|--stop] [-c <ch>] [--save|--reload]\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (mon_args.clear_nvs->count > 0) {
|
||||
wifi_ctl_param_clear();
|
||||
printf("Monitor config cleared (Defaulting to Ch 6).\n");
|
||||
end_cmd();
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (mon_args.reload->count > 0) {
|
||||
wifi_ctl_param_reload();
|
||||
printf("Config reloaded from NVS.\n");
|
||||
}
|
||||
|
||||
if (mon_args.channel->count > 0) {
|
||||
wifi_ctl_param_set_monitor_channel((uint8_t)mon_args.channel->ival[0]);
|
||||
printf("Channel set to %d (RAM).\n", mon_args.channel->ival[0]);
|
||||
}
|
||||
|
||||
if (mon_args.save->count > 0) {
|
||||
if (wifi_ctl_param_save()) printf("Configuration saved to NVS.\n");
|
||||
else printf("No changes to save (NVS matches RAM).\n");
|
||||
}
|
||||
|
||||
if (mon_args.stop->count > 0) {
|
||||
wifi_ctl_switch_to_sta(WIFI_BW_HT20);
|
||||
printf("Switched to Station Mode.\n");
|
||||
}
|
||||
|
||||
if (mon_args.start->count > 0) {
|
||||
if (wifi_ctl_switch_to_monitor(0, WIFI_BW_HT20) == ESP_OK) printf("Monitor Mode Started.\n");
|
||||
else printf("Failed to start Monitor Mode.\n");
|
||||
}
|
||||
|
||||
if (mon_args.status->count > 0) {
|
||||
wifi_ctl_mode_t mode = wifi_ctl_get_mode();
|
||||
printf("MONITOR STATUS:\n");
|
||||
printf(" Mode: %s\n", (mode == WIFI_CTL_MODE_MONITOR) ? "MONITOR" : "STATION");
|
||||
printf(" Active: Ch %d\n", (mode == WIFI_CTL_MODE_MONITOR) ? wifi_ctl_get_monitor_channel() : 0);
|
||||
printf(" Staged: Ch %d\n", wifi_ctl_param_get_monitor_channel());
|
||||
printf(" Frames: %" PRIu32 "\n", wifi_ctl_get_monitor_frame_count());
|
||||
}
|
||||
|
||||
end_cmd();
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void register_monitor_cmd(void) {
|
||||
mon_args.start = arg_lit0(NULL, "start", "Start");
|
||||
mon_args.stop = arg_lit0(NULL, "stop", "Stop");
|
||||
mon_args.status = arg_lit0(NULL, "status", "Status");
|
||||
mon_args.save = arg_lit0(NULL, "save", "Save");
|
||||
mon_args.reload = arg_lit0(NULL, "reload", "Reload");
|
||||
mon_args.clear_nvs = arg_lit0(NULL, "clear-nvs", "Clear NVS");
|
||||
mon_args.channel = arg_int0("c", "channel", "<n>", "Chan");
|
||||
mon_args.help = arg_lit0("h", "help", "Help");
|
||||
mon_args.end = arg_end(20);
|
||||
|
||||
const esp_console_cmd_t cmd = { .command = "monitor", .help = "Monitor Mode", .func = &cmd_monitor, .argtable = &mon_args };
|
||||
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// COMMAND: scan
|
||||
// ============================================================================
|
||||
static struct {
|
||||
struct arg_lit *help;
|
||||
struct arg_end *end;
|
||||
} scan_args;
|
||||
|
||||
static int cmd_scan(int argc, char **argv) {
|
||||
int nerrors = arg_parse(argc, argv, (void **)&scan_args);
|
||||
if (nerrors > 0) {
|
||||
arg_print_errors(stderr, scan_args.end, argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (scan_args.help->count > 0) {
|
||||
printf("Usage: scan\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
printf("Starting WiFi Scan...\n");
|
||||
|
||||
// Force STA mode to allow scanning
|
||||
wifi_ctl_switch_to_sta(WIFI_BW_HT20);
|
||||
|
||||
wifi_scan_config_t scan_config = { .show_hidden = true };
|
||||
esp_err_t err = esp_wifi_scan_start(&scan_config, true);
|
||||
if (err != ESP_OK) {
|
||||
printf("Scan failed: %s\n", esp_err_to_name(err));
|
||||
return 1;
|
||||
}
|
||||
|
||||
uint16_t ap_count = 0;
|
||||
esp_wifi_scan_get_ap_num(&ap_count);
|
||||
printf("Found %d APs:\n", ap_count);
|
||||
|
||||
if (ap_count > 0) {
|
||||
wifi_ap_record_t *ap_list = (wifi_ap_record_t *)malloc(sizeof(wifi_ap_record_t) * ap_count);
|
||||
if (ap_list) {
|
||||
esp_wifi_scan_get_ap_records(&ap_count, ap_list);
|
||||
printf("%-32s | %-4s | %-4s | %-3s\n", "SSID", "RSSI", "CH", "Auth");
|
||||
printf("----------------------------------------------------------\n");
|
||||
for (int i = 0; i < ap_count; i++) {
|
||||
printf("%-32s | %-4d | %-4d | %d\n", (char *)ap_list[i].ssid, ap_list[i].rssi, ap_list[i].primary, ap_list[i].authmode);
|
||||
}
|
||||
free(ap_list);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void register_scan_cmd(void) {
|
||||
scan_args.help = arg_lit0("h", "help", "Help");
|
||||
scan_args.end = arg_end(1);
|
||||
const esp_console_cmd_t cmd = { .command = "scan", .help = "WiFi Scan", .func = &cmd_scan, .argtable = &scan_args };
|
||||
const esp_console_cmd_t cmd = {
|
||||
.command = "iperf",
|
||||
.help = "Control iperf traffic generator",
|
||||
.hint = NULL,
|
||||
.func = &cmd_iperf,
|
||||
.argtable = &iperf_args
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
|
||||
}
|
||||
|
||||
|
|
@ -373,7 +86,6 @@ static struct {
|
|||
struct arg_str *pass;
|
||||
struct arg_str *ip;
|
||||
struct arg_lit *dhcp;
|
||||
struct arg_lit *clear_nvs;
|
||||
struct arg_lit *help;
|
||||
struct arg_end *end;
|
||||
} wifi_args;
|
||||
|
|
@ -386,13 +98,7 @@ static int cmd_wifi_config(int argc, char **argv) {
|
|||
}
|
||||
|
||||
if (wifi_args.help->count > 0) {
|
||||
printf("Usage: wifi_config -s <ssid> [-p <pass>] [--clear-nvs]\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (wifi_args.clear_nvs->count > 0) {
|
||||
wifi_cfg_clear_credentials();
|
||||
printf("WiFi Credentials CLEARED from NVS.\n");
|
||||
printf("Usage: wifi_config -s <ssid> -p <pass> [-i <ip>] [-d]\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
|
@ -403,6 +109,7 @@ static int cmd_wifi_config(int argc, char **argv) {
|
|||
|
||||
const char* ssid = wifi_args.ssid->sval[0];
|
||||
const char* pass = (wifi_args.pass->count > 0) ? wifi_args.pass->sval[0] : "";
|
||||
|
||||
const char* ip = (wifi_args.ip->count > 0) ? wifi_args.ip->sval[0] : NULL;
|
||||
bool dhcp = (wifi_args.dhcp->count > 0);
|
||||
|
||||
|
|
@ -413,7 +120,10 @@ static int cmd_wifi_config(int argc, char **argv) {
|
|||
if (ip) {
|
||||
char mask[] = "255.255.255.0";
|
||||
char gw[32];
|
||||
|
||||
// FIXED: Use strlcpy instead of strncpy to prevent truncation warnings
|
||||
strlcpy(gw, ip, sizeof(gw));
|
||||
|
||||
char *last_dot = strrchr(gw, '.');
|
||||
if (last_dot) strcpy(last_dot, ".1");
|
||||
|
||||
|
|
@ -429,22 +139,24 @@ static int cmd_wifi_config(int argc, char **argv) {
|
|||
}
|
||||
|
||||
static void register_wifi_cmd(void) {
|
||||
wifi_args.ssid = arg_str0("s", "ssid", "<ssid>", "SSID");
|
||||
wifi_args.pass = arg_str0("p", "password", "<pass>", "Pass");
|
||||
wifi_args.ssid = arg_str0("s", "ssid", "<ssid>", "WiFi SSID");
|
||||
wifi_args.pass = arg_str0("p", "password", "<pass>", "WiFi Password");
|
||||
wifi_args.ip = arg_str0("i", "ip", "<ip>", "Static IP");
|
||||
wifi_args.dhcp = arg_lit0("d", "dhcp", "Enable DHCP");
|
||||
wifi_args.clear_nvs = arg_lit0(NULL, "clear-nvs", "Clear NVS");
|
||||
wifi_args.help = arg_lit0("h", "help", "Help");
|
||||
wifi_args.help = arg_lit0("h", "help", "Show help");
|
||||
wifi_args.end = arg_end(20);
|
||||
|
||||
const esp_console_cmd_t cmd = { .command = "wifi_config", .help = "Configure WiFi", .func = &cmd_wifi_config, .argtable = &wifi_args };
|
||||
const esp_console_cmd_t cmd = {
|
||||
.command = "wifi_config",
|
||||
.help = "Configure WiFi credentials",
|
||||
.hint = NULL,
|
||||
.func = &cmd_wifi_config,
|
||||
.argtable = &wifi_args
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
|
||||
}
|
||||
|
||||
void app_console_register_commands(void) {
|
||||
register_iperf_cmd();
|
||||
register_monitor_cmd();
|
||||
register_scan_cmd();
|
||||
register_wifi_cmd();
|
||||
register_nvs_cmd();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,6 @@ extern "C" {
|
|||
* @brief Register application-specific console commands
|
||||
*/
|
||||
void app_console_register_commands(void);
|
||||
// Implemented in main.c - updates prompt based on NVS dirty state
|
||||
void app_console_update_prompt(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,61 +20,49 @@ static const char *TAG = "GPS_SYNC";
|
|||
static uart_port_t gps_uart_num = UART_NUM_1;
|
||||
static int64_t monotonic_offset_us = 0;
|
||||
static volatile int64_t last_pps_monotonic = 0;
|
||||
static volatile time_t next_pps_gps_second = 0;
|
||||
static bool gps_has_fix = false;
|
||||
static bool use_gps_for_logs = false;
|
||||
static SemaphoreHandle_t sync_mutex;
|
||||
static volatile bool force_sync_update = true;
|
||||
|
||||
// PPS interrupt
|
||||
// Stores the monotonic time of the rising edge of the PPS signal
|
||||
static void IRAM_ATTR pps_isr_handler(void* arg) {
|
||||
// Capture time immediately
|
||||
int64_t now = esp_timer_get_time();
|
||||
last_pps_monotonic = now;
|
||||
static bool onetime = true;
|
||||
last_pps_monotonic = esp_timer_get_time();
|
||||
if (onetime) {
|
||||
esp_rom_printf("PPS connected!\n");
|
||||
onetime = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Parse GPS time from NMEA (GPRMC or GNRMC)
|
||||
// Parse GPS time from NMEA
|
||||
static bool parse_gprmc(const char* nmea, struct tm* tm_out, bool* valid) {
|
||||
// Check Header
|
||||
if (strncmp(nmea, "$GPRMC", 6) != 0 && strncmp(nmea, "$GNRMC", 6) != 0) return false;
|
||||
|
||||
// Find Time Field
|
||||
char *p = strchr(nmea, ',');
|
||||
if (!p) return false;
|
||||
p++; // Move past comma
|
||||
|
||||
p++;
|
||||
int hour, min, sec;
|
||||
// Scan %2d%2d%2d effectively, using floats can be safer for sub-seconds but int is fine for PPS
|
||||
if (sscanf(p, "%2d%2d%2d", &hour, &min, &sec) != 3) return false;
|
||||
|
||||
// Find Status Field (A=Active/Valid, V=Void)
|
||||
p = strchr(p, ',');
|
||||
if (!p) return false;
|
||||
p++;
|
||||
*valid = (*p == 'A');
|
||||
|
||||
// Skip Latitude, N/S, Longitude, E/W, Speed, Course (6 fields)
|
||||
for (int i = 0; i < 7; i++) {
|
||||
p = strchr(p, ',');
|
||||
if (!p) return false;
|
||||
p++;
|
||||
}
|
||||
|
||||
// Date Field
|
||||
int day, month, year;
|
||||
if (sscanf(p, "%2d%2d%2d", &day, &month, &year) != 3) return false;
|
||||
|
||||
// Adjust Year (NMEA provides 2 digits)
|
||||
year += (year < 80) ? 2000 : 1900;
|
||||
|
||||
tm_out->tm_sec = sec;
|
||||
tm_out->tm_min = min;
|
||||
tm_out->tm_hour = hour;
|
||||
tm_out->tm_mday = day;
|
||||
tm_out->tm_mon = month - 1; // tm_mon is 0-11
|
||||
tm_out->tm_year = year - 1900; // tm_year is years since 1900
|
||||
tm_out->tm_mon = month - 1;
|
||||
tm_out->tm_year = year - 1900;
|
||||
tm_out->tm_isdst = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -83,159 +71,115 @@ void gps_force_next_update(void) {
|
|||
ESP_LOGW(TAG, "Requesting forced GPS sync update");
|
||||
}
|
||||
|
||||
// Helper to convert struct tm to time_t (UTC assumption)
|
||||
// Uses standard mktime but we assume TZ is handled or default is UTC
|
||||
static time_t timegm_impl(struct tm *tm) {
|
||||
time_t t = mktime(tm);
|
||||
return t;
|
||||
}
|
||||
|
||||
static void gps_task(void* arg) {
|
||||
uint8_t d_buf[64];
|
||||
char line[128];
|
||||
int pos = 0;
|
||||
static int log_counter = 0;
|
||||
|
||||
// Ensure timezone is UTC for correct time math
|
||||
setenv("TZ", "UTC", 1);
|
||||
tzset();
|
||||
|
||||
while (1) {
|
||||
// Read from UART with a reasonable timeout
|
||||
int len = uart_read_bytes(gps_uart_num, d_buf, sizeof(d_buf), pdMS_TO_TICKS(100));
|
||||
|
||||
if (len > 0) {
|
||||
for (int i = 0; i < len; i++) {
|
||||
uint8_t data = d_buf[i];
|
||||
|
||||
// Buffer the line
|
||||
if (data == '\n' || data == '\r') {
|
||||
if (pos > 0) {
|
||||
if (data == '\n') {
|
||||
line[pos] = '\0';
|
||||
struct tm gps_tm;
|
||||
bool valid_fix;
|
||||
|
||||
// Try to parse GPRMC
|
||||
if (parse_gprmc(line, &gps_tm, &valid_fix)) {
|
||||
if (valid_fix) {
|
||||
// 1. Convert Parsed Time to Seconds
|
||||
time_t gps_time_sec = timegm_impl(&gps_tm);
|
||||
|
||||
// 2. Critical Section: Read PPS Timestamp
|
||||
bool valid;
|
||||
if (parse_gprmc(line, &gps_tm, &valid)) {
|
||||
if (valid) {
|
||||
time_t gps_time = mktime(&gps_tm);
|
||||
xSemaphoreTake(sync_mutex, portMAX_DELAY);
|
||||
int64_t last_pps = last_pps_monotonic;
|
||||
next_pps_gps_second = gps_time + 1;
|
||||
xSemaphoreGive(sync_mutex);
|
||||
|
||||
// 3. Analyze Timing
|
||||
int64_t now = esp_timer_get_time();
|
||||
int64_t age_us = now - last_pps;
|
||||
|
||||
// The PPS pulse described by this message should have happened
|
||||
// fairly recently (e.g., within the last 800ms).
|
||||
// If age > 900ms, we likely missed the pulse or UART is lagging badly.
|
||||
if (last_pps > 0 && age_us < 900000) {
|
||||
|
||||
// Calculate Offset
|
||||
// GPS Time (in microseconds) = Seconds * 1M
|
||||
int64_t gps_time_us = (int64_t)gps_time_sec * 1000000LL;
|
||||
|
||||
// Offset = GPS_Timestamp - Monotonic_Timestamp
|
||||
// This means: GPS = Monotonic + Offset
|
||||
int64_t new_offset = gps_time_us - last_pps;
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(300));
|
||||
xSemaphoreTake(sync_mutex, portMAX_DELAY);
|
||||
if (last_pps_monotonic > 0) {
|
||||
int64_t gps_us = (int64_t)next_pps_gps_second * 1000000LL;
|
||||
int64_t new_offset = gps_us - last_pps_monotonic;
|
||||
if (monotonic_offset_us == 0 || force_sync_update) {
|
||||
// Hard Snap (First fix or Forced)
|
||||
monotonic_offset_us = new_offset;
|
||||
if (force_sync_update) {
|
||||
ESP_LOGW(TAG, "GPS SNAP: Offset forced to %" PRIi64 " us", monotonic_offset_us);
|
||||
ESP_LOGW(TAG, "GPS sync SNAP: Offset forced to %" PRIi64 " us", monotonic_offset_us);
|
||||
force_sync_update = false;
|
||||
log_counter = 0; // Force immediate log
|
||||
log_counter = 0;
|
||||
}
|
||||
} else {
|
||||
// Exponential Smoothing (Filter Jitter)
|
||||
// 90% old, 10% new
|
||||
monotonic_offset_us = (monotonic_offset_us * 9 + new_offset) / 10;
|
||||
}
|
||||
gps_has_fix = true;
|
||||
xSemaphoreGive(sync_mutex);
|
||||
|
||||
// Periodic Logging
|
||||
if (log_counter <= 0) {
|
||||
ESP_LOGI(TAG, "GPS Sync: %02d:%02d:%02d | Offset: %" PRIi64 " us | PPS Age: %" PRIi64 " ms",
|
||||
if (log_counter == 0) {
|
||||
ESP_LOGI(TAG, "GPS sync: %04d-%02d-%02d %02d:%02d:%02d, offset=%" PRIi64 " us",
|
||||
gps_tm.tm_year + 1900, gps_tm.tm_mon + 1, gps_tm.tm_mday,
|
||||
gps_tm.tm_hour, gps_tm.tm_min, gps_tm.tm_sec,
|
||||
monotonic_offset_us, age_us / 1000);
|
||||
log_counter = 10; // Log every 10 valid fixes
|
||||
}
|
||||
log_counter--;
|
||||
|
||||
} else {
|
||||
// PPS signal lost or not correlated
|
||||
if (log_counter <= 0) {
|
||||
ESP_LOGW(TAG, "GPS valid but PPS missing/old (Age: %" PRIi64 " ms)", age_us / 1000);
|
||||
log_counter = 10;
|
||||
monotonic_offset_us);
|
||||
log_counter = 60;
|
||||
}
|
||||
log_counter--;
|
||||
}
|
||||
xSemaphoreGive(sync_mutex);
|
||||
} else {
|
||||
gps_has_fix = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
pos = 0;
|
||||
} else {
|
||||
if (pos < sizeof(line) - 1) {
|
||||
} else if (pos < sizeof(line) - 1) {
|
||||
line[pos++] = data;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void gps_sync_init(const gps_sync_config_t *config, bool use_gps_log_timestamps) {
|
||||
ESP_LOGI(TAG, "Initializing GPS Sync (UART %d, PPS GPIO %d)", config->uart_port, config->pps_pin);
|
||||
ESP_LOGI(TAG, "Checking for GPS PPS signal on GPIO %d...", config->pps_pin);
|
||||
|
||||
// 1. Initial PPS Pin Check (Input Mode)
|
||||
// We poll briefly just to see if the pin is physically toggling before committing resources.
|
||||
gpio_config_t pps_poll_conf = {
|
||||
// 1. Configure PPS pin as Input to sense signal
|
||||
gpio_config_t pps_conf = {
|
||||
.pin_bit_mask = (1ULL << config->pps_pin),
|
||||
.mode = GPIO_MODE_INPUT,
|
||||
.pull_up_en = GPIO_PULLUP_DISABLE,
|
||||
.pull_down_en = GPIO_PULLDOWN_DISABLE,
|
||||
.pull_down_en = GPIO_PULLDOWN_DISABLE, // High-Z to detect active driving
|
||||
.intr_type = GPIO_INTR_DISABLE
|
||||
};
|
||||
ESP_ERROR_CHECK(gpio_config(&pps_poll_conf));
|
||||
ESP_ERROR_CHECK(gpio_config(&pps_conf));
|
||||
|
||||
// 2. Poll for ~3 seconds to detect ANY edge transition
|
||||
bool pps_detected = false;
|
||||
int start_level = gpio_get_level(config->pps_pin);
|
||||
// Poll for up to 2 seconds
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
if (gpio_get_level(config->pps_pin) != start_level) {
|
||||
|
||||
// Poll loop: 3000 iterations * 1ms = 3 seconds
|
||||
for (int i = 0; i < 3000; i++) {
|
||||
int current_level = gpio_get_level(config->pps_pin);
|
||||
if (current_level != start_level) {
|
||||
pps_detected = true;
|
||||
break;
|
||||
break; // Signal found!
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(1));
|
||||
}
|
||||
|
||||
if (!pps_detected) {
|
||||
ESP_LOGW(TAG, "No PPS signal detected on GPIO %d during boot check.", config->pps_pin);
|
||||
// We continue anyway, as GPS might gain lock later.
|
||||
} else {
|
||||
ESP_LOGI(TAG, "PPS signal activity detected.");
|
||||
printf("GPS PPS not found over GPIO with pin number %d\n", config->pps_pin);
|
||||
ESP_LOGW(TAG, "GPS initialization aborted due to lack of PPS signal.");
|
||||
return; // ABORT INITIALIZATION
|
||||
}
|
||||
|
||||
// 2. Setup Globals
|
||||
ESP_LOGI(TAG, "PPS signal detected! Initializing GPS subsystem...");
|
||||
|
||||
// 3. Proceed with Full Initialization
|
||||
gps_uart_num = config->uart_port;
|
||||
use_gps_for_logs = use_gps_log_timestamps;
|
||||
|
||||
gps_force_next_update();
|
||||
sync_mutex = xSemaphoreCreateMutex();
|
||||
|
||||
if (use_gps_log_timestamps) {
|
||||
ESP_LOGI(TAG, "ESP_LOG timestamps: GPS time in seconds.milliseconds format");
|
||||
esp_log_set_vprintf(gps_log_vprintf);
|
||||
}
|
||||
|
||||
// 3. Setup UART
|
||||
sync_mutex = xSemaphoreCreateMutex();
|
||||
|
||||
uart_config_t uart_config = {
|
||||
.baud_rate = GPS_BAUD_RATE,
|
||||
.data_bits = UART_DATA_8_BITS,
|
||||
|
|
@ -247,48 +191,49 @@ void gps_sync_init(const gps_sync_config_t *config, bool use_gps_log_timestamps)
|
|||
|
||||
ESP_ERROR_CHECK(uart_driver_install(config->uart_port, UART_BUF_SIZE, 0, 0, NULL, 0));
|
||||
ESP_ERROR_CHECK(uart_param_config(config->uart_port, &uart_config));
|
||||
ESP_ERROR_CHECK(uart_set_pin(config->uart_port, config->tx_pin, config->rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
|
||||
|
||||
// 4. Setup PPS Interrupt (Rising Edge)
|
||||
gpio_config_t pps_intr_conf = {
|
||||
ESP_ERROR_CHECK(uart_set_pin(config->uart_port,
|
||||
config->tx_pin,
|
||||
config->rx_pin,
|
||||
UART_PIN_NO_CHANGE,
|
||||
UART_PIN_NO_CHANGE));
|
||||
|
||||
// Re-configure PPS for Interrupts (Posedge)
|
||||
gpio_config_t io_conf = {
|
||||
.intr_type = GPIO_INTR_POSEDGE,
|
||||
.mode = GPIO_MODE_INPUT,
|
||||
.pin_bit_mask = (1ULL << config->pps_pin),
|
||||
.pull_up_en = GPIO_PULLUP_DISABLE, // High-Z usually best for driven PPS
|
||||
.pull_up_en = GPIO_PULLUP_ENABLE,
|
||||
.pull_down_en = GPIO_PULLDOWN_DISABLE,
|
||||
};
|
||||
ESP_ERROR_CHECK(gpio_config(&pps_intr_conf));
|
||||
ESP_ERROR_CHECK(gpio_config(&io_conf));
|
||||
|
||||
// Install ISR service if not already done by other components
|
||||
// Note: If you have other components using GPIO ISRs, ensure flags match or install is called only once.
|
||||
gpio_install_isr_service(0);
|
||||
ESP_ERROR_CHECK(gpio_isr_handler_add(config->pps_pin, pps_isr_handler, NULL));
|
||||
|
||||
// 5. Start Processor Task
|
||||
xTaskCreate(gps_task, "gps_task", 4096, NULL, 5, NULL);
|
||||
|
||||
ESP_LOGI(TAG, "GPS sync initialized (UART=%d, RX=%d, TX=%d, PPS=%d)",
|
||||
config->uart_port, config->rx_pin, config->tx_pin, config->pps_pin);
|
||||
}
|
||||
|
||||
gps_timestamp_t gps_get_timestamp(void) {
|
||||
gps_timestamp_t ts;
|
||||
// Capture raw monotonic time
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts.mono_ts);
|
||||
|
||||
// Calculate microseconds
|
||||
xSemaphoreTake(sync_mutex, portMAX_DELAY);
|
||||
ts.monotonic_us = (int64_t)ts.mono_ts.tv_sec * 1000000LL + ts.mono_ts.tv_nsec / 1000;
|
||||
ts.monotonic_ms = ts.monotonic_us / 1000;
|
||||
|
||||
// Apply Offset safely
|
||||
xSemaphoreTake(sync_mutex, portMAX_DELAY);
|
||||
ts.gps_us = ts.monotonic_us + monotonic_offset_us;
|
||||
ts.gps_ms = ts.gps_us / 1000;
|
||||
ts.synced = gps_has_fix;
|
||||
xSemaphoreGive(sync_mutex);
|
||||
|
||||
ts.gps_ms = ts.gps_us / 1000;
|
||||
return ts;
|
||||
}
|
||||
|
||||
int64_t gps_get_monotonic_ms(void) {
|
||||
return esp_timer_get_time() / 1000;
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (int64_t)ts.tv_sec * 1000LL + ts.tv_nsec / 1000000;
|
||||
}
|
||||
|
||||
bool gps_is_synced(void) {
|
||||
|
|
@ -308,7 +253,6 @@ int gps_log_vprintf(const char *fmt, va_list args) {
|
|||
|
||||
if (use_gps_for_logs) {
|
||||
char *timestamp_start = NULL;
|
||||
// Find ESP log timestamp format "(1234)"
|
||||
for (int i = 0; buffer[i] != '\0' && i < sizeof(buffer) - 20; i++) {
|
||||
if ((buffer[i] == 'I' || buffer[i] == 'W' || buffer[i] == 'E' ||
|
||||
buffer[i] == 'D' || buffer[i] == 'V') &&
|
||||
|
|
@ -325,35 +269,24 @@ int gps_log_vprintf(const char *fmt, va_list args) {
|
|||
if (sscanf(timestamp_start, "%lu", &monotonic_log_ms) == 1) {
|
||||
char reformatted[512];
|
||||
size_t prefix_len = timestamp_start - buffer;
|
||||
|
||||
// Copy prefix "I "
|
||||
if (prefix_len > sizeof(reformatted)) prefix_len = sizeof(reformatted);
|
||||
memcpy(reformatted, buffer, prefix_len);
|
||||
|
||||
int decimal_len = 0;
|
||||
|
||||
if (gps_has_fix) {
|
||||
int64_t log_mono_us = (int64_t)monotonic_log_ms * 1000;
|
||||
int64_t log_gps_us = log_mono_us + monotonic_offset_us;
|
||||
|
||||
// Split into seconds and fractional ms
|
||||
uint64_t gps_sec = log_gps_us / 1000000;
|
||||
uint32_t gps_ms = (log_gps_us % 1000000) / 1000;
|
||||
|
||||
// Overwrite timestamp with GPS time e.g., "+1703000000.123"
|
||||
decimal_len = snprintf(reformatted + prefix_len,
|
||||
sizeof(reformatted) - prefix_len,
|
||||
"+%" PRIu64 ".%03lu", gps_sec, gps_ms);
|
||||
} else {
|
||||
// Fallback: Keep monotonic but mark as unsynced
|
||||
uint32_t sec = monotonic_log_ms / 1000;
|
||||
uint32_t ms = monotonic_log_ms % 1000;
|
||||
decimal_len = snprintf(reformatted + prefix_len,
|
||||
sizeof(reformatted) - prefix_len,
|
||||
"*%lu.%03lu", (unsigned long)sec, (unsigned long)ms);
|
||||
"*%lu.%03lu", sec, ms);
|
||||
}
|
||||
|
||||
// Copy remainder of message
|
||||
strcpy(reformatted + prefix_len + decimal_len, timestamp_end);
|
||||
return printf("%s", reformatted);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,20 +23,6 @@
|
|||
|
||||
static const char *TAG = "iperf";
|
||||
|
||||
// --- NVS Keys ---
|
||||
#define NVS_KEY_IPERF_ENABLE "iperf_enabled"
|
||||
#define NVS_KEY_IPERF_PPS "iperf_pps"
|
||||
#define NVS_KEY_IPERF_ROLE "iperf_role"
|
||||
#define NVS_KEY_IPERF_DST_IP "iperf_dst_ip"
|
||||
#define NVS_KEY_IPERF_PORT "iperf_port"
|
||||
#define NVS_KEY_IPERF_PROTO "iperf_proto"
|
||||
#define NVS_KEY_IPERF_BURST "iperf_burst"
|
||||
#define NVS_KEY_IPERF_LEN "iperf_len"
|
||||
|
||||
// --- Global Config State ---
|
||||
static iperf_cfg_t s_staging_cfg = {0}; // The "Running" Config
|
||||
static bool s_staging_initialized = false;
|
||||
|
||||
static EventGroupHandle_t s_iperf_event_group = NULL;
|
||||
#define IPERF_IP_READY_BIT (1 << 0)
|
||||
#define IPERF_STOP_REQ_BIT (1 << 1)
|
||||
|
|
@ -44,7 +30,6 @@ static EventGroupHandle_t s_iperf_event_group = NULL;
|
|||
#define RATE_CHECK_INTERVAL_US 500000
|
||||
#define MIN_PACING_INTERVAL_US 100
|
||||
|
||||
// --- Runtime Control ---
|
||||
typedef struct {
|
||||
iperf_cfg_t cfg;
|
||||
bool finish;
|
||||
|
|
@ -52,17 +37,20 @@ typedef struct {
|
|||
uint8_t *buffer;
|
||||
} iperf_ctrl_t;
|
||||
|
||||
static iperf_ctrl_t s_iperf_ctrl = {0}; // The "Active" Config (while task runs)
|
||||
static iperf_ctrl_t s_iperf_ctrl = {0};
|
||||
static TaskHandle_t s_iperf_task_handle = NULL;
|
||||
static bool s_reload_req = false;
|
||||
static iperf_cfg_t s_next_cfg; // Holding area for the new config
|
||||
static bool s_reload_req = false; // Flag to trigger internal restart
|
||||
|
||||
// Global Stats Tracker
|
||||
static iperf_stats_t s_stats = {0};
|
||||
|
||||
// --- Session Persistence Variables ---
|
||||
static int64_t s_session_start_time = 0;
|
||||
static int64_t s_session_end_time = 0;
|
||||
static uint64_t s_session_packets = 0;
|
||||
|
||||
// --- FSM State & Stats ---
|
||||
// --- State Duration & Edge Counters ---
|
||||
typedef enum {
|
||||
IPERF_STATE_IDLE = 0,
|
||||
IPERF_STATE_TX,
|
||||
|
|
@ -70,8 +58,6 @@ typedef enum {
|
|||
IPERF_STATE_TX_STALLED
|
||||
} iperf_fsm_state_t;
|
||||
|
||||
static iperf_fsm_state_t s_current_fsm_state = IPERF_STATE_IDLE;
|
||||
|
||||
static int64_t s_time_tx_us = 0;
|
||||
static int64_t s_time_slow_us = 0;
|
||||
static int64_t s_time_stalled_us = 0;
|
||||
|
|
@ -80,207 +66,35 @@ static uint32_t s_edge_tx = 0;
|
|||
static uint32_t s_edge_slow = 0;
|
||||
static uint32_t s_edge_stalled = 0;
|
||||
|
||||
static iperf_fsm_state_t s_current_fsm_state = IPERF_STATE_IDLE;
|
||||
|
||||
static esp_event_handler_instance_t instance_any_id;
|
||||
static esp_event_handler_instance_t instance_got_ip;
|
||||
|
||||
// --- Packet Structures ---
|
||||
typedef struct {
|
||||
int32_t id;
|
||||
uint32_t tv_sec;
|
||||
uint32_t tv_usec;
|
||||
int32_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;
|
||||
|
||||
|
||||
// --- Helper: Defaults ---
|
||||
static void set_defaults(iperf_cfg_t *cfg) {
|
||||
memset(cfg, 0, sizeof(iperf_cfg_t));
|
||||
cfg->flag = IPERF_FLAG_CLIENT | IPERF_FLAG_UDP;
|
||||
cfg->dip = 0; // 0.0.0.0
|
||||
cfg->dport = IPERF_DEFAULT_PORT;
|
||||
cfg->time = 0; // Infinite
|
||||
cfg->target_pps = 100; // Default 100 PPS
|
||||
cfg->burst_count = 1;
|
||||
cfg->send_len = IPERF_UDP_TX_LEN;
|
||||
}
|
||||
|
||||
// --- Parameter Management (Init / Load / Save / Get / Set) ---
|
||||
|
||||
static void trim_whitespace(char *str) {
|
||||
char *end = str + strlen(str) - 1;
|
||||
while(end > str && isspace((unsigned char)*end)) end--;
|
||||
*(end+1) = 0;
|
||||
}
|
||||
|
||||
// Clear NVS
|
||||
|
||||
void iperf_param_clear(void) {
|
||||
nvs_handle_t h;
|
||||
if (nvs_open("storage", NVS_READWRITE, &h) == ESP_OK) {
|
||||
nvs_erase_key(h, NVS_KEY_IPERF_PPS);
|
||||
nvs_erase_key(h, NVS_KEY_IPERF_BURST);
|
||||
nvs_erase_key(h, NVS_KEY_IPERF_LEN);
|
||||
nvs_erase_key(h, NVS_KEY_IPERF_PORT);
|
||||
nvs_erase_key(h, NVS_KEY_IPERF_DST_IP);
|
||||
nvs_commit(h);
|
||||
nvs_close(h);
|
||||
ESP_LOGI(TAG, "iPerf NVS configuration cleared.");
|
||||
}
|
||||
|
||||
// Reset RAM to defaults to match the "Empty" NVS state
|
||||
set_defaults(&s_staging_cfg);
|
||||
}
|
||||
|
||||
void iperf_param_init(void) {
|
||||
if (s_staging_initialized) return;
|
||||
|
||||
set_defaults(&s_staging_cfg);
|
||||
|
||||
// Load from NVS
|
||||
nvs_handle_t h;
|
||||
if (nvs_open("storage", NVS_READONLY, &h) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Loading saved config from NVS...");
|
||||
|
||||
uint32_t val;
|
||||
// Direct Load: No conversion needed
|
||||
if (nvs_get_u32(h, NVS_KEY_IPERF_PPS, &val) == ESP_OK && val > 0) {
|
||||
s_staging_cfg.target_pps = val;
|
||||
}
|
||||
|
||||
if (nvs_get_u32(h, NVS_KEY_IPERF_BURST, &val) == ESP_OK) s_staging_cfg.burst_count = val;
|
||||
if (nvs_get_u32(h, NVS_KEY_IPERF_LEN, &val) == ESP_OK) s_staging_cfg.send_len = val;
|
||||
if (nvs_get_u32(h, NVS_KEY_IPERF_PORT, &val) == ESP_OK) s_staging_cfg.dport = (uint16_t)val;
|
||||
|
||||
size_t req;
|
||||
if (nvs_get_str(h, NVS_KEY_IPERF_DST_IP, NULL, &req) == ESP_OK) {
|
||||
char *ip_str = malloc(req);
|
||||
if (ip_str) {
|
||||
nvs_get_str(h, NVS_KEY_IPERF_DST_IP, ip_str, &req);
|
||||
trim_whitespace(ip_str);
|
||||
s_staging_cfg.dip = inet_addr(ip_str);
|
||||
free(ip_str);
|
||||
}
|
||||
}
|
||||
nvs_close(h);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "No saved config found, using defaults.");
|
||||
}
|
||||
|
||||
s_staging_initialized = true;
|
||||
}
|
||||
|
||||
void iperf_param_get(iperf_cfg_t *out_cfg) {
|
||||
if (!s_staging_initialized) iperf_param_init();
|
||||
*out_cfg = s_staging_cfg;
|
||||
}
|
||||
|
||||
void iperf_param_set(const iperf_cfg_t *new_cfg) {
|
||||
if (!s_staging_initialized) iperf_param_init();
|
||||
|
||||
// Update Staging
|
||||
s_staging_cfg = *new_cfg;
|
||||
|
||||
// Hot Reload Logic
|
||||
if (s_iperf_task_handle) {
|
||||
ESP_LOGI(TAG, "Hot reloading parameters...");
|
||||
s_iperf_ctrl.cfg = s_staging_cfg;
|
||||
s_reload_req = true;
|
||||
|
||||
// Stop current internal loop to pick up new config
|
||||
if (s_iperf_event_group) xEventGroupSetBits(s_iperf_event_group, IPERF_STOP_REQ_BIT);
|
||||
// --- Helper: Pattern Initialization ---
|
||||
// Fills buffer with 0-9 cyclic ASCII pattern (matches iperf2 "pattern" function)
|
||||
static void iperf_pattern(uint8_t *buf, uint32_t len) {
|
||||
for (uint32_t i = 0; i < len; i++) {
|
||||
buf[i] = (i % 10) + '0';
|
||||
}
|
||||
}
|
||||
|
||||
// --- Dirty Check ---
|
||||
bool iperf_param_is_unsaved(void) {
|
||||
if (!s_staging_initialized) return false;
|
||||
// --- Helper: Generate Client Header ---
|
||||
// Modified to set all zeros except HEADER_SEQNO64B
|
||||
static void iperf_generate_client_hdr(iperf_cfg_t *cfg, client_hdr_v1 *hdr) {
|
||||
// Zero out the entire structure
|
||||
memset(hdr, 0, sizeof(client_hdr_v1));
|
||||
|
||||
nvs_handle_t h;
|
||||
if (nvs_open("storage", NVS_READONLY, &h) != ESP_OK) return false;
|
||||
|
||||
uint32_t val;
|
||||
bool match = true;
|
||||
|
||||
// Direct Compare: No conversion needed
|
||||
uint32_t saved_pps = 0;
|
||||
if (nvs_get_u32(h, NVS_KEY_IPERF_PPS, &val) == ESP_OK) saved_pps = val;
|
||||
if (s_staging_cfg.target_pps != saved_pps) match = false;
|
||||
|
||||
// Standard Fields
|
||||
if (nvs_get_u32(h, NVS_KEY_IPERF_BURST, &val) == ESP_OK) { if (s_staging_cfg.burst_count != val) match = false; }
|
||||
if (nvs_get_u32(h, NVS_KEY_IPERF_LEN, &val) == ESP_OK) { if (s_staging_cfg.send_len != val) match = false; }
|
||||
|
||||
uint32_t saved_port = 0;
|
||||
if (nvs_get_u32(h, NVS_KEY_IPERF_PORT, &val) == ESP_OK) saved_port = val;
|
||||
if (s_staging_cfg.dport != (uint16_t)saved_port) match = false;
|
||||
|
||||
// IP String
|
||||
size_t req;
|
||||
char staging_ip[32];
|
||||
struct in_addr daddr; daddr.s_addr = s_staging_cfg.dip;
|
||||
inet_ntop(AF_INET, &daddr, staging_ip, sizeof(staging_ip));
|
||||
|
||||
if (nvs_get_str(h, NVS_KEY_IPERF_DST_IP, NULL, &req) == ESP_OK) {
|
||||
char *saved_ip = malloc(req);
|
||||
if (saved_ip) {
|
||||
nvs_get_str(h, NVS_KEY_IPERF_DST_IP, saved_ip, &req);
|
||||
trim_whitespace(saved_ip);
|
||||
if (strcmp(saved_ip, staging_ip) != 0) match = false;
|
||||
free(saved_ip);
|
||||
}
|
||||
} else {
|
||||
if (s_staging_cfg.dip != 0) match = false;
|
||||
}
|
||||
|
||||
nvs_close(h);
|
||||
return !match;
|
||||
// Set only the SEQNO64B flag (Server will detect 64-bit seqno in UDP header)
|
||||
hdr->flags = htonl(HEADER_SEQNO64B);
|
||||
}
|
||||
|
||||
// --- Save with Check ---
|
||||
esp_err_t iperf_param_save(bool *out_changed) {
|
||||
if (out_changed) *out_changed = false;
|
||||
if (!iperf_param_is_unsaved()) {
|
||||
ESP_LOGI(TAG, "Config matches NVS. No write needed.");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open("storage", NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
|
||||
// Direct Save: No conversion needed
|
||||
nvs_set_u32(h, NVS_KEY_IPERF_PPS, s_staging_cfg.target_pps);
|
||||
nvs_set_u32(h, NVS_KEY_IPERF_BURST, s_staging_cfg.burst_count);
|
||||
nvs_set_u32(h, NVS_KEY_IPERF_LEN, s_staging_cfg.send_len);
|
||||
nvs_set_u32(h, NVS_KEY_IPERF_PORT, (uint32_t)s_staging_cfg.dport);
|
||||
|
||||
char ip_str[32];
|
||||
struct in_addr daddr;
|
||||
daddr.s_addr = s_staging_cfg.dip;
|
||||
inet_ntop(AF_INET, &daddr, ip_str, sizeof(ip_str));
|
||||
nvs_set_str(h, NVS_KEY_IPERF_DST_IP, ip_str);
|
||||
|
||||
err = nvs_commit(h);
|
||||
if (err == ESP_OK && out_changed) *out_changed = true;
|
||||
|
||||
nvs_close(h);
|
||||
return err;
|
||||
}
|
||||
|
||||
// --- Status & Helpers ---
|
||||
// ... [Existing Status Reporting & Event Handler Code] ...
|
||||
|
||||
void iperf_get_stats(iperf_stats_t *stats) {
|
||||
if (stats) {
|
||||
s_stats.config_pps = s_iperf_ctrl.cfg.target_pps;
|
||||
s_stats.config_pps = (s_iperf_ctrl.cfg.pacing_period_us > 0) ?
|
||||
(1000000 / s_iperf_ctrl.cfg.pacing_period_us) : 0;
|
||||
*stats = s_stats;
|
||||
}
|
||||
}
|
||||
|
|
@ -288,24 +102,29 @@ void iperf_get_stats(iperf_stats_t *stats) {
|
|||
void iperf_print_status(void) {
|
||||
iperf_get_stats(&s_stats);
|
||||
|
||||
// 1. Get Source IP
|
||||
char src_ip[32] = "0.0.0.0";
|
||||
esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
|
||||
if (netif) {
|
||||
esp_netif_ip_info_t ip_info;
|
||||
if (esp_netif_get_ip_info(netif, &ip_info) == ESP_OK) {
|
||||
inet_ntop(AF_INET, &ip_info.ip, src_ip, sizeof(src_ip));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Get Destination IP
|
||||
char dst_ip[32] = "0.0.0.0";
|
||||
struct in_addr daddr;
|
||||
|
||||
// Show active config if running, otherwise staging
|
||||
if (s_stats.running) daddr.s_addr = s_iperf_ctrl.cfg.dip;
|
||||
else daddr.s_addr = s_staging_cfg.dip;
|
||||
|
||||
daddr.s_addr = s_iperf_ctrl.cfg.dip;
|
||||
inet_ntop(AF_INET, &daddr, dst_ip, sizeof(dst_ip));
|
||||
|
||||
// Calculate Percentages
|
||||
double total_us = (double)(s_time_tx_us + s_time_slow_us + s_time_stalled_us);
|
||||
if (total_us < 1.0) total_us = 1.0;
|
||||
float err = 0.0f;
|
||||
if (s_stats.running && s_stats.config_pps > 0) {
|
||||
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;
|
||||
}
|
||||
|
||||
double pct_tx = ((double)s_time_tx_us / total_us) * 100.0;
|
||||
double pct_slow = ((double)s_time_slow_us / total_us) * 100.0;
|
||||
double pct_stalled = ((double)s_time_stalled_us / total_us) * 100.0;
|
||||
|
||||
// Bandwidth Calculation
|
||||
// 3. Compute Session Bandwidth
|
||||
float avg_bw_mbps = 0.0f;
|
||||
if (s_session_start_time > 0) {
|
||||
int64_t end_t = (s_stats.running) ? esp_timer_get_time() : s_session_end_time;
|
||||
|
|
@ -318,32 +137,26 @@ void iperf_print_status(void) {
|
|||
}
|
||||
}
|
||||
|
||||
printf("IPERF: Dest=%s:%u, Pkts=%llu, BW=%.2f Mbps, Running=%d\n",
|
||||
dst_ip,
|
||||
s_stats.running ? s_iperf_ctrl.cfg.dport : s_staging_cfg.dport,
|
||||
s_session_packets,
|
||||
avg_bw_mbps,
|
||||
s_stats.running);
|
||||
// 4. Calculate State Percentages
|
||||
double total_us = (double)(s_time_tx_us + s_time_slow_us + s_time_stalled_us);
|
||||
if (total_us < 1.0) total_us = 1.0;
|
||||
|
||||
printf("STATES: TX=%.2fs/%.1f%% (%lu), SLOW=%.2fs/%.1f%% (%lu), STALLED=%.2fs/%.1f%% (%lu)\n",
|
||||
double pct_tx = ((double)s_time_tx_us / total_us) * 100.0;
|
||||
double pct_slow = ((double)s_time_slow_us / total_us) * 100.0;
|
||||
double pct_stalled = ((double)s_time_stalled_us / total_us) * 100.0;
|
||||
|
||||
// Standard Stats
|
||||
printf("IPERF_STATUS: Src=%s, Dst=%s, Running=%d, Config=%" PRIu32 ", Actual=%" PRIu32 ", Err=%.1f%%, Pkts=%" PRIu64 ", AvgBW=%.2f Mbps\n",
|
||||
src_ip, dst_ip, s_stats.running, s_stats.config_pps, s_stats.actual_pps, err, s_session_packets, avg_bw_mbps);
|
||||
|
||||
// New Format: Time + Percentage + Edges
|
||||
printf("IPERF_STATES: TX=%.2fs/%.1f%% (%lu), SLOW=%.2fs/%.1f%% (%lu), STALLED=%.2fs/%.1f%% (%lu)\n",
|
||||
(double)s_time_tx_us/1000000.0, pct_tx, (unsigned long)s_edge_tx,
|
||||
(double)s_time_slow_us/1000000.0, pct_slow, (unsigned long)s_edge_slow,
|
||||
(double)s_time_stalled_us/1000000.0, pct_stalled, (unsigned long)s_edge_stalled);
|
||||
}
|
||||
|
||||
// --- Core Logic ---
|
||||
|
||||
static void iperf_pattern(uint8_t *buf, uint32_t len) {
|
||||
for (uint32_t i = 0; i < len; i++) {
|
||||
buf[i] = (i % 10) + '0';
|
||||
}
|
||||
}
|
||||
|
||||
static void iperf_generate_client_hdr(iperf_cfg_t *cfg, client_hdr_v1 *hdr) {
|
||||
memset(hdr, 0, sizeof(client_hdr_v1));
|
||||
hdr->flags = htonl(HEADER_SEQNO64B);
|
||||
}
|
||||
|
||||
// --- 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) {
|
||||
|
|
@ -362,7 +175,7 @@ static bool iperf_wait_for_ip(void) {
|
|||
if (netif) {
|
||||
esp_netif_ip_info_t ip_info;
|
||||
if (esp_netif_get_ip_info(netif, &ip_info) == ESP_OK && ip_info.ip.addr != 0) {
|
||||
return true;
|
||||
xEventGroupSetBits(s_iperf_event_group, IPERF_IP_READY_BIT);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -375,21 +188,95 @@ static bool iperf_wait_for_ip(void) {
|
|||
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);
|
||||
|
||||
if (bits & IPERF_STOP_REQ_BIT) return false;
|
||||
if (bits & IPERF_STOP_REQ_BIT) {
|
||||
ESP_LOGW(TAG, "Stop requested while waiting for IP");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI(TAG, "IP Ready. Starting traffic.");
|
||||
return true;
|
||||
}
|
||||
|
||||
static void trim_whitespace(char *str) {
|
||||
char *end = str + strlen(str) - 1;
|
||||
while(end > str && isspace((unsigned char)*end)) end--;
|
||||
*(end+1) = 0;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
uint32_t val;
|
||||
if (nvs_get_u32(my_handle, NVS_KEY_IPERF_PERIOD, &val) == ESP_OK) cfg->pacing_period_us = val;
|
||||
if (nvs_get_u32(my_handle, NVS_KEY_IPERF_BURST, &val) == ESP_OK) cfg->burst_count = val;
|
||||
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;
|
||||
|
||||
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;
|
||||
else cfg->flag |= IPERF_FLAG_CLIENT;
|
||||
}
|
||||
|
||||
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;
|
||||
else cfg->flag |= IPERF_FLAG_UDP;
|
||||
}
|
||||
|
||||
if (nvs_get_str(my_handle, NVS_KEY_IPERF_DST_IP, NULL, &req) == ESP_OK) {
|
||||
char *ip_str = malloc(req);
|
||||
if (ip_str) {
|
||||
nvs_get_str(my_handle, NVS_KEY_IPERF_DST_IP, ip_str, &req);
|
||||
trim_whitespace(ip_str);
|
||||
cfg->dip = inet_addr(ip_str);
|
||||
free(ip_str);
|
||||
}
|
||||
}
|
||||
nvs_close(my_handle);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
if (s_iperf_task_handle != NULL) {
|
||||
s_iperf_ctrl.cfg.pacing_period_us = period_us;
|
||||
printf("IPERF_PPS_UPDATED: %" PRIu32 "\n", pps);
|
||||
} else {
|
||||
s_iperf_ctrl.cfg.pacing_period_us = period_us;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t iperf_get_pps(void) {
|
||||
if (s_iperf_ctrl.cfg.pacing_period_us == 0) return 0;
|
||||
return 1000000 / s_iperf_ctrl.cfg.pacing_period_us;
|
||||
}
|
||||
|
||||
|
||||
static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) {
|
||||
if (!iperf_wait_for_ip()) return ESP_OK;
|
||||
if (!iperf_wait_for_ip()) {
|
||||
printf("IPERF_STOPPED\n");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
struct sockaddr_in addr;
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(ctrl->cfg.dport);
|
||||
addr.sin_port = htons(ctrl->cfg.dport > 0 ? ctrl->cfg.dport : 5001);
|
||||
addr.sin_addr.s_addr = ctrl->cfg.dip;
|
||||
|
||||
char ip_str[32];
|
||||
inet_ntop(AF_INET, &addr.sin_addr, ip_str, sizeof(ip_str));
|
||||
ESP_LOGI(TAG, "Client sending to %s:%d", ip_str, ntohs(addr.sin_port));
|
||||
|
||||
int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
if (sockfd < 0) {
|
||||
ESP_LOGE(TAG, "Socket failed: %d", errno);
|
||||
status_led_set_state(LED_STATE_FAILED);
|
||||
ESP_LOGE(TAG, "Socket creation failed: %d", errno);
|
||||
printf("IPERF_STOPPED\n");
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
|
|
@ -401,6 +288,7 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) {
|
|||
|
||||
s_stats.running = true;
|
||||
s_session_start_time = esp_timer_get_time();
|
||||
s_session_end_time = 0;
|
||||
s_session_packets = 0;
|
||||
|
||||
// Reset FSM
|
||||
|
|
@ -408,33 +296,22 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) {
|
|||
s_edge_tx = 0; s_edge_slow = 0; s_edge_stalled = 0;
|
||||
s_current_fsm_state = IPERF_STATE_IDLE;
|
||||
|
||||
ESP_LOGI(TAG, "UDP Started. Target: %s", inet_ntoa(addr.sin_addr));
|
||||
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 packet_id = 0;
|
||||
struct timespec ts;
|
||||
|
||||
// Calculate period based on PPS (Target Period)
|
||||
uint32_t period_us = (ctrl->cfg.target_pps > 0) ? (1000000 / ctrl->cfg.target_pps) : 10000;
|
||||
if (period_us < MIN_PACING_INTERVAL_US) period_us = MIN_PACING_INTERVAL_US;
|
||||
|
||||
while (!ctrl->finish && !s_reload_req) {
|
||||
while (!ctrl->finish && esp_timer_get_time() < end_time) {
|
||||
int64_t now = esp_timer_get_time();
|
||||
int64_t wait = next_send_time - now;
|
||||
|
||||
// 1. Sleep if gap is large
|
||||
if (wait > 2000) {
|
||||
vTaskDelay(pdMS_TO_TICKS(wait / 1000));
|
||||
}
|
||||
|
||||
// 2. Spin until exact time (Strict Monotonic enforcement)
|
||||
while (esp_timer_get_time() < next_send_time) {
|
||||
taskYIELD();
|
||||
}
|
||||
|
||||
if (xEventGroupGetBits(s_iperf_event_group) & IPERF_STOP_REQ_BIT) break;
|
||||
if (wait > 2000) vTaskDelay(pdMS_TO_TICKS(wait / 1000));
|
||||
else while (esp_timer_get_time() < next_send_time) taskYIELD();
|
||||
|
||||
for (int k = 0; k < ctrl->cfg.burst_count; k++) {
|
||||
int64_t current_id = packet_id++;
|
||||
|
|
@ -446,20 +323,32 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) {
|
|||
udp_hdr->tv_sec = htonl((uint32_t)ts.tv_sec);
|
||||
udp_hdr->tv_usec = htonl(ts.tv_nsec / 1000);
|
||||
|
||||
if (sendto(sockfd, ctrl->buffer, ctrl->cfg.send_len, 0, (struct sockaddr *)&addr, sizeof(addr)) > 0) {
|
||||
s_session_packets++;
|
||||
int sent = sendto(sockfd, ctrl->buffer, ctrl->cfg.send_len, 0, (struct sockaddr *)&addr, sizeof(addr));
|
||||
|
||||
if (sent > 0) {
|
||||
packets_since_check++;
|
||||
s_session_packets++;
|
||||
} else {
|
||||
// --- ROBUST FIX: Never Abort ---
|
||||
// If send fails (buffer full, routing issue, etc.), we just yield and retry next loop.
|
||||
// We do NOT goto exit.
|
||||
if (errno != 12) {
|
||||
// Log rarely to avoid spamming serial
|
||||
if ((packet_id % 100) == 0) {
|
||||
ESP_LOGW(TAG, "Send error: %d (Ignored)", errno);
|
||||
}
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
}
|
||||
}
|
||||
|
||||
// FSM STATS LOGIC
|
||||
now = esp_timer_get_time();
|
||||
if (now - last_rate_check > RATE_CHECK_INTERVAL_US) {
|
||||
uint32_t interval_us = (uint32_t)(now - last_rate_check);
|
||||
if (interval_us > 0) {
|
||||
s_stats.actual_pps = (uint32_t)((uint64_t)packets_since_check * 1000000 / interval_us);
|
||||
uint32_t threshold = (ctrl->cfg.target_pps * 3) / 4;
|
||||
|
||||
uint32_t config_pps = iperf_get_pps();
|
||||
uint32_t threshold = (config_pps * 3) / 4;
|
||||
iperf_fsm_state_t next_state;
|
||||
if (s_stats.actual_pps == 0) next_state = IPERF_STATE_TX_STALLED;
|
||||
else if (s_stats.actual_pps >= threshold) next_state = IPERF_STATE_TX;
|
||||
|
|
@ -471,7 +360,6 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) {
|
|||
case IPERF_STATE_TX_STALLED: s_time_stalled_us += interval_us; break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
if (next_state != s_current_fsm_state) {
|
||||
switch (next_state) {
|
||||
case IPERF_STATE_TX: s_edge_tx++; break;
|
||||
|
|
@ -481,73 +369,96 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) {
|
|||
}
|
||||
s_current_fsm_state = next_state;
|
||||
}
|
||||
|
||||
led_state_t led_target = (s_current_fsm_state == IPERF_STATE_TX) ? LED_STATE_TRANSMITTING : LED_STATE_TRANSMITTING_SLOW;
|
||||
if (status_led_get_state() != led_target) status_led_set_state(led_target);
|
||||
}
|
||||
last_rate_check = now;
|
||||
packets_since_check = 0;
|
||||
}
|
||||
|
||||
// MONOTONIC UPDATE
|
||||
next_send_time += period_us;
|
||||
next_send_time += ctrl->cfg.pacing_period_us;
|
||||
}
|
||||
|
||||
udp_datagram *hdr = (udp_datagram *)ctrl->buffer;
|
||||
int64_t final_id = -packet_id;
|
||||
hdr->id = htonl((uint32_t)(final_id & 0xFFFFFFFF));
|
||||
hdr->id2 = htonl((uint32_t)((final_id >> 32) & 0xFFFFFFFF));
|
||||
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
hdr->tv_sec = htonl((uint32_t)ts.tv_sec);
|
||||
hdr->tv_usec = htonl(ts.tv_nsec / 1000);
|
||||
for(int i=0; i<10; i++) {
|
||||
sendto(sockfd, ctrl->buffer, ctrl->cfg.send_len, 0, (struct sockaddr *)&addr, sizeof(addr));
|
||||
vTaskDelay(pdMS_TO_TICKS(2));
|
||||
}
|
||||
ESP_LOGI(TAG, "Sent termination packets (ID: %" PRId64 ")", final_id);
|
||||
|
||||
close(sockfd);
|
||||
s_stats.running = false;
|
||||
s_session_end_time = esp_timer_get_time();
|
||||
status_led_set_state(LED_STATE_CONNECTED);
|
||||
s_stats.actual_pps = 0;
|
||||
status_led_set_state(LED_STATE_CONNECTED); // <--- This is your "Solid Green"
|
||||
printf("IPERF_STOPPED\n");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void iperf_task(void *arg) {
|
||||
iperf_ctrl_t *ctrl = (iperf_ctrl_t *)arg;
|
||||
|
||||
while (1) {
|
||||
do {
|
||||
s_reload_req = false;
|
||||
ctrl->finish = false;
|
||||
xEventGroupClearBits(s_iperf_event_group, IPERF_STOP_REQ_BIT);
|
||||
|
||||
if (ctrl->cfg.flag & IPERF_FLAG_UDP && ctrl->cfg.flag & IPERF_FLAG_CLIENT) {
|
||||
iperf_start_udp_client(ctrl);
|
||||
}
|
||||
|
||||
if (s_reload_req) {
|
||||
ESP_LOGI(TAG, "Task reloading config...");
|
||||
if (ctrl->buffer_len < ctrl->cfg.send_len + 128) {
|
||||
free(ctrl->buffer);
|
||||
ctrl->buffer_len = ctrl->cfg.send_len + 128;
|
||||
ctrl->buffer = calloc(1, ctrl->buffer_len);
|
||||
iperf_pattern(ctrl->buffer, ctrl->buffer_len);
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
ESP_LOGI(TAG, "Hot reloading iperf task with new config...");
|
||||
ctrl->cfg = s_next_cfg;
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
}
|
||||
|
||||
} while (s_reload_req);
|
||||
|
||||
free(ctrl->buffer);
|
||||
s_iperf_task_handle = NULL;
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void iperf_start(void) {
|
||||
if (!s_staging_initialized) iperf_param_init();
|
||||
void iperf_start(iperf_cfg_t *cfg) {
|
||||
iperf_cfg_t new_cfg = *cfg;
|
||||
iperf_read_nvs_config(&new_cfg);
|
||||
|
||||
if (new_cfg.send_len == 0) new_cfg.send_len = 1470;
|
||||
if (new_cfg.pacing_period_us == 0) new_cfg.pacing_period_us = 10000;
|
||||
if (new_cfg.burst_count == 0) new_cfg.burst_count = 1;
|
||||
|
||||
if (s_iperf_task_handle) {
|
||||
ESP_LOGW(TAG, "Already running. Use 'set' to update parameters.");
|
||||
ESP_LOGI(TAG, "Task running. Staging hot reload.");
|
||||
s_next_cfg = new_cfg;
|
||||
s_reload_req = true;
|
||||
iperf_stop();
|
||||
printf("IPERF_RELOADING\n");
|
||||
return;
|
||||
}
|
||||
|
||||
// Copy Staging -> Active
|
||||
s_iperf_ctrl.cfg = s_staging_cfg;
|
||||
s_iperf_ctrl.cfg = new_cfg;
|
||||
s_iperf_ctrl.finish = false;
|
||||
|
||||
// Allocate Buffer
|
||||
if (s_iperf_ctrl.buffer == NULL) {
|
||||
s_iperf_ctrl.buffer_len = s_iperf_ctrl.cfg.send_len + 128;
|
||||
s_iperf_ctrl.buffer = calloc(1, s_iperf_ctrl.buffer_len);
|
||||
}
|
||||
|
||||
// Initialize Buffer Pattern
|
||||
if (s_iperf_ctrl.buffer) {
|
||||
iperf_pattern(s_iperf_ctrl.buffer, s_iperf_ctrl.buffer_len);
|
||||
}
|
||||
|
||||
if (s_iperf_event_group == NULL) s_iperf_event_group = xEventGroupCreate();
|
||||
if (s_iperf_event_group == NULL) {
|
||||
s_iperf_event_group = xEventGroupCreate();
|
||||
}
|
||||
|
||||
xTaskCreate(iperf_task, "iperf", 4096, &s_iperf_ctrl, 5, &s_iperf_task_handle);
|
||||
}
|
||||
|
|
@ -556,5 +467,7 @@ 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 {
|
||||
printf("IPERF_STOPPED\n");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
#define IPERF_FLAG_TCP (1 << 2)
|
||||
#define IPERF_FLAG_UDP (1 << 3)
|
||||
|
||||
// --- Standard Iperf2 Header Flags ---
|
||||
// --- Standard Iperf2 Header Flags (from payloads.h) ---
|
||||
#define HEADER_VERSION1 0x80000000
|
||||
#define HEADER_EXTEND 0x40000000
|
||||
#define HEADER_UDPTESTS 0x20000000
|
||||
|
|
@ -21,18 +21,32 @@
|
|||
#define IPERF_DEFAULT_PORT 5001
|
||||
#define IPERF_DEFAULT_INTERVAL 3
|
||||
#define IPERF_DEFAULT_TIME 30
|
||||
#define IPERF_UDP_TX_LEN 1470
|
||||
#define IPERF_TRAFFIC_TASK_PRIORITY 4
|
||||
#define IPERF_REPORT_TASK_PRIORITY 5
|
||||
|
||||
#define IPERF_UDP_TX_LEN (1470)
|
||||
|
||||
// --- NVS Keys ---
|
||||
#define NVS_KEY_IPERF_ENABLE "iperf_enabled"
|
||||
#define NVS_KEY_IPERF_PERIOD "iperf_period"
|
||||
#define NVS_KEY_IPERF_ROLE "iperf_role"
|
||||
#define NVS_KEY_IPERF_DST_IP "iperf_dst_ip"
|
||||
#define NVS_KEY_IPERF_PORT "iperf_port"
|
||||
#define NVS_KEY_IPERF_PROTO "iperf_proto"
|
||||
#define NVS_KEY_IPERF_BURST "iperf_burst"
|
||||
#define NVS_KEY_IPERF_LEN "iperf_len"
|
||||
|
||||
typedef struct {
|
||||
uint32_t flag;
|
||||
uint32_t dip; // Destination IP
|
||||
uint16_t dport; // Destination Port
|
||||
uint32_t time; // Duration (seconds), 0 = infinite
|
||||
uint32_t target_pps; // Packets Per Second (Replaces period)
|
||||
uint32_t burst_count; // Packets per RTOS tick
|
||||
uint32_t send_len; // Packet payload length
|
||||
uint32_t dip;
|
||||
uint16_t dport;
|
||||
uint32_t time;
|
||||
uint32_t pacing_period_us;
|
||||
uint32_t burst_count;
|
||||
uint32_t send_len;
|
||||
} iperf_cfg_t;
|
||||
|
||||
// --- Stats Structure ---
|
||||
typedef struct {
|
||||
bool running;
|
||||
uint32_t config_pps;
|
||||
|
|
@ -40,29 +54,41 @@ typedef struct {
|
|||
float error_rate;
|
||||
} iperf_stats_t;
|
||||
|
||||
// --- Wire Formats (Strict Layout) ---
|
||||
|
||||
// 1. Basic UDP Datagram Header (16 bytes)
|
||||
// Corresponds to 'struct UDP_datagram' in payloads.h
|
||||
typedef struct {
|
||||
int32_t id; // Lower 32 bits of seqno
|
||||
uint32_t tv_sec; // Seconds
|
||||
uint32_t tv_usec; // Microseconds
|
||||
int32_t id2; // Upper 32 bits of seqno (when HEADER_SEQNO64B is set)
|
||||
} udp_datagram;
|
||||
|
||||
// 2. Client Header V1 (Used for First Packet Exchange)
|
||||
// Corresponds to 'struct client_hdr_v1' in payloads.h
|
||||
typedef struct {
|
||||
int32_t flags;
|
||||
int32_t numThreads;
|
||||
int32_t mPort;
|
||||
int32_t mBufLen;
|
||||
int32_t mWinBand;
|
||||
int32_t mAmount;
|
||||
} client_hdr_v1;
|
||||
|
||||
// --- API ---
|
||||
|
||||
// Initialization (Call this in app_main to load NVS)
|
||||
void iperf_param_init(void);
|
||||
void iperf_init_led(led_strip_handle_t handle);
|
||||
void iperf_set_pps(uint32_t pps);
|
||||
uint32_t iperf_get_pps(void);
|
||||
|
||||
// Parameter Management (Running Config)
|
||||
void iperf_param_get(iperf_cfg_t *out_cfg);
|
||||
void iperf_param_set(const iperf_cfg_t *new_cfg);
|
||||
// Get snapshot of current stats
|
||||
void iperf_get_stats(iperf_stats_t *stats);
|
||||
|
||||
// Save returns true if NVS was actually updated
|
||||
esp_err_t iperf_param_save(bool *out_changed);
|
||||
|
||||
// Check if dirty
|
||||
bool iperf_param_is_unsaved(void);
|
||||
|
||||
// Control
|
||||
void iperf_start(void); // Uses current Running Config
|
||||
void iperf_stop(void);
|
||||
// Print formatted status to stdout (for CLI/Python)
|
||||
void iperf_print_status(void);
|
||||
|
||||
// Utils
|
||||
void iperf_init_led(led_strip_handle_t handle);
|
||||
void iperf_start(iperf_cfg_t *cfg);
|
||||
void iperf_stop(void);
|
||||
|
||||
// Erase NVS and reset RAM defaults
|
||||
void iperf_param_clear(void);
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -5,8 +5,6 @@
|
|||
#include "led_strip.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
static const char *TAG = "status_led";
|
||||
|
||||
static led_strip_handle_t s_led_strip = NULL;
|
||||
static bool s_is_rgb = false;
|
||||
static int s_gpio_pin = -1;
|
||||
|
|
@ -17,7 +15,6 @@ static void set_color(uint8_t r, uint8_t g, uint8_t b) {
|
|||
led_strip_set_pixel(s_led_strip, 0, r, g, b);
|
||||
led_strip_refresh(s_led_strip);
|
||||
} else if (!s_is_rgb && s_gpio_pin >= 0) {
|
||||
// Simple LED: On if any color component is > 0
|
||||
gpio_set_level(s_gpio_pin, (r+g+b) > 0);
|
||||
}
|
||||
}
|
||||
|
|
@ -26,40 +23,33 @@ static void led_task(void *arg) {
|
|||
int toggle = 0;
|
||||
while (1) {
|
||||
switch (s_current_state) {
|
||||
case LED_STATE_NO_CONFIG: // Yellow (Solid for RGB, Blink for Single)
|
||||
if (s_is_rgb) { set_color(20, 20, 0); vTaskDelay(pdMS_TO_TICKS(1000)); }
|
||||
else { set_color(1,1,1); vTaskDelay(pdMS_TO_TICKS(100)); set_color(0,0,0); vTaskDelay(pdMS_TO_TICKS(100)); }
|
||||
case LED_STATE_NO_CONFIG: // Yellow
|
||||
if (s_is_rgb) { set_color(25, 25, 0); vTaskDelay(pdMS_TO_TICKS(1000)); }
|
||||
else { set_color(1,1,1); vTaskDelay(100); set_color(0,0,0); vTaskDelay(100); }
|
||||
break;
|
||||
case LED_STATE_WAITING: // Blue Blink (Searching)
|
||||
set_color(0, 0, toggle ? 50 : 0);
|
||||
toggle = !toggle;
|
||||
case LED_STATE_WAITING: // Blue Blink
|
||||
set_color(0, 0, toggle ? 50 : 0); toggle = !toggle;
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
break;
|
||||
case LED_STATE_CONNECTED: // Green Solid (Idle)
|
||||
set_color(0, 20, 0);
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
case LED_STATE_CONNECTED: // Green Solid
|
||||
set_color(0, 25, 0); vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
break;
|
||||
case LED_STATE_MONITORING: // Blue Solid (Sniffer Mode)
|
||||
set_color(0, 0, 50);
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
case LED_STATE_MONITORING: // Blue Solid
|
||||
set_color(0, 0, 50); vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
break;
|
||||
case LED_STATE_TRANSMITTING: // Fast Purple Flash (Busy)
|
||||
set_color(toggle ? 50 : 0, 0, toggle ? 50 : 0);
|
||||
toggle = !toggle;
|
||||
case LED_STATE_TRANSMITTING: // Fast Purple (Busy)
|
||||
set_color(toggle ? 50 : 0, 0, toggle ? 50 : 0); toggle = !toggle;
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
break;
|
||||
case LED_STATE_TRANSMITTING_SLOW: // Slow Purple Pulse (Pacing)
|
||||
set_color(toggle ? 50 : 0, 0, toggle ? 50 : 0);
|
||||
toggle = !toggle;
|
||||
case LED_STATE_TRANSMITTING_SLOW: // Slow Purple (Relaxed)
|
||||
set_color(toggle ? 50 : 0, 0, toggle ? 50 : 0); toggle = !toggle;
|
||||
vTaskDelay(pdMS_TO_TICKS(250));
|
||||
break;
|
||||
case LED_STATE_STALLED: // Purple Solid (Stalled)
|
||||
set_color(50, 0, 50);
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
case LED_STATE_STALLED: // Purple Solid
|
||||
set_color(50, 0, 50); vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
break;
|
||||
case LED_STATE_FAILED: // Red Blink (Error)
|
||||
set_color(toggle ? 50 : 0, 0, 0);
|
||||
toggle = !toggle;
|
||||
case LED_STATE_FAILED: // Red Blink
|
||||
set_color(toggle ? 50 : 0, 0, 0); toggle = !toggle;
|
||||
vTaskDelay(pdMS_TO_TICKS(200));
|
||||
break;
|
||||
}
|
||||
|
|
@ -69,34 +59,15 @@ static void led_task(void *arg) {
|
|||
void status_led_init(int gpio_pin, bool is_rgb_strip) {
|
||||
s_gpio_pin = gpio_pin;
|
||||
s_is_rgb = is_rgb_strip;
|
||||
|
||||
ESP_LOGI(TAG, "Initializing LED on GPIO %d (RGB=%d)", gpio_pin, is_rgb_strip);
|
||||
|
||||
if (s_is_rgb) {
|
||||
led_strip_config_t s_cfg = {
|
||||
.strip_gpio_num = gpio_pin,
|
||||
.max_leds = 1,
|
||||
.led_pixel_format = LED_PIXEL_FORMAT_GRB, // Standard for WS2812
|
||||
.led_model = LED_MODEL_WS2812, // Specific model
|
||||
.flags.invert_out = false,
|
||||
};
|
||||
led_strip_rmt_config_t r_cfg = {
|
||||
.resolution_hz = 10 * 1000 * 1000, // 10MHz
|
||||
.flags.with_dma = false,
|
||||
};
|
||||
|
||||
esp_err_t ret = led_strip_new_rmt_device(&s_cfg, &r_cfg, &s_led_strip);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to create RMT LED strip: %s", esp_err_to_name(ret));
|
||||
return;
|
||||
}
|
||||
led_strip_config_t s_cfg = { .strip_gpio_num = gpio_pin, .max_leds = 1 };
|
||||
led_strip_rmt_config_t r_cfg = { .resolution_hz = 10 * 1000 * 1000 };
|
||||
led_strip_new_rmt_device(&s_cfg, &r_cfg, &s_led_strip);
|
||||
led_strip_clear(s_led_strip);
|
||||
} else {
|
||||
gpio_reset_pin(gpio_pin);
|
||||
gpio_set_direction(gpio_pin, GPIO_MODE_OUTPUT);
|
||||
gpio_set_level(gpio_pin, 0);
|
||||
}
|
||||
|
||||
xTaskCreate(led_task, "led_task", 2048, NULL, 5, NULL);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -52,30 +52,6 @@ void wifi_cfg_set_dhcp(bool enable) {
|
|||
nvs_write_u8("dhcp", enable ? 1 : 0);
|
||||
}
|
||||
|
||||
// --- Clearing ---
|
||||
void wifi_cfg_clear_credentials(void) {
|
||||
nvs_handle_t h;
|
||||
if (nvs_open("netcfg", NVS_READWRITE, &h) == ESP_OK) {
|
||||
nvs_erase_key(h, "ssid");
|
||||
nvs_erase_key(h, "pass");
|
||||
nvs_erase_key(h, "ip");
|
||||
nvs_erase_key(h, "mask");
|
||||
nvs_erase_key(h, "gw");
|
||||
nvs_erase_key(h, "dhcp");
|
||||
nvs_commit(h);
|
||||
nvs_close(h);
|
||||
}
|
||||
}
|
||||
|
||||
void wifi_cfg_clear_monitor_channel(void) {
|
||||
nvs_handle_t h;
|
||||
if (nvs_open("netcfg", NVS_READWRITE, &h) == ESP_OK) {
|
||||
nvs_erase_key(h, "mon_ch");
|
||||
nvs_commit(h);
|
||||
nvs_close(h);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Init & Load ---
|
||||
|
||||
void wifi_cfg_init(void) {
|
||||
|
|
@ -178,38 +154,3 @@ bool wifi_cfg_get_mode(char *mode, uint8_t *mon_ch) {
|
|||
nvs_close(h);
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- State Checkers ---
|
||||
|
||||
bool wifi_cfg_monitor_channel_is_unsaved(uint8_t ram_value) {
|
||||
nvs_handle_t h;
|
||||
if (nvs_open("netcfg", NVS_READONLY, &h) != ESP_OK) return true; // Assume dirty if error
|
||||
|
||||
uint8_t nvs_val = 0;
|
||||
esp_err_t err = nvs_get_u8(h, "mon_ch", &nvs_val);
|
||||
nvs_close(h);
|
||||
|
||||
if (err != ESP_OK) return true; // Key missing = dirty (using default)
|
||||
return (nvs_val != ram_value);
|
||||
}
|
||||
|
||||
// --- Setters ---
|
||||
|
||||
bool wifi_cfg_set_monitor_channel(uint8_t channel) {
|
||||
nvs_handle_t h;
|
||||
if (nvs_open("netcfg", NVS_READWRITE, &h) != ESP_OK) return false;
|
||||
|
||||
uint8_t current = 0;
|
||||
// Check if write is necessary
|
||||
if (nvs_get_u8(h, "mon_ch", ¤t) == ESP_OK) {
|
||||
if (current == channel) {
|
||||
nvs_close(h);
|
||||
return false; // No change needed
|
||||
}
|
||||
}
|
||||
|
||||
nvs_set_u8(h, "mon_ch", channel);
|
||||
nvs_commit(h);
|
||||
nvs_close(h);
|
||||
return true; // Write occurred
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
|
||||
#ifndef WIFI_CFG_H
|
||||
#define WIFI_CFG_H
|
||||
|
||||
|
|
@ -12,28 +11,17 @@ extern "C" {
|
|||
// --- Initialization ---
|
||||
void wifi_cfg_init(void);
|
||||
|
||||
// --- Getters ---
|
||||
// --- Getters (Used by Controller) ---
|
||||
bool wifi_cfg_apply_from_nvs(void);
|
||||
wifi_ps_type_t wifi_cfg_get_power_save_mode(void);
|
||||
bool wifi_cfg_get_bandwidth(char *buf, size_t buf_size);
|
||||
bool wifi_cfg_get_mode(char *mode, uint8_t *mon_ch);
|
||||
|
||||
// --- State Checkers (Dirty Flag) ---
|
||||
// Returns true if RAM value differs from NVS
|
||||
bool wifi_cfg_monitor_channel_is_unsaved(uint8_t ram_value);
|
||||
|
||||
// --- Setters ---
|
||||
// --- Setters (Used by Console) ---
|
||||
void wifi_cfg_set_credentials(const char* ssid, const char* pass);
|
||||
void wifi_cfg_set_static_ip(const char* ip, const char* mask, const char* gw);
|
||||
void wifi_cfg_set_dhcp(bool enable);
|
||||
|
||||
// Returns true if NVS was actually updated, false if values were identical
|
||||
bool wifi_cfg_set_monitor_channel(uint8_t channel);
|
||||
|
||||
// --- Clearing ---
|
||||
void wifi_cfg_clear_credentials(void);
|
||||
void wifi_cfg_clear_monitor_channel(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
idf_component_register(SRCS "wifi_controller.c"
|
||||
INCLUDE_DIRS "."
|
||||
REQUIRES esp_wifi freertos
|
||||
PRIV_REQUIRES csi_manager iperf status_led wifi_monitor wifi_cfg gps_sync log esp_netif)
|
||||
PRIV_REQUIRES csi_manager iperf status_led wifi_monitor gps_sync log esp_netif)
|
||||
|
|
|
|||
|
|
@ -3,9 +3,7 @@
|
|||
#include "freertos/task.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event.h" // Added
|
||||
#include "inttypes.h"
|
||||
#include "wifi_cfg.h"
|
||||
|
||||
// Dependencies
|
||||
#include "iperf.h"
|
||||
|
|
@ -13,6 +11,7 @@
|
|||
#include "wifi_monitor.h"
|
||||
#include "gps_sync.h"
|
||||
|
||||
// 1. GUARDED INCLUDE
|
||||
#ifdef CONFIG_ESP_WIFI_CSI_ENABLED
|
||||
#include "csi_manager.h"
|
||||
#endif
|
||||
|
|
@ -21,35 +20,33 @@ static const char *TAG = "WIFI_CTL";
|
|||
|
||||
static wifi_ctl_mode_t s_current_mode = WIFI_CTL_MODE_STA;
|
||||
static uint8_t s_monitor_channel = 6;
|
||||
static uint8_t s_monitor_channel_staging = 6;
|
||||
|
||||
static bool s_monitor_enabled = false;
|
||||
static uint32_t s_monitor_frame_count = 0;
|
||||
static TaskHandle_t s_monitor_stats_task_handle = NULL;
|
||||
|
||||
// --- Event Handler ---
|
||||
static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
|
||||
if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
|
||||
ESP_LOGI(TAG, "Got IP -> LED Connected");
|
||||
status_led_set_state(LED_STATE_CONNECTED);
|
||||
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
|
||||
status_led_set_state(LED_STATE_NO_CONFIG); // Or WAITING if retrying
|
||||
}
|
||||
}
|
||||
|
||||
// ... [Helper: Log Collapse Events (Same as before)] ...
|
||||
// --- Helper: Log Collapse Events ---
|
||||
static void log_collapse_event(float nav_duration_us, int rssi, int retry) {
|
||||
gps_timestamp_t ts = gps_get_timestamp();
|
||||
// CSV Format: COLLAPSE,MonoMS,GpsMS,Synced,Duration,RSSI,Retry
|
||||
printf("COLLAPSE,%" PRIi64 ",%" PRIi64 ",%d,%.2f,%d,%d\n",
|
||||
ts.monotonic_ms, ts.gps_ms, ts.synced ? 1 : 0, nav_duration_us, rssi, retry);
|
||||
ts.monotonic_ms,
|
||||
ts.gps_ms,
|
||||
ts.synced ? 1 : 0,
|
||||
nav_duration_us,
|
||||
rssi,
|
||||
retry);
|
||||
}
|
||||
|
||||
// ... [Monitor Callbacks (Same as before)] ...
|
||||
// --- Monitor Callbacks & Tasks ---
|
||||
|
||||
static void monitor_frame_callback(const wifi_frame_info_t *frame, const uint8_t *payload, uint16_t len) {
|
||||
s_monitor_frame_count++;
|
||||
|
||||
// Check for Collapse conditions (High NAV + Retry)
|
||||
if (frame->retry && frame->duration_id > 5000) {
|
||||
log_collapse_event((float)frame->duration_id, frame->rssi, frame->retry);
|
||||
}
|
||||
|
||||
if (frame->duration_id > 30000) {
|
||||
ESP_LOGW("MONITOR", "⚠️ VERY HIGH NAV: %u us", frame->duration_id);
|
||||
}
|
||||
|
|
@ -62,19 +59,26 @@ static void monitor_stats_task(void *arg) {
|
|||
if (wifi_monitor_get_stats(&stats) == ESP_OK) {
|
||||
ESP_LOGI("MONITOR", "--- Stats: %lu frames, Retry: %.2f%%, Avg NAV: %u us ---",
|
||||
(unsigned long)stats.total_frames, stats.retry_rate, stats.avg_nav);
|
||||
if (wifi_monitor_is_collapsed()) ESP_LOGW("MONITOR", "⚠️ ⚠️ COLLAPSE DETECTED! ⚠️ ⚠️");
|
||||
|
||||
if (wifi_monitor_is_collapsed()) {
|
||||
ESP_LOGW("MONITOR", "⚠️ ⚠️ COLLAPSE DETECTED! ⚠️ ⚠️");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void auto_monitor_task_func(void *arg) {
|
||||
uint8_t channel = (uint8_t)(uintptr_t)arg;
|
||||
|
||||
ESP_LOGI(TAG, "Waiting for WiFi connection before switching to monitor mode...");
|
||||
// Wait until LED indicates connected
|
||||
while (status_led_get_state() != LED_STATE_CONNECTED) {
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "WiFi connected, waiting for GPS sync (2s)...");
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
|
||||
ESP_LOGI(TAG, "Auto-switching to MONITOR mode on channel %d...", channel);
|
||||
wifi_ctl_switch_to_monitor(channel, WIFI_BW_HT20);
|
||||
vTaskDelete(NULL);
|
||||
|
|
@ -86,72 +90,15 @@ void wifi_ctl_init(void) {
|
|||
s_current_mode = WIFI_CTL_MODE_STA;
|
||||
s_monitor_enabled = false;
|
||||
s_monitor_frame_count = 0;
|
||||
|
||||
// Register Event Handlers for LED feedback
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &wifi_event_handler, NULL, NULL));
|
||||
|
||||
if (!wifi_cfg_apply_from_nvs()) {
|
||||
ESP_LOGW(TAG, "No saved WiFi config found, driver initialized in defaults.");
|
||||
status_led_set_state(LED_STATE_NO_CONFIG);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "WiFi driver initialized from NVS.");
|
||||
status_led_set_state(LED_STATE_WAITING); // Waiting for connection
|
||||
}
|
||||
|
||||
// Load Staging Params
|
||||
char mode_ignored[16];
|
||||
wifi_cfg_get_mode(mode_ignored, &s_monitor_channel_staging);
|
||||
if (s_monitor_channel_staging == 0) s_monitor_channel_staging = 6;
|
||||
}
|
||||
|
||||
// --- Parameter Management ---
|
||||
void wifi_ctl_param_set_monitor_channel(uint8_t channel) {
|
||||
if (channel >= 1 && channel <= 14) s_monitor_channel_staging = channel;
|
||||
}
|
||||
|
||||
uint8_t wifi_ctl_param_get_monitor_channel(void) {
|
||||
return s_monitor_channel_staging;
|
||||
}
|
||||
|
||||
bool wifi_ctl_param_save(void) {
|
||||
bool changed = wifi_cfg_set_monitor_channel(s_monitor_channel_staging);
|
||||
if (changed) ESP_LOGI(TAG, "Monitor channel (%d) saved to NVS", s_monitor_channel_staging);
|
||||
return changed;
|
||||
}
|
||||
|
||||
void wifi_ctl_param_reload(void) {
|
||||
char mode_ignored[16];
|
||||
uint8_t ch = 0;
|
||||
wifi_cfg_get_mode(mode_ignored, &ch);
|
||||
if (ch > 0) s_monitor_channel_staging = ch;
|
||||
ESP_LOGI(TAG, "Reloaded monitor channel: %d", s_monitor_channel_staging);
|
||||
}
|
||||
|
||||
void wifi_ctl_param_clear(void) {
|
||||
// 1. Erase NVS
|
||||
wifi_cfg_clear_monitor_channel();
|
||||
|
||||
// 2. Reset RAM Staging to Default (6)
|
||||
s_monitor_channel_staging = 6;
|
||||
|
||||
ESP_LOGI(TAG, "Monitor configuration cleared (Defaulting to Ch 6).");
|
||||
}
|
||||
|
||||
bool wifi_ctl_param_is_unsaved(void) {
|
||||
return wifi_cfg_monitor_channel_is_unsaved(s_monitor_channel_staging);
|
||||
}
|
||||
|
||||
// --- Actions ---
|
||||
|
||||
esp_err_t wifi_ctl_switch_to_monitor(uint8_t channel_override, wifi_bandwidth_t bandwidth) {
|
||||
uint8_t channel = (channel_override > 0) ? channel_override : s_monitor_channel_staging;
|
||||
|
||||
if (s_current_mode == WIFI_CTL_MODE_MONITOR && s_monitor_channel == channel) {
|
||||
esp_err_t wifi_ctl_switch_to_monitor(uint8_t channel, wifi_bandwidth_t bandwidth) {
|
||||
if (s_current_mode == WIFI_CTL_MODE_MONITOR) {
|
||||
ESP_LOGW(TAG, "Already in monitor mode");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// Monitor mode typically requires 20MHz
|
||||
if (bandwidth != WIFI_BW_HT20) {
|
||||
ESP_LOGW(TAG, "Forcing bandwidth to 20MHz for monitor mode");
|
||||
bandwidth = WIFI_BW_HT20;
|
||||
|
|
@ -159,17 +106,22 @@ esp_err_t wifi_ctl_switch_to_monitor(uint8_t channel_override, wifi_bandwidth_t
|
|||
|
||||
ESP_LOGI(TAG, "Switching to MONITOR MODE (Ch %d)", channel);
|
||||
|
||||
// 1. Stop high-level apps
|
||||
iperf_stop();
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
|
||||
// 2. Disable CSI (hardware conflict)
|
||||
// 2. GUARDED CALL
|
||||
#ifdef CONFIG_ESP_WIFI_CSI_ENABLED
|
||||
csi_mgr_disable();
|
||||
#endif
|
||||
|
||||
// 3. Teardown Station
|
||||
esp_wifi_disconnect();
|
||||
esp_wifi_stop();
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
|
||||
// 4. Re-init in NULL/Promiscuous Mode
|
||||
esp_wifi_set_mode(WIFI_MODE_NULL);
|
||||
|
||||
if (wifi_monitor_init(channel, monitor_frame_callback) != ESP_OK) {
|
||||
|
|
@ -184,6 +136,7 @@ esp_err_t wifi_ctl_switch_to_monitor(uint8_t channel_override, wifi_bandwidth_t
|
|||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
// 5. Update State
|
||||
s_monitor_enabled = true;
|
||||
s_current_mode = WIFI_CTL_MODE_MONITOR;
|
||||
s_monitor_channel = channel;
|
||||
|
|
@ -204,29 +157,34 @@ esp_err_t wifi_ctl_switch_to_sta(wifi_band_mode_t band_mode) {
|
|||
|
||||
ESP_LOGI(TAG, "Switching to STA MODE");
|
||||
|
||||
// 1. Stop Monitor Tasks
|
||||
if (s_monitor_stats_task_handle != NULL) {
|
||||
vTaskDelete(s_monitor_stats_task_handle);
|
||||
s_monitor_stats_task_handle = NULL;
|
||||
}
|
||||
|
||||
// 2. Stop Monitor Driver
|
||||
if (s_monitor_enabled) {
|
||||
wifi_monitor_stop();
|
||||
s_monitor_enabled = false;
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
}
|
||||
|
||||
// 3. Re-enable Station Mode
|
||||
esp_wifi_set_mode(WIFI_MODE_STA);
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
|
||||
// 4. Configure & Connect
|
||||
wifi_config_t wifi_config;
|
||||
esp_wifi_get_config(WIFI_IF_STA, &wifi_config);
|
||||
wifi_config.sta.channel = 0;
|
||||
wifi_config.sta.channel = 0; // Auto channel scan
|
||||
|
||||
esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
|
||||
esp_wifi_start();
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
esp_wifi_connect();
|
||||
|
||||
// 5. Update State
|
||||
s_current_mode = WIFI_CTL_MODE_STA;
|
||||
status_led_set_state(LED_STATE_WAITING);
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
#include "esp_err.h"
|
||||
#include "esp_wifi.h"
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
|
|
@ -13,24 +12,44 @@ typedef enum {
|
|||
WIFI_CTL_MODE_MONITOR
|
||||
} wifi_ctl_mode_t;
|
||||
|
||||
/**
|
||||
* @brief Initialize the WiFi Controller
|
||||
*/
|
||||
void wifi_ctl_init(void);
|
||||
|
||||
// --- Parameter Management ---
|
||||
void wifi_ctl_param_set_monitor_channel(uint8_t channel);
|
||||
uint8_t wifi_ctl_param_get_monitor_channel(void);
|
||||
bool wifi_ctl_param_save(void);
|
||||
void wifi_ctl_param_reload(void);
|
||||
bool wifi_ctl_param_is_unsaved(void);
|
||||
void wifi_ctl_param_clear(void);
|
||||
/**
|
||||
* @brief Switch operation mode to Monitor (Sniffer)
|
||||
* @param channel WiFi channel (1-165)
|
||||
* @param bandwidth Bandwidth (usually WIFI_BW_HT20 for monitor)
|
||||
*/
|
||||
esp_err_t wifi_ctl_switch_to_monitor(uint8_t channel, wifi_bandwidth_t bandwidth);
|
||||
|
||||
// --- Actions ---
|
||||
esp_err_t wifi_ctl_switch_to_monitor(uint8_t channel_override, wifi_bandwidth_t bandwidth);
|
||||
/**
|
||||
* @brief Switch operation mode to Station (Client)
|
||||
* @param band_mode Band preference (Auto, 2G only, 5G only)
|
||||
*/
|
||||
esp_err_t wifi_ctl_switch_to_sta(wifi_band_mode_t band_mode);
|
||||
|
||||
/**
|
||||
* @brief Start the auto-monitor task
|
||||
* Waits for connection, waits for GPS, then switches to monitor mode.
|
||||
* @param channel Channel to monitor
|
||||
*/
|
||||
void wifi_ctl_auto_monitor_start(uint8_t channel);
|
||||
|
||||
// --- Getters ---
|
||||
/**
|
||||
* @brief Get current operation mode
|
||||
*/
|
||||
wifi_ctl_mode_t wifi_ctl_get_mode(void);
|
||||
|
||||
/**
|
||||
* @brief Get the current monitor channel
|
||||
*/
|
||||
uint8_t wifi_ctl_get_monitor_channel(void);
|
||||
|
||||
/**
|
||||
* @brief Get total frames captured in monitor mode
|
||||
*/
|
||||
uint32_t wifi_ctl_get_monitor_frame_count(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
|
|
|||
125
esp32_deploy.py
125
esp32_deploy.py
|
|
@ -12,8 +12,6 @@ import logging
|
|||
import glob
|
||||
import random
|
||||
from pathlib import Path
|
||||
from serial.tools import list_ports
|
||||
import subprocess
|
||||
|
||||
# Ensure detection script is available
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
|
@ -58,35 +56,13 @@ def generate_config_suffix(target, csi, ampdu):
|
|||
return f"{target}_{csi_str}_{ampdu_str}"
|
||||
|
||||
def auto_detect_devices():
|
||||
"""Prioritizes static udev paths (/dev/esp_port_XX) and removes duplicates."""
|
||||
"""Prioritizes static udev paths (/dev/esp_port_XX) if they exist."""
|
||||
try:
|
||||
ports = glob.glob('/dev/esp_port_*')
|
||||
if ports:
|
||||
# --- New Deduplication Logic ---
|
||||
unique_map = {}
|
||||
for p in ports:
|
||||
try:
|
||||
# Resolve symlink (e.g., /dev/esp_port_01 -> /dev/ttyUSB0)
|
||||
real_path = os.path.realpath(p)
|
||||
|
||||
if real_path not in unique_map:
|
||||
unique_map[real_path] = p
|
||||
else:
|
||||
# Conflict! We have both esp_port_1 and esp_port_01.
|
||||
# Keep the "shorter" one (esp_port_1) to match your new scheme.
|
||||
current_alias = unique_map[real_path]
|
||||
if len(p) < len(current_alias):
|
||||
unique_map[real_path] = p
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
# Use the filtered list
|
||||
ports = list(unique_map.values())
|
||||
# -------------------------------
|
||||
|
||||
# Sort by suffix number
|
||||
ports.sort(key=lambda x: int(re.search(r'(\d+)$', x).group(1)) if re.search(r'(\d+)$', x) else 0)
|
||||
print(f"{Colors.CYAN}Auto-detected {len(ports)} devices (filtered from {len(unique_map) + (len(glob.glob('/dev/esp_port_*')) - len(unique_map))} aliases).{Colors.RESET}")
|
||||
print(f"{Colors.CYAN}Auto-detected {len(ports)} devices using static udev rules.{Colors.RESET}")
|
||||
return [type('obj', (object,), {'device': p}) for p in ports]
|
||||
except Exception:
|
||||
pass
|
||||
|
|
@ -368,81 +344,6 @@ class UnifiedDeployWorker:
|
|||
self.log.error(f"Flash Prep Error: {e}")
|
||||
return False
|
||||
|
||||
def update_udev_map(dry_run=False):
|
||||
"""
|
||||
Scans all USB serial devices, sorts them by physical topology (Bus/Port),
|
||||
and generates a udev rule file to map them to /dev/esp_port_XX.
|
||||
"""
|
||||
print(f"{Colors.BLUE}Scanning USB topology to generate stable port maps...{Colors.RESET}")
|
||||
|
||||
# Get all USB serial devices
|
||||
devices = list(list_ports.grep("USB|ACM|CP210|FT232"))
|
||||
|
||||
if not devices:
|
||||
print(f"{Colors.RED}No devices found.{Colors.RESET}")
|
||||
return
|
||||
|
||||
# Sort by "location" (Physical USB path: e.g., 1-1.2.3)
|
||||
# This guarantees esp_port_01 is always the first physical port.
|
||||
devices.sort(key=lambda x: x.location if x.location else x.device)
|
||||
|
||||
generated_rules = []
|
||||
print(f"{'Physical Path':<20} | {'Current Dev':<15} | {'Assigned Symlink'}")
|
||||
print("-" * 65)
|
||||
|
||||
for i, dev in enumerate(devices):
|
||||
port_num = i + 1
|
||||
symlink = f"esp_port_{port_num}" # e.g., esp_port_1
|
||||
|
||||
# Get detailed udev info to find the stable physical path ID
|
||||
try:
|
||||
cmd = ['udevadm', 'info', '--name', dev.device, '--query=property']
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
props = dict(line.split('=', 1) for line in proc.stdout.splitlines() if '=' in line)
|
||||
|
||||
# ID_PATH is the robust physical identifier (e.g., pci-0000:00:14.0-usb-0:1.4.3:1.0)
|
||||
dev_path = props.get('ID_PATH', '')
|
||||
|
||||
if not dev_path:
|
||||
print(f"{Colors.YELLOW}Skipping {dev.device} (No ID_PATH found){Colors.RESET}")
|
||||
continue
|
||||
|
||||
# Generate the rule
|
||||
rule = f'SUBSYSTEM=="tty", ENV{{ID_PATH}}=="{dev_path}", SYMLINK+="{symlink}"'
|
||||
generated_rules.append(rule)
|
||||
|
||||
print(f"{dev.location:<20} | {dev.device:<15} | {symlink}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error inspecting {dev.device}: {e}")
|
||||
|
||||
print("-" * 65)
|
||||
|
||||
rules_content = "# Auto-generated by esp32_deploy.py\n" + "\n".join(generated_rules) + "\n"
|
||||
rule_file = "/etc/udev/rules.d/99-esp32-stable.rules"
|
||||
|
||||
if dry_run:
|
||||
print(f"\n{Colors.YELLOW}--- DRY RUN: Rules that would be written to {rule_file} ---{Colors.RESET}")
|
||||
print(rules_content)
|
||||
else:
|
||||
if os.geteuid() != 0:
|
||||
print(f"\n{Colors.RED}ERROR: Root privileges required to write udev rules.{Colors.RESET}")
|
||||
print(f"Run: sudo ./esp32_deploy.py --map-ports")
|
||||
return
|
||||
|
||||
print(f"\nWriting rules to {rule_file}...")
|
||||
try:
|
||||
with open(rule_file, 'w') as f:
|
||||
f.write(rules_content)
|
||||
|
||||
print("Reloading udev rules...")
|
||||
subprocess.run(['udevadm', 'control', '--reload-rules'], check=True)
|
||||
subprocess.run(['udevadm', 'trigger'], check=True)
|
||||
print(f"{Colors.GREEN}Success! Devices re-mapped.{Colors.RESET}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"{Colors.RED}Failed to write rules: {e}{Colors.RESET}")
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description='ESP32 Unified Deployment Tool')
|
||||
parser.add_argument('-i', '--interactive', action='store_true', help='Prompt for build options')
|
||||
|
|
@ -479,9 +380,8 @@ def parse_args():
|
|||
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')
|
||||
parser.add_argument('--map-ports', action='store_true', help="Rescan USB topology and generate udev rules for esp_port_xx")
|
||||
args = parser.parse_args()
|
||||
if args.target != 'all' and not args.start_ip and not args.check_version and not args.map_ports:
|
||||
if args.target != 'all' and not args.start_ip and not args.check_version:
|
||||
parser.error("the following arguments are required: --start-ip")
|
||||
if args.config_only and args.flash_only: parser.error("Conflicting modes")
|
||||
return args
|
||||
|
|
@ -653,22 +553,9 @@ async def run_deployment(args):
|
|||
print(f"\n{Colors.BLUE}Summary: {success}/{len(devs)} Success{Colors.RESET}")
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
|
||||
# --- INTERCEPT --map-ports HERE ---
|
||||
if args.map_ports:
|
||||
# Run synchronously, no async loop needed
|
||||
update_udev_map(dry_run=False)
|
||||
sys.exit(0)
|
||||
|
||||
# Standard async deployment flow
|
||||
if os.name == 'nt':
|
||||
asyncio.set_event_loop(asyncio.ProactorEventLoop())
|
||||
|
||||
try:
|
||||
asyncio.run(run_deployment(args))
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(1)
|
||||
if os.name == 'nt': asyncio.set_event_loop(asyncio.ProactorEventLoop())
|
||||
try: asyncio.run(run_deployment(parse_args()))
|
||||
except KeyboardInterrupt: sys.exit(1)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
|
|||
|
|
@ -2,47 +2,44 @@
|
|||
#define BOARD_CONFIG_H
|
||||
|
||||
#include "sdkconfig.h"
|
||||
#include "driver/gpio.h"
|
||||
|
||||
|
||||
#if defined (CONFIG_IDF_TARGET_ESP32C5)
|
||||
// ============================================================================
|
||||
// ESP32-C5 (DevKitC-1) 3.3V VCC Pin 1 GND PIN 15
|
||||
// ESP32-C5 (DevKitC-1)
|
||||
// ============================================================================
|
||||
#ifdef CONFIG_IDF_TARGET_ESP32C5
|
||||
#define RGB_LED_GPIO 8 // Common addressable LED pin for C5
|
||||
#define HAS_RGB_LED 1
|
||||
#define GPS_TX_PIN GPIO_NUM_24
|
||||
#define GPS_RX_PIN GPIO_NUM_23
|
||||
#define GPS_PPS_PIN GPIO_NUM_25
|
||||
#elif defined (CONFIG_IDF_TARGET_ESP32S3)
|
||||
#endif
|
||||
|
||||
// ============================================================================
|
||||
// ESP32-S3 (DevKitC-1)
|
||||
// Most S3 DevKits use GPIO 48 for the addressable RGB LED.
|
||||
// If yours uses GPIO 38, change this value.
|
||||
// ============================================================================
|
||||
#ifdef CONFIG_IDF_TARGET_ESP32S3
|
||||
// Most S3 DevKits use GPIO 48 for the addressable RGB LED.
|
||||
// If yours uses GPIO 38, change this value.
|
||||
#define RGB_LED_GPIO 48
|
||||
#define HAS_RGB_LED 1
|
||||
#define GPS_TX_PIN GPIO_NUM_5
|
||||
#define GPS_RX_PIN GPIO_NUM_4
|
||||
#define GPS_PPS_PIN GPIO_NUM_6
|
||||
#elif defined (CONFIG_IDF_TARGET_ESP32)
|
||||
#endif
|
||||
|
||||
// ============================================================================
|
||||
// ESP32 (Original / Standard)
|
||||
// Standard ESP32 DevKits usually have a single blue LED on GPIO 2.
|
||||
// They rarely have an addressable RGB LED built-in.
|
||||
// ============================================================================
|
||||
#define RGB_LED_GPIO 2 // Standard Blue LED
|
||||
#define HAS_RGB_LED 0 // Not RGB
|
||||
#define GPS_TX_PIN GPIO_NUM_17
|
||||
#define GPS_RX_PIN GPIO_NUM_16
|
||||
#define GPS_PPS_PIN GPIO_NUM_4
|
||||
#else
|
||||
// Fallback
|
||||
#define RGB_LED_GPIO 8
|
||||
#define HAS_RGB_LED 1
|
||||
#define GPS_TX_PIN GPIO_NUM_1
|
||||
#define GPS_RX_PIN GPIO_NUM_3
|
||||
#define GPS_PPS_PIN GPIO_NUM_5
|
||||
#ifdef CONFIG_IDF_TARGET_ESP32
|
||||
// Standard ESP32 DevKits usually have a single blue LED on GPIO 2.
|
||||
// They rarely have an addressable RGB LED built-in.
|
||||
#define RGB_LED_GPIO 2
|
||||
#define HAS_RGB_LED 0
|
||||
#endif
|
||||
|
||||
// ============================================================================
|
||||
// Fallbacks (Prevent Compilation Errors)
|
||||
// ============================================================================
|
||||
#ifndef RGB_LED_GPIO
|
||||
#define RGB_LED_GPIO 2
|
||||
#endif
|
||||
|
||||
#ifndef HAS_RGB_LED
|
||||
#define HAS_RGB_LED 0
|
||||
#endif
|
||||
|
||||
#endif // BOARD_CONFIG_H
|
||||
|
|
|
|||
43
main/main.c
43
main/main.c
|
|
@ -15,11 +15,9 @@
|
|||
// Components
|
||||
#include "status_led.h"
|
||||
#include "board_config.h"
|
||||
#include "gps_sync.h"
|
||||
#include "wifi_controller.h"
|
||||
#include "wifi_cfg.h"
|
||||
#include "app_console.h"
|
||||
#include "iperf.h"
|
||||
|
||||
#ifdef CONFIG_ESP_WIFI_CSI_ENABLED
|
||||
#include "csi_log.h"
|
||||
|
|
@ -30,25 +28,6 @@
|
|||
|
||||
static const char *TAG = "MAIN";
|
||||
|
||||
// --- Global Prompt Buffer (Mutable) ---
|
||||
static char s_cli_prompt[32] = "esp32> ";
|
||||
|
||||
// --- Prompt Updater ---
|
||||
// This is called by app_console.c commands whenever a setting is changed.
|
||||
void app_console_update_prompt(void) {
|
||||
bool dirty = false;
|
||||
|
||||
// Check if any component has unsaved changes (RAM != NVS)
|
||||
if (wifi_ctl_param_is_unsaved()) dirty = true;
|
||||
if (iperf_param_is_unsaved()) dirty = true;
|
||||
|
||||
if (dirty) {
|
||||
snprintf(s_cli_prompt, sizeof(s_cli_prompt), "esp32*> ");
|
||||
} else {
|
||||
snprintf(s_cli_prompt, sizeof(s_cli_prompt), "esp32> ");
|
||||
}
|
||||
}
|
||||
|
||||
// --- System Commands ---
|
||||
|
||||
static int cmd_restart(int argc, char **argv) {
|
||||
|
|
@ -93,13 +72,6 @@ void app_main(void) {
|
|||
// 2. Initialize Netif & Event Loop
|
||||
ESP_ERROR_CHECK(esp_netif_init());
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
const gps_sync_config_t gps_cfg = {
|
||||
.uart_port = UART_NUM_1,
|
||||
.tx_pin = GPS_TX_PIN,
|
||||
.rx_pin = GPS_RX_PIN,
|
||||
.pps_pin = GPS_PPS_PIN,
|
||||
};
|
||||
gps_sync_init(&gps_cfg, true);
|
||||
|
||||
// 3. Hardware Init
|
||||
status_led_init(RGB_LED_GPIO, HAS_RGB_LED);
|
||||
|
|
@ -108,18 +80,15 @@ void app_main(void) {
|
|||
csi_mgr_init();
|
||||
#endif
|
||||
|
||||
// 4. Initialize WiFi Controller & iPerf
|
||||
// 4. Initialize WiFi Controller (Loads config from NVS automatically)
|
||||
wifi_ctl_init();
|
||||
iperf_param_init();
|
||||
|
||||
// 5. Initialize Console
|
||||
esp_console_repl_t *repl = NULL;
|
||||
esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// CRITICAL FIX: Use the mutable buffer, NOT a string literal
|
||||
// ---------------------------------------------------------
|
||||
repl_config.prompt = s_cli_prompt;
|
||||
// This prompt is the anchor for your Python script
|
||||
repl_config.prompt = "esp32> ";
|
||||
repl_config.max_cmdline_length = 1024;
|
||||
|
||||
// Install UART driver for Console (Standard IO)
|
||||
|
|
@ -130,14 +99,12 @@ void app_main(void) {
|
|||
register_system_common();
|
||||
app_console_register_commands();
|
||||
|
||||
// 7. Initial Prompt State Check
|
||||
app_console_update_prompt();
|
||||
|
||||
// 8. Start Shell
|
||||
// 7. Start Shell
|
||||
printf("\n ==================================================\n");
|
||||
printf(" | ESP32 iPerf Shell - Ready |\n");
|
||||
printf(" | Type 'help' for commands |\n");
|
||||
printf(" ==================================================\n");
|
||||
|
||||
// This function runs the REPL loop and does not return
|
||||
ESP_ERROR_CHECK(esp_console_start_repl(repl));
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue