Skip to content

Commit 2741588

Browse files
author
Kiran Jojare
committed
Setting up Main for Command Line Version
1 parent f25e394 commit 2741588

File tree

2 files changed

+83
-25
lines changed

2 files changed

+83
-25
lines changed

src/main.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import cantools
22
import sys
3+
import os
34
import matplotlib.pyplot as plt
45
import argparse
56

@@ -98,7 +99,7 @@ def plot_signals(parsed_data, signal_name, start_time, end_time):
9899
print(f"No data found for signal: {signal_name}")
99100
return
100101

101-
plt.figure(figsize=(30, 15)) # Adjust the size as needed
102+
plt.figure(figsize=(15, 5)) # Adjust the size as needed
102103
plt.plot(timestamps, values)
103104
plt.xlabel('Time (s)')
104105
plt.ylabel('Value')
@@ -120,12 +121,9 @@ def plot_signals(parsed_data, signal_name, start_time, end_time):
120121

121122
args = parser.parse_args()
122123

123-
if args.mode == "test":
124-
dbc_file = "C:\\Github\\CAN-Log-Parser\\test\\data\\test.dbc"
125-
log_file = "C:\\Github\\CAN-Log-Parser\\test\\data\\test_log.txt"
126-
elif args.mode == "main":
127-
dbc_file = "C:\\Github\\CAN-Log-Parser\\data\\1200G_CAN-DBC_v01.01.00.dbc"
128-
log_file = "C:\\Github\\CAN-Log-Parser\\data\\DMW_Message_Timeout_CAN_Log.txt"
124+
script_dir = os.path.dirname(os.path.abspath(__file__))
125+
dbc_file = os.path.join(script_dir, "..", "data", "test.dbc")
126+
log_file = os.path.join(script_dir, "..", "data", "test_log.txt")
129127

130128
db = parse_dbc(dbc_file)
131129
if db:

test/test_signal_plotting.py

Lines changed: 78 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,43 @@
1+
"""
2+
/**
3+
* @file main.py
4+
* @brief Script to parse CAN DBC files and log files, and plot specific CAN signal data over time.
5+
*
6+
* This script is designed to parse a DBC file to understand the structure of CAN messages and a log file
7+
* to extract actual CAN message data. It then plots the specified signal data over time.
8+
*
9+
* The script uses the `cantools` library to parse the DBC file and understand the CAN message structure.
10+
* The log file is parsed to extract individual CAN messages and their signals, which are then plotted using `matplotlib`.
11+
*
12+
*
13+
* The script is designed to work with relative paths, making it easy to clone the repository and run the script without modifying paths.
14+
*
15+
* Author: Kiran Jojare
16+
*
17+
* Usage:
18+
* python main.py <test|main> <signal_name> [start_time] [end_time]
19+
*
20+
* Arguments:
21+
* mode: Mode to run the script in ('test' or 'main')
22+
* signal: Signal name to plot
23+
* start: (Optional) Start time for the plot
24+
* end: (Optional) End time for the plot
25+
*/
26+
"""
27+
128
import cantools
29+
import os
230
import sys
331
import matplotlib.pyplot as plt
432
import argparse
533

634
def parse_dbc(file_path):
35+
"""
36+
@brief Parse the DBC file to get CAN message definitions.
37+
38+
@param file_path Path to the DBC file.
39+
@return Parsed DBC database object.
40+
"""
741
try:
842
db = cantools.database.load_file(file_path)
943
print(f"Successfully parsed DBC file: {file_path}")
@@ -13,21 +47,28 @@ def parse_dbc(file_path):
1347
return None
1448

1549
def parse_log(db, log_file_path):
50+
"""
51+
@brief Parse the log file to extract CAN messages.
52+
53+
@param db Parsed DBC database object.
54+
@param log_file_path Path to the log file.
55+
@return List of parsed CAN messages.
56+
"""
1657
try:
1758
parsed_data = []
1859
with open(log_file_path, 'r') as log_file:
1960
current_message = None
2061
for line in log_file:
21-
# print(f"Reading line: {line.strip()}") # Commented for clean output
62+
# print(f"Reading line: {line.strip()}") # Debug print
2263
if line.startswith("CAN"):
2364
if current_message:
2465
process_message(db, current_message, parsed_data)
2566
current_message = [line.strip()]
26-
# print("Detected start of a new message") # Commented for clean output
67+
# print("Detected start of a new message") # Debug print
2768
elif line.strip().startswith("->"):
28-
# print("Detected start of line with ->")
69+
# print("Detected start of line with ->") # Debug print
2970
current_message.append(line.strip())
30-
# print(f"Appending signal line: {line.strip()}") # Commented for clean output
71+
# print(f"Appending signal line: {line.strip()}") # Debug print
3172
if current_message:
3273
process_message(db, current_message, parsed_data)
3374
print_parsed_data(parsed_data)
@@ -37,21 +78,26 @@ def parse_log(db, log_file_path):
3778
return None
3879

