Challenge

Project 1

#include <iostream>

#include <fstream>

#include <vector>

#include <chrono>

#include <ctime>

#include <thread>

#include <filesystem>

namespace fs = std::filesystem;

// Define the maximum number of messages per log file

const int MAX_MESSAGES_PER_LOG = 1000;

// Function to determine if a message has an even ARB ID

bool is_even_arb_id(uint32_t arb_id) {

return arb_id % 2 == 0;

}

// Function to write CAN messages to log files

void write_to_log(const std::vector<std::string>& messages, const std::string& log_dir) {

static int log_count = 1;

std::string log_filename = log_dir + "/log_" + std::to_string(log_count) + ".txt";

std::ofstream logfile(log_filename);

if (!logfile) {

std::cerr << "Failed to open log file: " << log_filename << std::endl;

return;

}

for (const auto& message : messages) {

logfile << message << std::endl;

}

logfile.close();

++log_count;

}

// Function to read CAN messages and sort them into even and odd logs

void process_can_data() {

// Create directories for even and odd logs

fs::create_directory("Even Logs");

fs::create_directory("Odd Logs");

int even_message_count = 0;

int odd_message_count = 0;

std::vector<std::string> even_log;

std::vector<std::string> odd_log;

while (true) {

// Simulate reading CAN data (replace with actual CAN data reading)

// For demonstration purposes, randomly generate ARB IDs

uint32_t arb_id = rand() % 0xFFFFFFFF;

// Simulate reading message data (replace with actual message data reading)

std::string message_data = "Sample CAN message data";

if (is_even_arb_id(arb_id)) {

even_log.push_back("ARB ID: " + std::to_string(arb_id) + ", Data: " + message_data);

++even_message_count;

if (even_message_count == MAX_MESSAGES_PER_LOG) {

write_to_log(even_log, "Even Logs");

even_log.clear();

even_message_count = 0;

}

} else {

odd_log.push_back("ARB ID: " + std::to_string(arb_id) + ", Data: " + message_data);

++odd_message_count;

if (odd_message_count == MAX_MESSAGES_PER_LOG) {

write_to_log(odd_log, "Odd Logs");

odd_log.clear();

odd_message_count = 0;

}

}

// Simulate delay between reading CAN messages (replace with actual delay)

std::this_thread::sleep_for(std::chrono::milliseconds(10));

}

}

int main() {

process_can_data();

return 0;

}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.