#include "logger.h" #include #include #include #include #include #define WINDOW_SEC 1 #define MAX_TIMES 1000 static FILE *csv_file = NULL; static double msg_times[MAX_TIMES]; static int msg_count = 0; static long long current_time_ms() { struct timeval tv; gettimeofday(&tv, NULL); return ((long long)tv.tv_sec * 1000) + (tv.tv_usec / 1000); } static double current_time_sec() { struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + (tv.tv_usec / 1e6); } static int update_throughput_window(double now) { int i, new_count = 0; for (i = 0; i < msg_count; i++) { if (now - msg_times[i] < WINDOW_SEC) { msg_times[new_count++] = msg_times[i]; } } msg_times[new_count++] = now; msg_count = new_count; return msg_count; } void logger_init(const char *filename) { csv_file = fopen(filename, "w"); if (!csv_file) { perror("Cannot open CSV file"); exit(EXIT_FAILURE); } fprintf(csv_file, "timestamp,sent_ms,received_ms,rtt_ms,throughput_msg_per_s\n"); fflush(csv_file); } void logger_cleanup() { if (csv_file) { fclose(csv_file); csv_file = NULL; } } void logger_handle_message(const void *payload, int payloadlen) { char *payload_str = malloc(payloadlen + 1); if (!payload_str) return; memcpy(payload_str, payload, payloadlen); payload_str[payloadlen] = '\0'; long long sent_ms = atoll(payload_str); free(payload_str); long long received_ms = current_time_ms(); long long rtt = received_ms - sent_ms; double now_sec = current_time_sec(); int throughput = update_throughput_window(now_sec); time_t now = time(NULL); struct tm *tm_info = localtime(&now); char iso_time[32]; strftime(iso_time, sizeof(iso_time), "%Y-%m-%dT%H:%M:%S", tm_info); if (csv_file) { fprintf(csv_file, "%s,%lld,%lld,%lld,%d\n", iso_time, sent_ms, received_ms, rtt, throughput); fflush(csv_file); } printf("RTT: %lld ms | Throughput: %d msg/s\n", rtt, throughput); }