Project 1
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/can.h>
#include <sys/ioctl.h>
// Define the maximum number of messages to store in a single log file
#define MAX_MSGS 1000
int main(int argc, char *argv[]) {
int s;
struct can_frame frame;
struct sockaddr_can addr;
struct ifreq ifr;
int num_msgs = 0;
// Create a CAN socket
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
strcpy(ifr.ifr_name, "can0");
ioctl(s, SIOCGIFINDEX, &ifr);
// Set the socket to listen on the specified CAN bus
addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;
bind(s, (struct sockaddr *)&addr, sizeof(addr));
// Create a directory for even logs, if it doesn't already exist
if (opendir("Even Logs") == NULL) {
mkdir("Even Logs", 0700);
}
// Create a directory for odd logs, if it doesn't already exist
if (opendir("Odd Logs") == NULL) {
mkdir("Odd Logs", 0700);
}
// Run indefinitely until manually stopped
while (1) {
// Receive CAN messages from the CAN bus
if (read(s, &frame, sizeof(struct can_frame)) > 0) {
// Determine whether the ID of the CAN message is even or odd
if (frame.can_id % 2 == 0) {
// If even, write to the even logs
char filename[100];
sprintf(filename, "Even Logs/%03d.log", num_msgs);
FILE *fp = fopen(filename, "w");
fprintf(fp, "CAN ID: %x, Length: %d, Data: ", frame.can_id, frame.can_dlc);
for (int i = 0; i < frame.can_dlc; i++) {
fprintf(fp, "%02x ", frame.data[i]);
}
fprintf(fp, "\n");
fclose(fp);
} else {
// If odd, write to the odd logs
char filename[100];
sprintf(filename, "Odd Logs/%03d.log", num_msgs);
FILE *fp = fopen(filename, "w");
fprintf(fp, "CAN ID: %x, Length: %d, Data: ", frame.can_id, frame.can_dlc);
for (int i = 0; i < frame.can_dlc; i++) {
fprintf(fp, "%02x ", frame.data[i]);
}
fprintf(fp, "\n");
fclose(fp);
}
// Increment the message counter
num_msgs++;
// Reset the message counter if it reaches the maximum number of messages
if (num_msgs == MAX_MSGS) {
num_msgs = 0;
}
}
}
return 0;
}