From b769dbc35655f4ca43d8aba698574654f8f1eb01 Mon Sep 17 00:00:00 2001 From: Robert McMahon Date: Mon, 22 Dec 2025 13:06:05 -0800 Subject: [PATCH] more on gps time --- components/app_console/cmd_gps.c | 157 +++---- components/gps_sync/gps_sync.c | 445 +++++++------------ components/gps_sync/gps_sync.h | 45 +- components/iperf/iperf.c | 26 +- components/wifi_controller/wifi_controller.c | 10 +- 5 files changed, 291 insertions(+), 392 deletions(-) diff --git a/components/app_console/cmd_gps.c b/components/app_console/cmd_gps.c index 706ed39..cbe057a 100644 --- a/components/app_console/cmd_gps.c +++ b/components/app_console/cmd_gps.c @@ -30,125 +30,116 @@ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ - #include #include -#include #include +#include +#include #include "esp_log.h" #include "esp_console.h" #include "argtable3/argtable3.h" -#include "nvs_flash.h" -#include "nvs.h" #include "gps_sync.h" #include "app_console.h" +// --- Forward Declarations --- +static int gps_do_status(int argc, char **argv); + // ============================================================================ -// COMMAND: gps (Configure & Status) +// COMMAND: gps (Dispatcher) // ============================================================================ -static struct { - struct arg_lit *enable; - struct arg_lit *disable; - struct arg_lit *status; - struct arg_lit *help; - struct arg_end *end; -} gps_args; +static void print_gps_usage(void) { + printf("Usage: gps [args]\n"); + printf("Subcommands:\n"); + printf(" status Show GPS lock status, time, and last NMEA message\n"); + printf("\nType 'gps --help' for details.\n"); +} static int cmd_gps(int argc, char **argv) { - int nerrors = arg_parse(argc, argv, (void **)&gps_args); - if (nerrors > 0) { - arg_print_errors(stderr, gps_args.end, argv[0]); - return 1; - } - - if (gps_args.help->count > 0) { - printf("Usage: gps [--enable|--disable|--status]\n"); + if (argc < 2 || strcmp(argv[1], "help") == 0 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) { + print_gps_usage(); return 0; } - nvs_handle_t h; - esp_err_t err = nvs_open("storage", NVS_READWRITE, &h); - if (err != ESP_OK) { - printf("Error opening NVS: %s\n", esp_err_to_name(err)); + if (strcmp(argv[1], "status") == 0) return gps_do_status(argc - 1, &argv[1]); + if (strcmp(argv[1], "info") == 0) return gps_do_status(argc - 1, &argv[1]); // Alias + + printf("Unknown subcommand '%s'.\n", argv[1]); + print_gps_usage(); + return 1; +} + +// ---------------------------------------------------------------------------- +// Sub-command: status +// ---------------------------------------------------------------------------- +static struct { + struct arg_lit *help; + struct arg_end *end; +} status_args; + +static int gps_do_status(int argc, char **argv) { + status_args.help = arg_lit0("h", "help", "Help"); + status_args.end = arg_end(1); + + int nerrors = arg_parse(argc, argv, (void **)&status_args); + if (nerrors > 0) { + arg_print_errors(stderr, status_args.end, argv[0]); return 1; } - // --- HANDLE SETTERS --- - bool changed = false; - if (gps_args.enable->count > 0) { - nvs_set_u8(h, "gps_enabled", 1); - printf("GPS set to ENABLED. (Reboot required)\n"); - changed = true; - } else if (gps_args.disable->count > 0) { - nvs_set_u8(h, "gps_enabled", 0); - printf("GPS set to DISABLED. (Reboot required)\n"); - changed = true; + if (status_args.help->count > 0) { + printf("Usage: gps status\n"); + return 0; } - if (changed) nvs_commit(h); + // 1. Get GPS Data + gps_timestamp_t ts = gps_get_timestamp(); + int64_t pps_age = gps_get_pps_age_ms(); - // --- DISPLAY STATUS --- - // 1. NVS State - uint8_t val = 1; - if (nvs_get_u8(h, "gps_enabled", &val) != ESP_OK) val = 1; // Default true - printf("GPS NVS State: %s\n", val ? "ENABLED" : "DISABLED"); - nvs_close(h); + char nmea_buf[128] = ""; + gps_get_last_nmea(nmea_buf, sizeof(nmea_buf)); - // 2. Runtime Status - if (val) { - gps_timestamp_t ts = gps_get_timestamp(); - int64_t pps_age = gps_get_pps_age_ms(); + // Strip trailing newline + size_t len = strlen(nmea_buf); + if (len > 0 && (nmea_buf[len-1] == '\n' || nmea_buf[len-1] == '\r')) nmea_buf[len-1] = 0; - printf("Status: %s\n", ts.synced ? "SYNCED" : "SEARCHING"); + // 2. Format Time + char time_str[64] = "Unknown"; + struct timespec ts_now = {0, 0}; - // Print Raw NMEA - char nmea_buf[128]; - gps_get_last_nmea(nmea_buf, sizeof(nmea_buf)); + if (ts.gps_us > 0) { + // Get raw timespec for display + clock_gettime(CLOCK_REALTIME, &ts_now); - // Cleanup CR/LF for printing - size_t len = strlen(nmea_buf); - if (len > 0 && (nmea_buf[len-1] == '\r' || nmea_buf[len-1] == '\n')) nmea_buf[len-1] = 0; - if (len > 1 && (nmea_buf[len-2] == '\r' || nmea_buf[len-2] == '\n')) nmea_buf[len-2] = 0; - - printf("Last NMEA: [%s]\n", nmea_buf); - - if (pps_age < 0) { - printf("PPS Signal: NEVER DETECTED\n"); - } else if (pps_age > 1100) { - printf("PPS Signal: LOST (Last seen %" PRId64 " ms ago)\n", pps_age); - } else { - printf("PPS Signal: ACTIVE (Age: %" PRId64 " ms)\n", pps_age); - } - - if (ts.gps_us > 0) { - time_t now_sec = ts.gps_us / 1000000; - struct tm tm_info; - gmtime_r(&now_sec, &tm_info); - char time_buf[64]; - strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S UTC", &tm_info); - printf("Current Time: %s\n", time_buf); - } else { - printf("Current Time: (System Epoch)\n"); - } + time_t now_sec = ts_now.tv_sec; + struct tm tm_info; + gmtime_r(&now_sec, &tm_info); + strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S UTC", &tm_info); } - app_console_update_prompt(); + // 3. Print + printf("GPS Status:\n"); + printf(" Time: %s\n", time_str); + // UPDATED: Show raw timespec structure + printf(" Timespec: tv_sec=%" PRId64 " tv_nsec=%ld\n", (int64_t)ts_now.tv_sec, ts_now.tv_nsec); + printf(" PPS Locked: %s (Age: %" PRId64 " ms)\n", ts.synced ? "YES" : "NO", pps_age); + printf(" NMEA Valid: %s\n", ts.valid ? "YES" : "NO"); + printf(" Last Message: %s\n", nmea_buf); + return 0; } -void register_gps_cmd(void) { - gps_args.enable = arg_lit0(NULL, "enable", "Enable GPS"); - gps_args.disable = arg_lit0(NULL, "disable", "Disable GPS"); - gps_args.status = arg_lit0(NULL, "status", "Show Status"); - gps_args.help = arg_lit0("h", "help", "Help"); - gps_args.end = arg_end(2); +// ---------------------------------------------------------------------------- +// Registration +// ---------------------------------------------------------------------------- +void register_gps_cmd(void) { const esp_console_cmd_t cmd = { .command = "gps", - .help = "Configure GPS", + .help = "GPS Tool: status", + .hint = "", .func = &cmd_gps, - .argtable = &gps_args + .argtable = NULL }; ESP_ERROR_CHECK(esp_console_cmd_register(&cmd)); } diff --git a/components/gps_sync/gps_sync.c b/components/gps_sync/gps_sync.c index 6949ce9..19525dd 100644 --- a/components/gps_sync/gps_sync.c +++ b/components/gps_sync/gps_sync.c @@ -30,341 +30,230 @@ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ - -#include "gps_sync.h" -#include "driver/gpio.h" -#include "driver/uart.h" -#include "esp_timer.h" -#include "esp_log.h" -#include "esp_rom_sys.h" -#include -#include -#include #include -#include -#include +#include +#include +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_log.h" +#include "esp_timer.h" +#include "driver/uart.h" +#include "driver/gpio.h" +#include "gps_sync.h" static const char *TAG = "GPS_SYNC"; -#define GPS_BAUD_RATE 9600 -#define UART_BUF_SIZE 1024 +#define GPS_BUF_SIZE 1024 -// --- GLOBAL STATE --- -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 bool gps_has_fix = false; -static bool use_gps_for_logs = false; -static SemaphoreHandle_t sync_mutex; -static volatile bool force_sync_update = true; +// --- Internal State --- +static gps_sync_config_t s_cfg; +static volatile int64_t s_last_pps_us = 0; +static volatile int64_t s_nmea_epoch_us = 0; +static volatile bool s_nmea_valid = false; +static char s_last_nmea_msg[128] = {0}; +static bool s_time_set = false; -// Debug Buffer -static char s_last_nmea_line[128] = ""; - -// PPS interrupt: Captures the exact monotonic time of the rising edge -static void IRAM_ATTR pps_isr_handler(void* arg) { - int64_t now = esp_timer_get_time(); - last_pps_monotonic = now; +// --- PPS Handler --- +static void IRAM_ATTR pps_gpio_isr_handler(void* arg) { + s_last_pps_us = esp_timer_get_time(); } -// Parse GPS time from NMEA (GPRMC or GNRMC) -static bool parse_gprmc(const char* nmea, struct tm* tm_out, bool* valid) { - if (strncmp(nmea, "$GPRMC", 6) != 0 && strncmp(nmea, "$GNRMC", 6) != 0) return false; +// --- Time Helper --- +static void set_system_time(char *time_str, char *date_str) { + // time_str: HHMMSS.ss (e.g., 123519.00) + // date_str: DDMMYY (e.g., 230394) - char *p = strchr(nmea, ','); - if (!p) return false; - p++; // Move past comma + struct tm tm_info = {0}; - int hour, min, sec; - if (sscanf(p, "%2d%2d%2d", &hour, &min, &sec) != 3) return false; + // Parse Time + int h, m, s; + if (sscanf(time_str, "%2d%2d%2d", &h, &m, &s) != 3) return; + tm_info.tm_hour = h; + tm_info.tm_min = m; + tm_info.tm_sec = s; - p = strchr(p, ','); - if (!p) return false; - p++; - *valid = (*p == 'A'); + // Parse Date + int day, mon, year; + if (sscanf(date_str, "%2d%2d%2d", &day, &mon, &year) != 3) return; + tm_info.tm_mday = day; + tm_info.tm_mon = mon - 1; // 0-11 + tm_info.tm_year = year + 100; // Years since 1900 (2025 -> 125) - for (int i = 0; i < 7; i++) { - p = strchr(p, ','); - if (!p) return false; - p++; + time_t t = mktime(&tm_info); + if (t == -1) return; + + struct timeval tv = { .tv_sec = t, .tv_usec = 0 }; + + // Simple sync: Only set if not set, or if drift is massive (>2s) + // In a real PTP/GPS app you'd use a PLL here, but this is a shell tool. + struct timeval now; + gettimeofday(&now, NULL); + + if (!s_time_set || llabs(now.tv_sec - t) > 2) { + settimeofday(&tv, NULL); + s_time_set = true; + ESP_LOGI(TAG, "System Time Updated to GPS: %s", asctime(&tm_info)); } - - int day, month, year; - if (sscanf(p, "%2d%2d%2d", &day, &month, &year) != 3) return false; - - 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_out->tm_year = year - 1900; - tm_out->tm_isdst = 0; - - return true; } -void gps_force_next_update(void) { - force_sync_update = true; - ESP_LOGW(TAG, "Requesting forced GPS sync update"); -} +// --- NMEA Parser --- +static void parse_nmea_line(char *line) { + strlcpy(s_last_nmea_msg, line, sizeof(s_last_nmea_msg)); -static time_t timegm_impl(struct tm *tm) { - time_t t = mktime(tm); - return t; -} + // Support GPRMC and GNRMC + if (strncmp(line, "$GPRMC", 6) == 0 || strncmp(line, "$GNRMC", 6) == 0) { + char *p = line; + int field = 0; + char *time_ptr = NULL; + char *date_ptr = NULL; + char status = 'V'; -static void gps_task(void* arg) { - uint8_t d_buf[64]; - char line[128]; - int pos = 0; - static int log_counter = 0; + // Walk fields + // $GPRMC,Time,Status,Lat,NS,Lon,EW,Spd,Trk,Date,... + // Field 1: Time + // Field 2: Status + // Field 9: Date - setenv("TZ", "UTC", 1); - tzset(); + while ((p = strchr(p, ',')) != NULL) { + p++; + field++; - while (1) { - int len = uart_read_bytes(gps_uart_num, d_buf, sizeof(d_buf), pdMS_TO_TICKS(100)); + if (field == 1) time_ptr = p; + else if (field == 2) status = *p; + else if (field == 9) { + date_ptr = p; + break; // We have what we need + } + } - if (len > 0) { - for (int i = 0; i < len; i++) { - uint8_t data = d_buf[i]; + s_nmea_valid = (status == 'A'); - if (data == '\n' || data == '\r') { - if (pos > 0) { - line[pos] = '\0'; + if (s_nmea_valid) { + s_nmea_epoch_us = esp_timer_get_time(); - // Copy to debug buffer - xSemaphoreTake(sync_mutex, portMAX_DELAY); - strncpy(s_last_nmea_line, line, sizeof(s_last_nmea_line) - 1); - s_last_nmea_line[sizeof(s_last_nmea_line) - 1] = '\0'; - xSemaphoreGive(sync_mutex); + // Extract substrings for Time/Date (comma terminated) + if (time_ptr && date_ptr) { + char t_buf[16] = {0}; + char d_buf[16] = {0}; - struct tm gps_tm; - bool valid_fix; - - if (parse_gprmc(line, &gps_tm, &valid_fix)) { - if (valid_fix) { - time_t gps_time_sec = timegm_impl(&gps_tm); - int64_t last_pps_snap = last_pps_monotonic; - int64_t now = esp_timer_get_time(); - int64_t age_us = now - last_pps_snap; - - if (last_pps_snap > 0 && age_us < 900000) { - - int64_t gps_time_us = (int64_t)gps_time_sec * 1000000LL; - int64_t new_offset = gps_time_us - last_pps_snap; - - xSemaphoreTake(sync_mutex, portMAX_DELAY); - if (monotonic_offset_us == 0 || force_sync_update) { - monotonic_offset_us = new_offset; - if (force_sync_update) { - ESP_LOGW(TAG, "GPS SNAP: Offset forced to %" PRIi64 " us", monotonic_offset_us); - force_sync_update = false; - log_counter = 0; - } - } else { - monotonic_offset_us = (monotonic_offset_us * 9 + new_offset) / 10; - } - gps_has_fix = true; - xSemaphoreGive(sync_mutex); - - // Periodic Logging - if (log_counter <= 0) { - // CHANGED FROM ESP_LOGI TO ESP_LOGD (Hidden by default) - ESP_LOGD(TAG, "GPS Sync: %02d:%02d:%02d | Offset: %" PRIi64 " us | PPS Age: %" PRIi64 " ms", - gps_tm.tm_hour, gps_tm.tm_min, gps_tm.tm_sec, - monotonic_offset_us, age_us / 1000); - log_counter = 10; - } - log_counter--; - - } else { - // Keep Warnings visible - if (log_counter <= 0) { - ESP_LOGW(TAG, "GPS valid but PPS missing/old (Age: %" PRIi64 " ms)", age_us / 1000); - log_counter = 10; - } - log_counter--; - } - } else { - gps_has_fix = false; - } - } + char *end = strchr(time_ptr, ','); + if (end) { + int len = end - time_ptr; + if (len < sizeof(t_buf)) { + memcpy(t_buf, time_ptr, len); + t_buf[len] = 0; } - pos = 0; - } else { - if (pos < sizeof(line) - 1) { - line[pos++] = data; + } + + end = strchr(date_ptr, ','); + if (end) { + int len = end - date_ptr; + if (len < sizeof(d_buf)) { + memcpy(d_buf, date_ptr, len); + d_buf[len] = 0; } } + + // Update System Clock + if (t_buf[0] && d_buf[0]) { + set_system_time(t_buf, d_buf); + } } } } } -void gps_get_last_nmea(char *buf, size_t max_len) { - if (!buf || max_len == 0) return; - xSemaphoreTake(sync_mutex, portMAX_DELAY); - strncpy(buf, s_last_nmea_line, max_len); - buf[max_len - 1] = '\0'; - xSemaphoreGive(sync_mutex); +// --- UART Task --- +static void gps_task(void *pvParameters) { + uint8_t *data = (uint8_t *)malloc(GPS_BUF_SIZE); + if (!data) { + ESP_LOGE(TAG, "Failed to allocate GPS buffer"); + vTaskDelete(NULL); + return; + } + + char line_buf[128]; + int line_pos = 0; + + while (1) { + int len = uart_read_bytes(s_cfg.uart_port, data, GPS_BUF_SIZE, 20 / portTICK_PERIOD_MS); + if (len > 0) { + for (int i = 0; i < len; i++) { + char c = (char)data[i]; + if (c == '\n' || c == '\r') { + if (line_pos > 0) { + line_buf[line_pos] = 0; + parse_nmea_line(line_buf); + line_pos = 0; + } + } else if (line_pos < sizeof(line_buf) - 1) { + line_buf[line_pos++] = c; + } + } + } + } + free(data); + vTaskDelete(NULL); } -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); +// --- API --- - gpio_config_t pps_poll_conf = { - .pin_bit_mask = (1ULL << config->pps_pin), - .mode = GPIO_MODE_INPUT, - .pull_up_en = GPIO_PULLUP_DISABLE, - .pull_down_en = GPIO_PULLDOWN_DISABLE, - .intr_type = GPIO_INTR_DISABLE - }; - ESP_ERROR_CHECK(gpio_config(&pps_poll_conf)); - - bool pps_detected = false; - int start_level = gpio_get_level(config->pps_pin); - for (int i = 0; i < 2000; i++) { - if (gpio_get_level(config->pps_pin) != start_level) { - pps_detected = true; - break; - } - vTaskDelay(pdMS_TO_TICKS(1)); - } - - if (!pps_detected) { - ESP_LOGW(TAG, "No PPS signal detected on GPIO %d during boot check.", config->pps_pin); - } else { - ESP_LOGI(TAG, "PPS signal activity detected."); - } - - 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_log_set_vprintf(gps_log_vprintf); - } +void gps_sync_init(const gps_sync_config_t *cfg, bool force_enable) { + if (!cfg) return; + s_cfg = *cfg; uart_config_t uart_config = { - .baud_rate = GPS_BAUD_RATE, + .baud_rate = 9600, .data_bits = UART_DATA_8_BITS, - .parity = UART_PARITY_DISABLE, + .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1, .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, .source_clk = UART_SCLK_DEFAULT, }; + uart_driver_install(s_cfg.uart_port, GPS_BUF_SIZE * 2, 0, 0, NULL, 0); + uart_param_config(s_cfg.uart_port, &uart_config); + uart_set_pin(s_cfg.uart_port, s_cfg.tx_pin, s_cfg.rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE); - 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)); - - gpio_config_t pps_intr_conf = { - .intr_type = GPIO_INTR_POSEDGE, - .mode = GPIO_MODE_INPUT, - .pin_bit_mask = (1ULL << config->pps_pin), - .pull_up_en = GPIO_PULLUP_DISABLE, - .pull_down_en = GPIO_PULLDOWN_DISABLE, - }; - ESP_ERROR_CHECK(gpio_config(&pps_intr_conf)); + gpio_config_t io_conf = {}; + io_conf.intr_type = GPIO_INTR_POSEDGE; + io_conf.pin_bit_mask = (1ULL << s_cfg.pps_pin); + io_conf.mode = GPIO_MODE_INPUT; + io_conf.pull_up_en = 1; + gpio_config(&io_conf); gpio_install_isr_service(0); - ESP_ERROR_CHECK(gpio_isr_handler_add(config->pps_pin, pps_isr_handler, NULL)); + gpio_isr_handler_add(s_cfg.pps_pin, pps_gpio_isr_handler, NULL); xTaskCreate(gps_task, "gps_task", 4096, NULL, 5, NULL); + + ESP_LOGI(TAG, "Initialized (UART:%d, PPS:%d)", s_cfg.uart_port, s_cfg.pps_pin); } gps_timestamp_t gps_get_timestamp(void) { - gps_timestamp_t ts; - clock_gettime(CLOCK_MONOTONIC, &ts.mono_ts); + gps_timestamp_t ts = {0}; + int64_t now_boot = esp_timer_get_time(); // Boot time - ts.monotonic_us = (int64_t)ts.mono_ts.tv_sec * 1000000LL + ts.mono_ts.tv_nsec / 1000; - ts.monotonic_ms = ts.monotonic_us / 1000; + // Check Flags + ts.synced = (now_boot - s_last_pps_us < 1100000); + ts.valid = s_nmea_valid && (now_boot - s_nmea_epoch_us < 2000000); - xSemaphoreTake(sync_mutex, portMAX_DELAY); - ts.gps_us = ts.monotonic_us + monotonic_offset_us; - ts.synced = gps_has_fix; - xSemaphoreGive(sync_mutex); + // Return WALL CLOCK time (Epoch), not boot time + struct timeval tv; + gettimeofday(&tv, NULL); + ts.gps_us = (int64_t)tv.tv_sec * 1000000LL + (int64_t)tv.tv_usec; - ts.gps_ms = ts.gps_us / 1000; return ts; } -int64_t gps_get_monotonic_ms(void) { - return esp_timer_get_time() / 1000; -} - -bool gps_is_synced(void) { - return gps_has_fix; -} - -// --- NEW: PPS Age Getter --- int64_t gps_get_pps_age_ms(void) { - if (last_pps_monotonic == 0) return -1; - int64_t now = esp_timer_get_time(); - return (now - last_pps_monotonic) / 1000; + if (s_last_pps_us == 0) return -1; + return (esp_timer_get_time() - s_last_pps_us) / 1000; } -// ---------------- LOGGING SYSTEM INTERCEPTION ---------------- - -uint32_t gps_log_timestamp(void) { - return (uint32_t)(esp_timer_get_time() / 1000ULL); -} - -int gps_log_vprintf(const char *fmt, va_list args) { - static char buffer[512]; - int ret = vsnprintf(buffer, sizeof(buffer), fmt, args); - assert(ret >= 0); - - if (use_gps_for_logs) { - char *timestamp_start = NULL; - 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') && - buffer[i+1] == ' ' && buffer[i+2] == '(') { - timestamp_start = &buffer[i+3]; - break; - } - } - - if (timestamp_start) { - char *timestamp_end = strchr(timestamp_start, ')'); - if (timestamp_end) { - uint32_t monotonic_log_ms = 0; - if (sscanf(timestamp_start, "%lu", &monotonic_log_ms) == 1) { - char reformatted[512]; - size_t prefix_len = timestamp_start - buffer; - - 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; - - uint64_t gps_sec = log_gps_us / 1000000; - uint32_t gps_ms = (log_gps_us % 1000000) / 1000; - - decimal_len = snprintf(reformatted + prefix_len, - sizeof(reformatted) - prefix_len, - "+%" PRIu64 ".%03lu", gps_sec, gps_ms); - } else { - 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); - } - strcpy(reformatted + prefix_len + decimal_len, timestamp_end); - return printf("%s", reformatted); - } - } - } +void gps_get_last_nmea(char *buf, size_t buf_len) { + if (buf && buf_len > 0) { + strlcpy(buf, s_last_nmea_msg, buf_len); } - return printf("%s", buffer); } diff --git a/components/gps_sync/gps_sync.h b/components/gps_sync/gps_sync.h index ef12ac3..972cd01 100644 --- a/components/gps_sync/gps_sync.h +++ b/components/gps_sync/gps_sync.h @@ -32,12 +32,18 @@ */ #pragma once -#include "driver/gpio.h" -#include "driver/uart.h" -#include -#include -#include +#include +#include +#include "esp_err.h" +#include "driver/uart.h" +#include "driver/gpio.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// --- Configuration Struct --- typedef struct { uart_port_t uart_port; gpio_num_t tx_pin; @@ -45,27 +51,26 @@ typedef struct { gpio_num_t pps_pin; } gps_sync_config_t; +// --- Timestamp Struct --- typedef struct { - int64_t monotonic_us; - int64_t monotonic_ms; - int64_t gps_us; - int64_t gps_ms; - struct timespec mono_ts; - bool synced; + int64_t gps_us; // Current GPS time in microseconds + bool synced; // PPS signal is active and stable (Precision Lock) + bool valid; // NMEA data indicates valid fix ('A' status) (Data Lock) } gps_timestamp_t; -void gps_sync_init(const gps_sync_config_t *config, bool use_gps_log_timestamps); -void gps_force_next_update(void); +// --- Initialization --- +// Initializes the GPS task with specific hardware pins +void gps_sync_init(const gps_sync_config_t *cfg, bool force_enable); // --- Getters --- gps_timestamp_t gps_get_timestamp(void); -int64_t gps_get_monotonic_ms(void); -bool gps_is_synced(void); -// Check health of the physical PPS signal +// Returns milliseconds since the last PPS edge (Diagnostic) int64_t gps_get_pps_age_ms(void); -void gps_get_last_nmea(char *buf, size_t max_len); -// --- Logging Hooks --- -uint32_t gps_log_timestamp(void); -int gps_log_vprintf(const char *fmt, va_list args); +// Copies the last received NMEA line into buffer (Diagnostic) +void gps_get_last_nmea(char *buf, size_t buf_len); + +#ifdef __cplusplus +} +#endif diff --git a/components/iperf/iperf.c b/components/iperf/iperf.c index 3e2b53b..d6f93ef 100644 --- a/components/iperf/iperf.c +++ b/components/iperf/iperf.c @@ -43,6 +43,12 @@ * - GPS Timestamp integration for status reporting. * @brief ESP32 iPerf Traffic Generator (UDP Client Only) with Trip-Time Support */ +/* + * iperf.c + * + * Copyright (c) 2025 Umber Networks & Robert McMahon + * All rights reserved. + */ #include #include #include @@ -276,15 +282,16 @@ void iperf_print_status(void) { iperf_get_stats(&s_stats); gps_timestamp_t ts = gps_get_timestamp(); - if (ts.synced && ts.gps_us > 0) { + // Check both Synced (PPS) and Valid (NMEA) + if (ts.synced && ts.valid && ts.gps_us > 0) { time_t now_sec = ts.gps_us / 1000000; struct tm tm_info; gmtime_r(&now_sec, &tm_info); char time_buf[64]; strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S UTC", &tm_info); - printf("TIME: %s\n", time_buf); + printf("TIME: %s (GPS Locked)\n", time_buf); } else { - printf("TIME: \n"); + printf("TIME: \n", ts.synced, ts.valid); } char dst_ip[32] = "0.0.0.0"; @@ -344,6 +351,10 @@ static void iperf_generate_headers(iperf_cfg_t *cfg, uint8_t *buffer, bool gps_s udp_hdr->flags = htonl(HEADER_EXTEND | HEADER_SEQNO64B | HEADER_TRIPTIME); udp_hdr->start_tv_sec = htonl(start_time->tv_sec); udp_hdr->start_tv_usec = htonl(start_time->tv_nsec / 1000); +#if 0 + ESP_LOGI(TAG, "TX Start Timestamp: %" PRIu32 ".%06" PRIu32, + (uint32_t)start_time.tv_sec, (uint32_t)(start_time.tv_nsec / 1000)); +#endif } else { udp_hdr->flags = htonl(HEADER_EXTEND | HEADER_SEQNO64B); } @@ -403,19 +414,18 @@ static esp_err_t iperf_start_udp_client(iperf_ctrl_t *ctrl) { // --- CHECK GPS SYNC --- gps_timestamp_t gps = gps_get_timestamp(); - bool gps_synced = gps.synced; + // FIX: Must have valid NMEA (absolute time) AND PPS (precision) + bool gps_synced = gps.synced && gps.valid; struct timespec start_ts = {0}; if (gps_synced) { - ESP_LOGI(TAG, "GPS Synced. Enabling Trip-Times (OWD)."); - // Capture START TIME for session + ESP_LOGI(TAG, "GPS Locked (PPS + NMEA). Enabling Trip-Times."); clock_gettime(CLOCK_REALTIME, &start_ts); } else { - ESP_LOGW(TAG, "GPS NOT Synced. Trip-Times disabled."); + ESP_LOGW(TAG, "GPS NOT Fully Locked (PPS:%d, NMEA:%d). Trip-Times disabled.", gps.synced, gps.valid); } // --- GENERATE HEADERS --- - // We pass the start_ts so it can be written into the start_fq header iperf_generate_headers(&ctrl->cfg, ctrl->buffer, gps_synced, &start_ts); s_stats.running = true; diff --git a/components/wifi_controller/wifi_controller.c b/components/wifi_controller/wifi_controller.c index a65fb56..f3931ca 100644 --- a/components/wifi_controller/wifi_controller.c +++ b/components/wifi_controller/wifi_controller.c @@ -71,10 +71,14 @@ static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t e } // ... [Helper: Log Collapse Events (Same as before)] ... -static void log_collapse_event(float nav_duration_us, int rssi, int retry) { +static void log_collapse_event(uint32_t nav_duration_us, int rssi, int retry) { gps_timestamp_t ts = gps_get_timestamp(); - printf("COLLAPSE,%" PRIi64 ",%" PRIi64 ",%d,%.2f,%d,%d\n", - ts.monotonic_ms, ts.gps_ms, ts.synced ? 1 : 0, nav_duration_us, rssi, retry); + // Use gps_us for timestamp, convert to ms for display + int64_t now_ms = ts.gps_us / 1000; + + // Log to CSV or similar + ESP_LOGI(TAG, "COLLAPSE: Time=%" PRId64 "ms, Sync=%d, Dur=%lu us, RSSI=%d, Retry=%d", + now_ms, ts.synced ? 1 : 0, nav_duration_us, rssi, retry); } // ... [Monitor Callbacks (Same as before)] ...