Challenge

Project 1

using the python-can library for working with CAN data and basic file operations for logging. install the python-can library

(pip install python-can).

1.
python
import os import time import can def create_log_directory(directory_path): if not os.path.exists(directory_path): os.makedirs(directory_path) def log_can_messages(bus, even_log_dir, odd_log_dir, max_messages_per_log): even_log_count = 0 odd_log_count = 0 even_log_file = None odd_log_file = None try: for msg in bus: arb_id = msg.arbitration_id log_dir = even_log_dir if arb_id % 2 == 0 else odd_log_dir if arb_id % 2 == 0 and even_log_count == 0: even_log_file = open(os.path.join(log_dir, f"even_log_{even_log_count}.txt"), "w") if arb_id % 2 != 0 and odd_log_count == 0: odd_log_file = open(os.path.join(log_dir, f"odd_log_{odd_log_count}.txt"), "w") if arb_id % 2 == 0 and even_log_count >= max_messages_per_log: even_log_count = 0 even_log_file.close() even_log_file = open(os.path.join(log_dir, f"even_log_{even_log_count}.txt"), "w") if arb_id % 2 != 0 and odd_log_count >= max_messages_per_log: odd_log_count = 0 odd_log_file.close() odd_log_file = open(os.path.join(log_dir, f"odd_log_{odd_log_count}.txt"), "w") log_file = even_log_file if arb_id % 2 == 0 else odd_log_file log_file.write(str(msg) + '\n') if arb_id % 2 == 0: even_log_count += 1 else: odd_log_count += 1 except KeyboardInterrupt: pass finally: if even_log_file: even_log_file.close() if odd_log_file: odd_log_file.close() def main(): can_interface = 'can0' # Change this to your CAN interface bus = can.interface.Bus(channel=can_interface, bustype='socketcan') even_log_dir = 'Even Logs' odd_log_dir = 'Odd Logs' max_messages_per_log = 1000 create_log_directory(even_log_dir) create_log_directory(odd_log_dir) try: log_can_messages(bus, even_log_dir, odd_log_dir, max_messages_per_log) except Exception as e: print("An error occurred:", str(e)) finally: bus.shutdown() if __name__ == "__main__": main()

we can replace 'can0' with actual CAN interface name. Also, make necessary permissions to access the CAN interface and write files to the specified directories.

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.