Branch data MC/DC data Line data Source code
1 : : : /**
2 : : : * @file log_utils.c
3 : : : * @brief Utilitary file for event tracking in actuators abstraction.
4 : : : *
5 : : : * This file provides functionality to log events with timestamps
6 : : : * and relevant actuator states.
7 : : : */
8 : : : #include <stdio.h>
9 : : : #include <time.h>
10 : : : #include <stdint.h>
11 : : : #include "log_utils.h"
12 : : :
13 : : :
14 : : : /**
15 : : : * @brief Logs an event to a file with a timestamp and actuator data.
16 : : : *
17 : : : * This function logs an event by appending it to a log file. It records the event ID,
18 : : : * the timestamp (in milliseconds), and actuator states in a structured format.
19 : : : *
20 : : : * @param id_aeb Identifier for the AEB system.
21 : : : * @param event_id The unique event identifier (formatted as a hexadecimal string).
22 : : : * @param actuators Structure containing actuator state information.
23 : : : *
24 : : : * \anchor log_event
25 : : : *
26 : : : * @note This function is a called from the actuators module, and it is used as a way to guarantee tava
27 : : : * every change to the AEB internal state is captured and stored on the log file.
28 : : : */
29 : : :
30 : : 4 : void log_event(const char *id_aeb, uint32_t event_id, actuators_abstraction actuators) {
31 : : 4 : FILE *log_file = fopen("log/log.txt", "a");
32 [ + + ]: [ T F ]: 4 : if (log_file == NULL) {
33 : : 1 : perror("Error opening log file");
34 : : 1 : return;
35 : : : }
36 : : :
37 : : : //Check if the file is empty
38 : : 3 : fseek(log_file, 0, SEEK_END);
39 [ + + ]: [ T F ]: 3 : if (ftell(log_file) == 0) {
40 : : : // If the file is empty, write the header
41 : : 2 : fprintf(log_file, "ID_AEB | EVENT_ID | TIMESTAMP | MESSAGE | BELT_TIGHTNESS | DOOR_LOCK | ABS_ACTIVATION | ALARM_LED | ALARM_BUZZER\n");
42 : : : }
43 : : 3 : fseek(log_file, 0, SEEK_END); // Move the file pointer to the end of the file
44 : : :
45 : : : // Getting the timestamp instead just the date, because it's more useful (miliseconds)
46 : : : struct timespec ts;
47 : : 3 : clock_gettime(CLOCK_REALTIME, &ts);
48 : : 3 : long timestamp_ms = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
49 : : :
50 : : : // Convert id to hexadecimal string
51 : : : char event_id_str[9]; // 8 caracteres + '\0'
52 : : 3 : snprintf(event_id_str, sizeof(event_id_str), "%08X", event_id);
53 : : :
54 : : : // Write in file in desired format
55 : : 3 : fprintf(log_file, "%s | %s | %07ld | WARNING | %d | %d | %d | %d | %d\n",
56 : : : id_aeb,
57 : : : event_id_str,
58 : : : timestamp_ms,
59 : : 3 : actuators.belt_tightness,
60 : : 3 : actuators.door_lock,
61 : : 3 : actuators.should_activate_abs,
62 : : 3 : actuators.alarm_led,
63 : : 3 : actuators.alarm_buzzer);
64 : : :
65 : : 3 : fclose(log_file);
66 : : : }
|