3980
def process_message(db, message_lines, parsed_data):
81+
"""
82+
@brief Process a single CAN message from the log file.
83+
84+
@param db Parsed DBC database object.
85+
@param message_lines List of lines representing a single CAN message.
86+
@param parsed_data List to append the parsed message data.
87+
"""
4088
try:
41-
# print(f"Processing message lines: {message_lines}") # Commented for clean output
89+
# print(f"Processing message lines: {message_lines}") # Debug print
4290
main_line = message_lines[0].split()
43-
# print(f"Main line parts: {main_line}") # Commented for clean output
91+
# print(f"Main line parts: {main_line}") # Debug print
4492
can_id = main_line[2]
45-
# if can_id in ["00000000", "0000040A"]:
46-
# return
4793
ecu_name, message_name = main_line[6].split('.')
4894
timestamp = main_line[7]
4995
direction = main_line[8]
5096

5197
signals = []
5298

5399
for signal_line in message_lines[1:]:
54-
# print("Signal Line ---- ", signal_line)
100+
# print("Signal Line ---- ", signal_line) # Debug print
55101
parts = signal_line.split()
56102
signal_name = parts[1]
57103
signal_value = parts[2]
@@ -66,18 +112,30 @@ def process_message(db, message_lines, parsed_data):
66112
})
67113

68114
except Exception as e:
69-
print(f"Error processing message: {e}, for CAN ID (Error Frames): {can_id}")
115+
print(f"Error processing message: {e}, for CAN ID: {can_id}")
70116
return
71117

72118
def print_parsed_data(parsed_data):
119+
"""
120+
@brief Print parsed data for debugging purposes.
121+
122+
@param parsed_data List of parsed CAN messages.
123+
"""
73124
for data in parsed_data:
74125
#print(f"Message: {data['message_name']}, CAN ID: {data['can_id']}, Timestamp: {data['timestamp']}, Direction: {data['direction']}")
75126
for signal in data['signals']:
76127
signal_name, signal_value, signal_timestamp = signal
77128
#print(f" Signal: {signal_name}, Value: {signal_value}, Timestamp: {signal_timestamp}")
78129

79-
80130
def plot_signals(parsed_data, signal_name, start_time, end_time):
131+
"""
132+
@brief Plot the signal data over time.
133+
134+
@param parsed_data List of parsed CAN messages.
135+
@param signal_name Name of the signal to plot.
136+
@param start_time Start time for the plot.
137+
@param end_time End time for the plot.
138+
"""
81139
timestamps = []
82140
values = []
83141
for data in parsed_data:
@@ -120,26 +178,28 @@ def plot_signals(parsed_data, signal_name, start_time, end_time):
120178

121179
args = parser.parse_args()
122180

123-
if args.mode == "test":
124-
dbc_file = "C:\\Github\\CAN-Log-Parser\\test\\data\\test.dbc"
125-
log_file = "C:\\Github\\CAN-Log-Parser\\test\\data\\test_log.txt"
126-
elif args.mode == "main":
127-
dbc_file = "C:\\Github\\CAN-Log-Parser\\data\\1200G_CAN-DBC_v01.01.00.dbc"
128-
log_file = "C:\\Github\\CAN-Log-Parser\\data\\DMW_Message_Timeout_CAN_Log.txt"
181+
# Determine the paths to the DBC and log files based on the mode
182+
script_dir = os.path.dirname(os.path.abspath(__file__))
183+
dbc_file = os.path.join(script_dir, "..", "data", "test.dbc")
184+
log_file = os.path.join(script_dir, "..", "data", "test_log.txt")
129185

186+
# Parse the DBC file
130187
db = parse_dbc(dbc_file)
131188
if db:
189+
# Parse the log file
132190
parsed_data = parse_log(db, log_file)
133191
if parsed_data:
192+
# Determine start and end times for the plot if not provided
134193
if args.start is None or args.end is None:
135194
all_timestamps = [float(data['timestamp']) / 1000 for data in parsed_data for signal in data['signals']]
136195
start_time = min(all_timestamps) if args.start is None else args.start
137196
end_time = max(all_timestamps) if args.end is None else args.end
138197
else:
139198
start_time = args.start
140199
end_time = args.end
200+
# Plot the signals
141201
plot_signals(parsed_data, args.signal, start_time, end_time)
142202
else:
143203
print("Parsed data is empty or None.")
144204
else:
145-
print("DBC parsing failed.")
205+
print("DBC parsing failed.")

0 commit comments

Comments
 (0)