Skip to content

Commit 31b8a7a

Browse files
committed
worked on hardbytes feedback
1 parent e4f4ef7 commit 31b8a7a

9 files changed

Lines changed: 127 additions & 101 deletions

File tree

can/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class CanError(IOError):
2020
from can.io import Logger, Printer, LogReader
2121
from can.io import ASCWriter, ASCReader
2222
from can.io import BLFReader, BLFWriter
23-
from can.io import canutilsLogReader, canutilsLogWriter
23+
from can.io import CanutilsLogReader, CanutilsLogWriter
2424
from can.io import CSVWriter
2525
from can.io import SqliteWriter, SqlReader
2626

can/io/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from .logger import Logger
77
from .player import LogReader
8-
from .log import canutilsLogReader, canutilsLogWriter
8+
from .log import CanutilsLogReader, CanutilsLogWriter
99
from .asc import ASCWriter, ASCReader
1010
from .blf import BLFReader, BLFWriter
1111
from .csv import CSVWriter

can/io/asc.py

Lines changed: 37 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@
44
from datetime import datetime
55
import time
66
CAN_MSG_EXT = 0x80000000
7-
7+
CAN_ID_MASK = 0x1FFFFFFF
88

99
class ASCReader(object):
1010
"""
1111
Iterator of CAN messages from a ASC Logging File.
12-
13-
Only CAN messages are supported (no Errorframes).
1412
"""
1513

1614
def __init__(self, filename):
@@ -19,41 +17,42 @@ def __init__(self, filename):
1917
def __iter__(self):
2018
for line in self.fp:
2119
temp = line.strip()
22-
if len(temp) > 0:
23-
if temp[0].isdigit():
24-
lineArray = temp.split()
25-
if lineArray[2] == "ErrorFrame":
26-
time = float(lineArray[0])
27-
msg = Message(timestamp=time, is_error_frame=True)
28-
yield msg
29-
continue
30-
if lineArray[1].isdigit() and lineArray[2] != "Statistic:":
31-
time = float(lineArray[0])
32-
channel = lineArray[1]
33-
if lineArray[2].endswith("x") or lineArray[2].endswith("X"):
34-
isExtended = True
35-
can_id = int(lineArray[2][0:-1], 16)
36-
else:
37-
isExtended = False
38-
can_id = int(lineArray[2],16)
39-
frameType = lineArray[4]
40-
if frameType == 'r' or frameType == 'R':
41-
msg = Message(timestamp=time,
42-
arbitration_id=can_id & 0x1FFFFFFF,
43-
extended_id=isExtended,
44-
is_remote_frame=True)
45-
else:
46-
dlc = int(lineArray[5])
47-
frame = bytearray()
48-
for byte in lineArray[6:6 + dlc]:
49-
frame.append(int(byte,16))
50-
msg = Message(timestamp=time,
51-
arbitration_id=can_id & 0x1FFFFFFF,
52-
extended_id=isExtended,
53-
is_remote_frame=False,
54-
dlc=dlc,
55-
data=frame)
56-
yield msg
20+
if len(temp) == 0 or not temp[0].isdigit():
21+
continue
22+
lineArray = temp.split()
23+
if lineArray[2] == "ErrorFrame":
24+
time = float(lineArray[0])
25+
msg = Message(timestamp=time, is_error_frame=True)
26+
yield msg
27+
continue
28+
if not lineArray[1].isdigit() or lineArray[2] == "Statistic:":
29+
continue
30+
time = float(lineArray[0])
31+
channel = lineArray[1]
32+
if lineArray[2].endswith("x") or lineArray[2].endswith("X"):
33+
isExtended = True
34+
can_id = int(lineArray[2][0:-1], 16)
35+
else:
36+
isExtended = False
37+
can_id = int(lineArray[2],16)
38+
frameType = lineArray[4]
39+
if frameType == 'r' or frameType == 'R':
40+
msg = Message(timestamp=time,
41+
arbitration_id=can_id & CAN_ID_MASK,
42+
extended_id=isExtended,
43+
is_remote_frame=True)
44+
else:
45+
dlc = int(lineArray[5])
46+
frame = bytearray()
47+
for byte in lineArray[6:6 + dlc]:
48+
frame.append(int(byte,16))
49+
msg = Message(timestamp=time,
50+
arbitration_id=can_id & CAN_ID_MASK,
51+
extended_id=isExtended,
52+
is_remote_frame=False,
53+
dlc=dlc,
54+
data=frame)
55+
yield msg
5756

5857

5958
class ASCWriter(Listener):

can/io/log.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
CAN_ERR_BUSERROR = 0x00000080
99
CAN_ERR_DLC = 8
1010

