more on gps time

This commit is contained in:
Robert McMahon 2025-12-22 13:06:05 -08:00
parent 9974174d5b
commit b769dbc356
5 changed files with 291 additions and 392 deletions

View File

@ -30,125 +30,116 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. * POSSIBILITY OF SUCH DAMAGE.
*/ */
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <time.h>
#include <inttypes.h> #include <inttypes.h>
#include <time.h>
#include <sys/time.h>
#include "esp_log.h" #include "esp_log.h"
#include "esp_console.h" #include "esp_console.h"
#include "argtable3/argtable3.h" #include "argtable3/argtable3.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "gps_sync.h" #include "gps_sync.h"
#include "app_console.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 { static void print_gps_usage(void) {
struct arg_lit *enable; printf("Usage: gps <subcommand> [args]\n");
struct arg_lit *disable; printf("Subcommands:\n");
struct arg_lit *status; printf(" status Show GPS lock status, time, and last NMEA message\n");
struct arg_lit *help; printf("\nType 'gps <subcommand> --help' for details.\n");
struct arg_end *end; }
} gps_args;
static int cmd_gps(int argc, char **argv) { static int cmd_gps(int argc, char **argv) {
int nerrors = arg_parse(argc, argv, (void **)&gps_args); if (argc < 2 || strcmp(argv[1], "help") == 0 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) {
if (nerrors > 0) { print_gps_usage();
arg_print_errors(stderr, gps_args.end, argv[0]);
return 1;
}
if (gps_args.help->count > 0) {
printf("Usage: gps [--enable|--disable|--status]\n");
return 0; return 0;
} }
nvs_handle_t h; if (strcmp(argv[1], "status") == 0) return gps_do_status(argc - 1, &argv[1]);
esp_err_t err = nvs_open("storage", NVS_READWRITE, &h); if (strcmp(argv[1], "info") == 0) return gps_do_status(argc - 1, &argv[1]); // Alias
if (err != ESP_OK) {
printf("Error opening NVS: %s\n", esp_err_to_name(err)); 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; return 1;
} }
// --- HANDLE SETTERS --- if (status_args.help->count > 0) {
bool changed = false; printf("Usage: gps status\n");
if (gps_args.enable->count > 0) { return 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 (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 --- char nmea_buf[128] = "<Empty>";
// 1. NVS State gps_get_last_nmea(nmea_buf, sizeof(nmea_buf));
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);
// 2. Runtime Status // Strip trailing newline
if (val) { size_t len = strlen(nmea_buf);
gps_timestamp_t ts = gps_get_timestamp(); if (len > 0 && (nmea_buf[len-1] == '\n' || nmea_buf[len-1] == '\r')) nmea_buf[len-1] = 0;
int64_t pps_age = gps_get_pps_age_ms();
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 if (ts.gps_us > 0) {
char nmea_buf[128]; // Get raw timespec for display
gps_get_last_nmea(nmea_buf, sizeof(nmea_buf)); clock_gettime(CLOCK_REALTIME, &ts_now);
// Cleanup CR/LF for printing time_t now_sec = ts_now.tv_sec;
size_t len = strlen(nmea_buf); struct tm tm_info;
if (len > 0 && (nmea_buf[len-1] == '\r' || nmea_buf[len-1] == '\n')) nmea_buf[len-1] = 0; gmtime_r(&now_sec, &tm_info);
if (len > 1 && (nmea_buf[len-2] == '\r' || nmea_buf[len-2] == '\n')) nmea_buf[len-2] = 0; strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S UTC", &tm_info);
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: <Unknown> (System Epoch)\n");
}
} }
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; return 0;
} }
void register_gps_cmd(void) { // ----------------------------------------------------------------------------
gps_args.enable = arg_lit0(NULL, "enable", "Enable GPS"); // Registration
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);
void register_gps_cmd(void) {
const esp_console_cmd_t cmd = { const esp_console_cmd_t cmd = {
.command = "gps", .command = "gps",
.help = "Configure GPS", .help = "GPS Tool: status",
.hint = "<subcommand>",
.func = &cmd_gps, .func = &cmd_gps,
.argtable = &gps_args .argtable = NULL
}; };
ESP_ERROR_CHECK(esp_console_cmd_register(&cmd)); ESP_ERROR_CHECK(esp_console_cmd_register(&cmd));
} }

View File

