Challenge

Project 1

To create a program that logs CAN data from one or more CAN buses and sorts them into even and odd ARB ID logs, with a limit of 1000 messages per log, we can use the SocketCAN package in Linux along with Python. The program will continuously listen to CAN messages, sort them based on their ARB ID, and store them in separate log files in designated directories.

Here the implementation:

import os
import time
from datetime import datetime
from can.interfaces.interface import Bus
from can import Message

# Set up CAN buses
can_buses = ["can0", "can1"]  # Replace with the desired CAN bus names
can_interfaces = []

# Create Even Logs and Odd Logs directories
os.makedirs("Even Logs", exist_ok=True)
os.makedirs("Odd Logs", exist_ok=True)

# Initialize log counters
even_log_counter = 0
odd_log_counter = 0
max_log_size = 1000  # Maximum number of messages per log

# Create a CAN interface for each bus
for bus in can_buses:
    can_interface = Bus(interface=bus)
    can_interfaces.append(can_interface)

# Start logging
try:
    while True:
        for bus_index, can_interface in enumerate(can_interfaces):
            message = can_interface.recv(timeout=1.0)  # Receive CAN message with a timeout of 1 second

            if message is not None:
                if message.arbitration_id % 2 == 0:
                    # Even ARB ID message
                    log_dir = "Even Logs"
                    log_counter = even_log_counter
                else:
                    # Odd ARB ID message
                    log_dir = "Odd Logs"
                    log_counter = odd_log_counter

                log_filename = f"{log_dir}/log_{log_counter}.txt"

                with open(log_filename, "a") as log_file:
                    log_file.write(f"{message}n")

                # Check log size and create a new log file if necessary
                if os.path.getsize(log_filename) > max_log_size:
                    if log_dir == "Even Logs":
                        even_log_counter += 1
                    else:
                        odd_log_counter += 1
                    log_filename = f"{log_dir}/log_{log_counter}.txt"

                print(f"Received CAN message: {message} | Logged in: {log_filename}")

except KeyboardInterrupt:
    print("Logging stopped.")

Explanation:

The program is implemented using Python and the SocketCAN package. It uses the can.interfaces.interface module to create a CAN interface for each specified bus. In this example, two buses, "can0" and "can1," are assumed, but you can modify the can_buses list to match your specific setup.

The program continuously listens for CAN messages using a while loop with a timeout of 1 second. If a message is received, it checks whether the ARB ID is even or odd by performing a modulo operation on the ARB ID. Messages with even ARB IDs are logged in the "Even Logs" directory, while messages with odd ARB IDs are logged in the "Odd Logs" directory.

The program keeps track of log counters (even_log_counter and odd_log_counter) to create new log files when the current log files reach the maximum size of 1000 messages. Each log file is named using the log counter and the corresponding directory.

The program appends the received CAN message to the log file and checks its size. If the log file exceeds the maximum size, a new log file is created by incrementing the corresponding log counter.

The program also prints the received CAN message and the log file in which it is stored for visual feedback.


Calculations:

The program involves basic file operations and handling message counts. Let's discuss some relevant calculations:

  1. Maximum log size: The maximum number of messages per log file is set to 1000 (max_log_size). You can modify this value based on your requirements. When the log file exceeds this size, a new log file is created.

  2. Log counters: The program uses separate log counters (even_log_counter and odd_log_counter) to keep track of the log file numbers for even and odd ARB ID messages, respectively. These counters are incremented whenever a new log file needs to be created. Initially, both counters are set to 0.

  3. Log file naming: Each log file is named in the format "log_{log_counter}.txt", where {log_counter} represents the value of the log counter for the corresponding ARB ID category.

  4. Log directories: The program creates the "Even Logs" and "Odd Logs" directories using os.makedirs(). If the directories already exist, the program continues without overwriting them.

  5. File size check: The program uses os.path.getsize() to check the size of the log file. If the size exceeds the maximum log size, a new log file is created by incrementing the corresponding log counter.

By executing this program, you can continuously log CAN messages from multiple CAN buses, sort them into even and odd ARB ID logs, and store them in separate directories. The program will run indefinitely until manually stopped by a keyboard interrupt (Ctrl+C).


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.