11-
class canutilsLogReader(object):
11+
class CanutilsLogReader(object):
1212
"""
1313
Iterator of CAN messages from a .log Logging File (candump -L).
1414
@@ -30,7 +30,7 @@ def __iter__(self):
3030
else:
3131
isExtended = False
3232
canId = int(canId, 16)
33-
if len(data) > 0 and (data[0] == "R" or data[0] == "r"):
33+
if len(data) > 0 and data[0].lower() == "r":
3434
isRemoteFrame = True
3535
if len(data) > 1:
3636
dlc = int(data[1:])
@@ -39,10 +39,10 @@ def __iter__(self):
3939
else:
4040
isRemoteFrame = False
4141

42-
dlc = len(data) / 2
42+
dlc = int(len(data) / 2)
4343
dataBin = bytearray()
44-
for i in range(0, int(dlc)):
45-
dataBin.append(int(data[i * 2:(i + 1) * 2], 16))
44+
for i in range(0, 2 * dlc, 2):
45+
dataBin.append(int(data[i:(i + 2)], 16))
4646

4747

4848
if canId & CAN_ERR_FLAG and canId & CAN_ERR_BUSERROR:
@@ -53,7 +53,7 @@ def __iter__(self):
5353
yield msg
5454

5555

56-
class canutilsLogWriter(Listener):
56+
class CanutilsLogWriter(Listener):
5757
"""Logs CAN data to an ASCII log file (.log)
5858
compatible to candump -L """
5959

@@ -69,6 +69,8 @@ def stop(self):
6969
self.log_file = None
7070

7171
def on_message_received(self, msg):
72+
if self.log_file is None:
73+
return
7274
if msg.is_error_frame:
7375
self.log_file.write("(%f) vcan0 %08X#0000000000000000\n" % (msg.timestamp, CAN_ERR_FLAG | CAN_ERR_BUSERROR, ))
7476
return
@@ -77,19 +79,18 @@ def on_message_received(self, msg):
7779
if timestamp >= self.started:
7880
timestamp -= self.started
7981

80-
if self.log_file is not None:
81-
if msg.is_remote_frame:
82-
data = []
83-
if msg.is_extended_id:
84-
self.log_file.write("(%f) vcan0 %08X#R\n" % (msg.timestamp, msg.arbitration_id ))
85-
else:
86-
self.log_file.write("(%f) vcan0 %03X#R\n" % (msg.timestamp, msg.arbitration_id ))
82+
if msg.is_remote_frame:
83+
data = []
84+
if msg.is_extended_id:
85+
self.log_file.write("(%f) vcan0 %08X#R\n" % (msg.timestamp, msg.arbitration_id ))
8786
else:
88-
data = ["{:02X}".format(byte) for byte in msg.data]
89-
if msg.is_extended_id:
90-
self.log_file.write("(%f) vcan0 %08X#%s\n" % (msg.timestamp, msg.arbitration_id, "".join(data)))
91-
else:
92-
self.log_file.write("(%f) vcan0 %03X#%s\n" % (msg.timestamp, msg.arbitration_id, "".join(data)))
87+
self.log_file.write("(%f) vcan0 %03X#R\n" % (msg.timestamp, msg.arbitration_id ))
88+
else:
89+
data = ["{:02X}".format(byte) for byte in msg.data]
90+
if msg.is_extended_id:
91+
self.log_file.write("(%f) vcan0 %08X#%s\n" % (msg.timestamp, msg.arbitration_id, "".join(data)))
92+
else:
93+
self.log_file.write("(%f) vcan0 %03X#%s\n" % (msg.timestamp, msg.arbitration_id, "".join(data)))
9394

9495

9596

can/io/logger.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from .csv import CSVWriter
44
from .sqlite import SqliteWriter
55
from .stdout import Printer
6-
from .log import canutilsLogWriter
6+
from .log import CanutilsLogWriter
77

88
class Logger(object):
99
"""
@@ -28,7 +28,7 @@ def __new__(cls, other, filename):
2828
elif filename.endswith(".asc"):
2929
return ASCWriter(filename)
3030
elif filename.endswith(".log"):
31-
return canutilsLogWriter(filename)
31+
return CanutilsLogWriter(filename)
3232
elif filename.endswith(".blf"):
3333
return BLFWriter(filename)
3434
elif filename.endswith(".csv"):

can/io/player.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44

55
from .asc import ASCReader
6-
from .log import canutilsLogReader
6+
from .log import CanutilsLogReader
77
from .blf import BLFReader
88
from .sqlite import SqlReader
99

@@ -39,7 +39,7 @@ def __new__(cls, other, filename):
3939
if filename.endswith(".asc"):
4040
return ASCReader(filename)
4141
if filename.endswith(".log"):
42-
return canutilsLogReader(filename)
42+
return CanutilsLogReader(filename)
4343

4444
raise NotImplementedError("No read support for this log format")
4545

examples/simpleLogConvert.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
#!/usr/bin/env python
2+
# use it to convert .can-log files
3+
# usage: simpleLogConvert.py sourceLog.asc targetLog.log
4+
25
import sys
36
import can.io.logger
47
import can.io.player

test/listener_test.py

