-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcandump-bitrate
executable file
·204 lines (183 loc) · 6.18 KB
/
candump-bitrate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/env python3
"""Compute estimated CAN bus bitrate
Consumes a CSV file generated by 'can2csv'.
"""
import argparse
import collections
import csv
import logging
import pathlib
import shutil
import sys
import tempfile
from csvutils import column_name_to_index, detect_dialect
def parse_args():
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"--log-level",
"-l",
type=str,
default="INFO",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
help="Set the logging output level. Defaults to INFO.",
)
parser.add_argument(
"input",
default="-",
nargs="?",
help="Candump CSV file input. Defaults to stdin.",
)
parser.add_argument(
"--bitrate",
"-b",
default=250000,
type=int,
help="The bus bitrate",
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--inplace",
"-i",
action="store_true",
help="Whether to edit the input file inplace. Requires a file input, not stdin",
)
group.add_argument(
"--output",
"-o",
default="-",
help="Script output. Defaults to stdout.",
)
group = parser.add_argument_group("CSV options")
group.add_argument(
"--no-header",
action="store_true",
default=False,
help="Whether the CSV file has a header",
)
group.add_argument(
"--delimiter",
"-d",
default=",",
help="Specify the column delimiter. Default is ','",
)
return parser.parse_args()
def main(args):
# Handle inplace input/output, and stdin/file input/output
input = None
if not args.input or args.input == "-":
input = sys.stdin
else:
input = pathlib.Path(args.input)
if not input.exists():
logging.critical("Input file '%s' does not exists", args.input)
sys.exit(1)
input = input.open("r", encoding="utf-8")
output = None
tempoutput = None
if args.inplace:
output = tempfile.NamedTemporaryFile(mode="w", delete=False)
tempoutput = pathlib.Path(output.name)
elif not args.output or args.output == "-":
output = sys.stdout
else:
output = pathlib.Path(args.output)
output = output.open("w", encoding="utf-8")
# Detect CSV dialect, sanity check header
dialect, has_header, input = detect_dialect(args, input)
if args.no_header:
has_header = False
reader = csv.reader(input, dialect)
header = None
if has_header:
header = next(reader)
timestamp_idx = column_name_to_index("timestamp", header) if has_header else 0
data_idx = column_name_to_index("data", header) if has_header else 3
if has_header:
if data_idx >= len(header):
logging.critical("'data' column not found in header '%s'", ",".join(header))
sys.exit(1)
# Write the new header
writer = csv.writer(output, dialect)
if has_header:
header += [
"raw-bits",
"data-bits",
"raw-bitrate",
"data-bitrate",
"raw-busload",
"data-busload",
]
writer.writerow(header)
# SOF + SRR + IDE + RTR + CF + CRC + ACK + EOF + IFS
overhead_bits = 1 + 2 + 1 + 6 + 16 + 2 + 7 + 3
# This isn't a true measure of bitrate, just an estimate, since it can't accomodate Remote or
# Error CAN frames, and assumes 29-bit IDs (as opposed to 11-bit). Additionally, it doesn't
# account for the time not spent sending data (in between messages), nor can it account for
# arbitration and ECU negotiation.
#
# The purpose of this script is to give an estimate, and a way to compare two different CAN logs
# to understand bus load.
window_size = 100
timestamp_ring = collections.deque(maxlen=window_size)
data_bits_ring = collections.deque(maxlen=window_size)
for row in reader:
if timestamp_idx >= len(row) or data_idx >= len(row):
logging.critical(
"Row not long enough to find field 'data' or 'timestamp' in row '%s'",
", ".join(row),
)
sys.exit(1)
value = row[timestamp_idx]
timestamp = None
if not value:
continue
try:
timestamp = float(value)
except ValueError:
logging.critical("Could not process non-float timestamp '%s'", value)
sys.exit(1)
value = row[data_idx]
# 4 bits per nibble with 1 char nibbles
data_bits = len(value) * 4
# Include the CAN ID in the data bits
data_bits += 29
raw_bits = data_bits + overhead_bits
timestamp_ring.append(timestamp)
duration = timestamp_ring[-1] - timestamp_ring[0]
data_bits_ring.append(data_bits)
data_bitrate = sum(data_bits_ring) / duration if duration else args.bitrate
raw_bitrate = (
(sum(data_bits_ring) + overhead_bits * len(data_bits_ring)) / duration
if duration
else args.bitrate
)
# The sliding window average takes some time to settle, so filter out extremes
data_bitrate = min(data_bitrate, args.bitrate)
raw_bitrate = min(raw_bitrate, args.bitrate)
raw_percent = raw_bitrate * 100 / args.bitrate
data_percent = data_bitrate * 100 / args.bitrate
row += [raw_bits, data_bits, raw_bitrate, data_bitrate, raw_percent, data_percent]
writer.writerow(row)
# Move the temp output file over the top of the input file
output.close()
input.close()
if args.inplace:
dst = pathlib.Path(args.input)
shutil.move(tempoutput, dst)
if __name__ == "__main__":
args = parse_args()
fmt = "%(asctime)s - %(module)s - %(levelname)s: %(message)s"
logging.basicConfig(
format=fmt,
level=args.log_level,
stream=sys.stderr,
)
# Color log output if possible, because I'm a sucker
try:
import coloredlogs
coloredlogs.install(fmt=fmt, level=args.log_level)
except ImportError:
pass
main(args)