@ -30,341 +30,230 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. * 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 <string.h>
#include <time.h>
#include <stdarg.h>
#include <stdio.h> #include <stdio.h>
#include <assert.h> #include <string.h>
#include <inttypes.h> #include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#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"; static const char *TAG = "GPS_SYNC";
#define GPS_BAUD_RATE 9600 #define GPS_BUF_SIZE 1024
#define UART_BUF_SIZE 1024
// --- GLOBAL STATE --- // --- Internal State ---
static uart_port_t gps_uart_num = UART_NUM_1; static gps_sync_config_t s_cfg;
static int64_t monotonic_offset_us = 0; static volatile int64_t s_last_pps_us = 0;
static volatile int64_t last_pps_monotonic = 0; static volatile int64_t s_nmea_epoch_us = 0;
static bool gps_has_fix = false; static volatile bool s_nmea_valid = false;
static bool use_gps_for_logs = false; static char s_last_nmea_msg[128] = {0};
static SemaphoreHandle_t sync_mutex; static bool s_time_set = false;
static volatile bool force_sync_update = true;
// Debug Buffer // --- PPS Handler ---
static char s_last_nmea_line[128] = "<WAITING FOR DATA>"; static void IRAM_ATTR pps_gpio_isr_handler(void* arg) {
s_last_pps_us = esp_timer_get_time();
// 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;
} }
// Parse GPS time from NMEA (GPRMC or GNRMC) // --- Time Helper ---
static bool parse_gprmc(const char* nmea, struct tm* tm_out, bool* valid) { static void set_system_time(char *time_str, char *date_str) {
if (strncmp(nmea, "$GPRMC", 6) != 0 && strncmp(nmea, "$GNRMC", 6) != 0) return false; // time_str: HHMMSS.ss (e.g., 123519.00)
// date_str: DDMMYY (e.g., 230394)
char *p = strchr(nmea, ','); struct tm tm_info = {0};
if (!p) return false;
p++; // Move past comma
int hour, min, sec; // Parse Time
if (sscanf(p, "%2d%2d%2d", &hour, &min, &sec) != 3) return false; 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, ','); // Parse Date
if (!p) return false; int day, mon, year;
p++; if (sscanf(date_str, "%2d%2d%2d", &day, &mon, &year) != 3) return;
*valid = (*p == 'A'); 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++) { time_t t = mktime(&tm_info);
p = strchr(p, ','); if (t == -1) return;
if (!p) return false;
p++; 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) { // --- NMEA Parser ---
force_sync_update = true; static void parse_nmea_line(char *line) {
ESP_LOGW(TAG, "Requesting forced GPS sync update"); strlcpy(s_last_nmea_msg, line, sizeof(s_last_nmea_msg));
}
static time_t timegm_impl(struct tm *tm) { // Support GPRMC and GNRMC
time_t t = mktime(tm); if (strncmp(line, "$GPRMC", 6) == 0 || strncmp(line, "$GNRMC", 6) == 0) {
return t; char *p = line;
} int field = 0;
char *time_ptr = NULL;
char *date_ptr = NULL;
char status = 'V';
static void gps_task(void* arg) { // Walk fields
uint8_t d_buf[64]; // $GPRMC,Time,Status,Lat,NS,Lon,EW,Spd,Trk,Date,...
char line[128]; // Field 1: Time
int pos = 0; // Field 2: Status
static int log_counter = 0; // Field 9: Date
setenv("TZ", "UTC", 1); while ((p = strchr(p, ',')) != NULL) {
tzset(); p++;
field++;
while (1) { if (field == 1) time_ptr = p;
int len = uart_read_bytes(gps_uart_num, d_buf, sizeof(d_buf), pdMS_TO_TICKS(100)); else if (field == 2) status = *p;
else if (field == 9) {
date_ptr = p;
break; // We have what we need
}
}
if (len > 0) { s_nmea_valid = (status == 'A');
for (int i = 0; i < len; i++) {
uint8_t data = d_buf[i];
if (data == '\n' || data == '\r') { if (s_nmea_valid) {
if (pos > 0) { s_nmea_epoch_us = esp_timer_get_time();
line[pos] = '\0';
// Copy to debug buffer // Extract substrings for Time/Date (comma terminated)
xSemaphoreTake(sync_mutex, portMAX_DELAY); if (time_ptr && date_ptr) {
strncpy(s_last_nmea_line, line, sizeof(s_last_nmea_line) - 1); char t_buf[16] = {0};
s_last_nmea_line[sizeof(s_last_nmea_line) - 1] = '\0'; char d_buf[16] = {0};
xSemaphoreGive(sync_mutex);
struct tm gps_tm; char *end = strchr(time_ptr, ',');
bool valid_fix; if (end) {
int len = end - time_ptr;
if (parse_gprmc(line, &gps_tm, &valid_fix)) { if (len < sizeof(t_buf)) {
if (valid_fix) { memcpy(t_buf, time_ptr, len);
time_t gps_time_sec = timegm_impl(&gps_tm); t_buf[len] = 0;
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;
}
}
} }
pos = 0; }
} else {
if (pos < sizeof(line) - 1) { end = strchr(date_ptr, ',');
line[pos++] = data; 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) { // --- UART Task ---
if (!buf || max_len == 0) return; static void gps_task(void *pvParameters) {
xSemaphoreTake(sync_mutex, portMAX_DELAY); uint8_t *data = (uint8_t *)malloc(GPS_BUF_SIZE);
strncpy(buf, s_last_nmea_line, max_len); if (!data) {
buf[max_len - 1] = '\0'; ESP_LOGE(TAG, "Failed to allocate GPS buffer");
xSemaphoreGive(sync_mutex); 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) { // --- API ---
ESP_LOGI(TAG, "Initializing GPS Sync (UART %d, PPS GPIO %d)", config->uart_port, config->pps_pin);
gpio_config_t pps_poll_conf = { void gps_sync_init(const gps_sync_config_t *cfg, bool force_enable) {
.pin_bit_mask = (1ULL << config->pps_pin), if (!cfg) return;
.mode = GPIO_MODE_INPUT, s_cfg = *cfg;
.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);
}
uart_config_t uart_config = { uart_config_t uart_config = {
.baud_rate = GPS_BAUD_RATE, .baud_rate = 9600,
.data_bits = UART_DATA_8_BITS, .data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE, .parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1, .stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE, .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.source_clk = UART_SCLK_DEFAULT, .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)); gpio_config_t io_conf = {};
ESP_ERROR_CHECK(uart_param_config(config->uart_port, &uart_config)); io_conf.intr_type = GPIO_INTR_POSEDGE;
ESP_ERROR_CHECK(uart_set_pin(config->uart_port, config->tx_pin, config->rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE)); io_conf.pin_bit_mask = (1ULL << s_cfg.pps_pin);
io_conf.mode = GPIO_MODE_INPUT;
gpio_config_t pps_intr_conf = { io_conf.pull_up_en = 1;
.intr_type = GPIO_INTR_POSEDGE, gpio_config(&io_conf);
.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_install_isr_service(0); 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); 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 gps_get_timestamp(void) {
gps_timestamp_t ts; gps_timestamp_t ts = {0};
clock_gettime(CLOCK_MONOTONIC, &ts.mono_ts); 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; // Check Flags
ts.monotonic_ms = ts.monotonic_us / 1000; 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); // Return WALL CLOCK time (Epoch), not boot time
ts.gps_us = ts.monotonic_us + monotonic_offset_us; struct timeval tv;
ts.synced = gps_has_fix; gettimeofday(&tv, NULL);
xSemaphoreGive(sync_mutex); ts.gps_us = (int64_t)tv.tv_sec * 1000000LL + (int64_t)tv.tv_usec;
ts.gps_ms = ts.gps_us / 1000;
return ts; 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) { int64_t gps_get_pps_age_ms(void) {
if (last_pps_monotonic == 0) return -1; if (s_last_pps_us == 0) return -1;
int64_t now = esp_timer_get_time(); return (esp_timer_get_time() - s_last_pps_us) / 1000;
return (now - last_pps_monotonic) / 1000;
} }
// ---------------- LOGGING SYSTEM INTERCEPTION ---------------- void gps_get_last_nmea(char *buf, size_t buf_len) {
if (buf && buf_len > 0) {
uint32_t gps_log_timestamp(void) { strlcpy(buf, s_last_nmea_msg, buf_len);
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);
}
}
}
} }
return printf("%s", buffer);
} }

View File

@ -32,12 +32,18 @@
*/ */
#pragma once #pragma once
#include "driver/gpio.h"
#include "driver/uart.h"
#include <stdbool.h>
#include <stdint.h>
#include <time.h>
#include <stdint.h>
#include <stdbool.h>
#include "esp_err.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#ifdef __cplusplus
extern "C" {
#endif
// --- Configuration Struct ---
typedef struct { typedef struct {
uart_port_t uart_port; uart_port_t uart_port;
gpio_num_t tx_pin; gpio_num_t tx_pin;
@ -45,27 +51,26 @@ typedef struct {
gpio_num_t pps_pin; gpio_num_t pps_pin;
} gps_sync_config_t; } gps_sync_config_t;
// --- Timestamp Struct ---
typedef struct { typedef struct {
int64_t monotonic_us; int64_t gps_us; // Current GPS time in microseconds
int64_t monotonic_ms; bool synced; // PPS signal is active and stable (Precision Lock)
int64_t gps_us; bool valid; // NMEA data indicates valid fix ('A' status) (Data Lock)
int64_t gps_ms;
struct timespec mono_ts;
bool synced;
} gps_timestamp_t; } gps_timestamp_t;
void gps_sync_init(const gps_sync_config_t *config, bool use_gps_log_timestamps); // --- Initialization ---
void gps_force_next_update(void); // Initializes the GPS task with specific hardware pins
void gps_sync_init(const gps_sync_config_t *cfg, bool force_enable);
// --- Getters --- // --- Getters ---
gps_timestamp_t gps_get_timestamp(void); 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); int64_t gps_get_pps_age_ms(void);
void gps_get_last_nmea(char *buf, size_t max_len);
// --- Logging Hooks --- // Copies the last received NMEA line into buffer (Diagnostic)
uint32_t gps_log_timestamp(void); void gps_get_last_nmea(char *buf, size_t buf_len);
int gps_log_vprintf(const char *fmt, va_list args);
#ifdef __cplusplus
}
#endif

View File

@ -43,6 +43,12 @@
* - GPS Timestamp integration for status reporting. * - GPS Timestamp integration for status reporting.
* @brief ESP32 iPerf Traffic Generator (UDP Client Only) with Trip-Time Support * @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 <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <ctype.h> #include <ctype.h>
@ -276,15 +282,16 @@ void iperf_print_status(void) {
iperf_get_stats(&s_stats); iperf_get_stats(&s_stats);
gps_timestamp_t ts = gps_get_timestamp(); 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; time_t now_sec = ts.gps_us / 1000000;
struct tm tm_info; struct tm tm_info;
gmtime_r(&now_sec, &tm_info); gmtime_r(&now_sec, &tm_info);
char time_buf[64]; char time_buf[64];
strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S UTC", &tm_info); 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 { } else {
printf("TIME: <Not Synced>\n"); printf("TIME: <Not Synced - PPS:%d NMEA:%d>\n", ts.synced, ts.valid);
} }
char dst_ip[32] = "0.0.0.0"; 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->flags = htonl(HEADER_EXTEND | HEADER_SEQNO64B | HEADER_TRIPTIME);
udp_hdr->start_tv_sec = htonl(start_time->tv_sec); udp_hdr->start_tv_sec = htonl(start_time->tv_sec);
udp_hdr->start_tv_usec = htonl(start_time->tv_nsec / 1000); 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 { } else {
udp_hdr->flags = htonl(HEADER_EXTEND | HEADER_SEQNO64B); 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 --- // --- CHECK GPS SYNC ---
gps_timestamp_t gps = gps_get_timestamp(); 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}; struct timespec start_ts = {0};
if (gps_synced) { if (gps_synced) {
ESP_LOGI(TAG, "GPS Synced. Enabling Trip-Times (OWD)."); ESP_LOGI(TAG, "GPS Locked (PPS + NMEA). Enabling Trip-Times.");
// Capture START TIME for session
clock_gettime(CLOCK_REALTIME, &start_ts); clock_gettime(CLOCK_REALTIME, &start_ts);
} else { } 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 --- // --- 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); iperf_generate_headers(&ctrl->cfg, ctrl->buffer, gps_synced, &start_ts);
s_stats.running = true; s_stats.running = true;

View File

@ -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)] ... // ... [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(); gps_timestamp_t ts = gps_get_timestamp();
printf("COLLAPSE,%" PRIi64 ",%" PRIi64 ",%d,%.2f,%d,%d\n", // Use gps_us for timestamp, convert to ms for display
ts.monotonic_ms, ts.gps_ms, ts.synced ? 1 : 0, nav_duration_us, rssi, retry); 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)] ... // ... [Monitor Callbacks (Same as before)] ...