From 1ba21da6cbc63c0c549fb92731e25bedc482eb51 Mon Sep 17 00:00:00 2001 From: Filip Wandzio Date: Thu, 4 Sep 2025 22:25:39 +0200 Subject: Unify the directory, add new analysis methods, unify the code style Signed-off-by: Filip Wandzio --- analysis/rtt/src/logger.c | 86 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 analysis/rtt/src/logger.c (limited to 'analysis/rtt/src/logger.c') diff --git a/analysis/rtt/src/logger.c b/analysis/rtt/src/logger.c new file mode 100644 index 0000000..ed5f6e5 --- /dev/null +++ b/analysis/rtt/src/logger.c @@ -0,0 +1,86 @@ + +#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); +} -- cgit v1.2.3