Lines changed: 2 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def testClassesImportable(self):
4444
assert hasattr(can, 'BufferedReader')
4545
assert hasattr(can, 'Notifier')
4646
assert hasattr(can, 'ASCWriter')
47-
assert hasattr(can, 'canutilsLogWriter')
47+
assert hasattr(can, 'CanutilsLogWriter')
4848
assert hasattr(can, 'SqlReader')
4949

5050

@@ -72,7 +72,7 @@ def test_filetype_to_instance(extension, klass):
7272
can_logger.stop()
7373

7474
test_filetype_to_instance('asc', can.ASCWriter)
75-
test_filetype_to_instance('log', can.canutilsLogWriter)
75+
test_filetype_to_instance('log', can.CanutilsLogWriter)
7676
test_filetype_to_instance("blf", can.BLFWriter)
7777
test_filetype_to_instance("csv", can.CSVWriter)
7878
test_filetype_to_instance("db", can.SqliteWriter)
@@ -218,42 +218,5 @@ def test_reader_writer(self):
218218
self.assertEqual(msg1, msg2)
219219
self.assertAlmostEqual(msg1.timestamp, msg2.timestamp)
220220

221-
class canutilsLog(unittest.TestCase):
222-
223-
def test_reader_writer(self):
224-
f = tempfile.NamedTemporaryFile('w', delete=False)
225-
f.close()
226-
filename = f.name
227-
writer = can.canutilsLogWriter(filename)
228-
229-
for msg in TEST_MESSAGES:
230-
writer(msg)
231-
writer.stop()
232-
233-
messages = list(can.canutilsLogReader(filename))
234-
self.assertEqual(len(messages), len(TEST_MESSAGES))
235-
for msg1, msg2 in zip(messages, TEST_MESSAGES):
236-
self.assertEqual(msg1, msg2)
237-
self.assertAlmostEqual(msg1.timestamp, msg2.timestamp)
238-
239-
class ascFileFormat(unittest.TestCase):
240-
241-
def test_reader_writer(self):
242-
f = tempfile.NamedTemporaryFile('w', delete=False)
243-
f.close()
244-
filename = f.name
245-
246-
writer = can.ASCWriter(filename)
247-
for msg in TEST_MESSAGES:
248-
writer(msg)
249-
writer.stop()
250-
251-
messages = list(can.ASCReader(filename))
252-
self.assertEqual(len(messages), len(TEST_MESSAGES))
253-
for msg1, msg2 in zip(messages, TEST_MESSAGES):
254-
self.assertEqual(msg1, msg2)
255-
self.assertAlmostEqual(msg1.timestamp, msg2.timestamp)
256-
257-
258221
if __name__ == '__main__':
259222
unittest.main()

test/logformats_test.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import unittest
2+
import tempfile
3+
import can
4+
5+
# List of messages of different types that can be used in tests
6+
TEST_MESSAGES = [
7+
can.Message(
8+
arbitration_id=0xDADADA, extended_id=True, is_remote_frame=False,
9+
timestamp=1483389464.165,
10+
data=[1, 2, 3, 4, 5, 6, 7, 8]),
11+
can.Message(
12+
arbitration_id=0x123, extended_id=False, is_remote_frame=False,
13+
timestamp=1483389464.365,
14+
data=[254, 255]),
15+
can.Message(
16+
arbitration_id=0x768, extended_id=False, is_remote_frame=True,
17+
timestamp=1483389466.165),
18+
can.Message(is_error_frame=True, timestamp=1483389466.170),
19+
]
20+
21+
22+
class TestCanutilsLog(unittest.TestCase):
23+
24+
def test_reader_writer(self):
25+
f = tempfile.NamedTemporaryFile('w', delete=False)
26+
f.close()
27+
filename = f.name
28+
writer = can.CanutilsLogWriter(filename)
29+
30+
for msg in TEST_MESSAGES:
31+
writer(msg)
32+
writer.stop()
33+
34+
messages = list(can.CanutilsLogReader(filename))
35+
self.assertEqual(len(messages), len(TEST_MESSAGES))
36+
for msg1, msg2 in zip(messages, TEST_MESSAGES):
37+
self.assertEqual(msg1, msg2)
38+
self.assertAlmostEqual(msg1.timestamp, msg2.timestamp)
39+
40+
class TestAscFileFormat(unittest.TestCase):
41+
42+
def test_reader_writer(self):
43+
f = tempfile.NamedTemporaryFile('w', delete=False)
44+
f.close()
45+
filename = f.name
46+
47+
writer = can.ASCWriter(filename)
48+
for msg in TEST_MESSAGES:
49+
writer(msg)
50+
writer.stop()
51+
52+
messages = list(can.ASCReader(filename))
53+
self.assertEqual(len(messages), len(TEST_MESSAGES))
54+
for msg1, msg2 in zip(messages, TEST_MESSAGES):
55+
self.assertEqual(msg1, msg2)
56+
self.assertAlmostEqual(msg1.timestamp, msg2.timestamp)
57+
58+
if __name__ == '__main__':
59+
unittest.main()
60+

0 commit comments

Comments
 (0)