33
44"""
55This module contains handling for CSV (comma seperated values) files.
6+
7+ TODO: CAN FD messages are not yet supported.
8+ TODO: This module could use https://docs.python.org/2/library/csv.html#module-csv
9+ to allow different delimiters for writing, special escape chars to circumvent
10+ the base64 encoding and use csv.Sniffer to automatically deduce the delimiters
11+ of a CSV file.
612"""
713
8- import base64
14+ from base64 import b64encode , b64decode
915
16+ from can .message import Message
1017from can .listener import Listener
1118
1219
13- # TODO allow other seperators in CSVWriter
14-
1520class CSVWriter (Listener ):
1621 """Writes a comma separated text file of
1722
@@ -21,14 +26,15 @@ class CSVWriter(Listener):
2126 * dlc and
2227 * data
2328
24- for each messages received. Each line is terminated with a '\\ n'.
29+ for each message received. Each line is terminated with a platform
30+ specific line seperator.
2531 """
2632
2733 def __init__ (self , filename ):
2834 self .csv_file = open (filename , 'wt' )
2935
3036 # Write a header row
31- self .csv_file .write ("timestamp, arbitration id, extended, remote, error, dlc, data\n " )
37+ self .csv_file .write ("timestamp,arbitration_id, extended,remote,error,dlc,data\n " )
3238
3339 def on_message_received (self , msg ):
3440 row = ',' .join ([
@@ -38,7 +44,7 @@ def on_message_received(self, msg):
3844 '1' if msg .is_remote_frame else '0' ,
3945 '1' if msg .is_error_frame else '0' ,
4046 str (msg .dlc ),
41- base64 . b64encode (msg .data ).decode ('utf8' )
47+ b64encode (msg .data ).decode ('utf8' )
4248 ])
4349 self .csv_file .write (row + '\n ' )
4450
@@ -47,4 +53,30 @@ def stop(self):
4753 self .csv_file .close ()
4854
4955class CSVReader ():
50- pass
56+ """Iterator over CAN messages from a .csv file that was
57+ generated by :class:`~can.CSVWriter` or that uses the same
58+ format that is described there.
59+ """
60+
61+ def __init__ (self , filename ):
62+ self .csv_file = open (filename , 'rt' )
63+
64+ # skip the header line
65+ self .header_line = next (self .csv_file ).split (',' )
66+
67+ def __iter__ (self ):
68+ for line in self .csv_file :
69+
70+ timestamp , arbitration_id , extended , remote , error , dlc , data = line .split (',' )
71+
72+ yield Message (
73+ timestamp = float (timestamp ),
74+ is_remote_frame = (remote == '1' ),
75+ extended_id = (extended == '1' ),
76+ is_error_frame = (error == '1' ),
77+ arbitration_id = int (arbitration_id , base = 16 ),
78+ dlc = int (dlc ),
79+ data = b64decode (data ),
80+ )
81+
82+ self .csv_file .close ()
0 commit comments