Skip to content

Commit d66a787

Browse files
christiansandberghardbyte
authored andcommitted
Add log_event method and channel to ASCWriter.
1 parent c19516b commit d66a787

2 files changed

Lines changed: 16 additions & 6 deletions

File tree

‎can/CAN.py‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -230,24 +230,33 @@ class ASCWriter(Listener):
230230
"""Logs CAN data to an ASCII log file (.asc)"""
231231

232232
LOG_STRING = "{time: 9.4f} {channel} {id:<15} Rx d {dlc} {data}\n"
233+
EVENT_STRING = "{time: 9.4f} {message}\n"
233234

234-
def __init__(self, filename):
235+
def __init__(self, filename, channel=1):
235236
now = datetime.now().strftime("%a %b %m %I:%M:%S %p %Y")
237+
self.channel = channel
236238
self.started = time.time()
237239
self.log_file = open(filename, "w")
238240
self.log_file.write("date %s\n" % now)
239241
self.log_file.write("base hex timestamps absolute\n")
240242
self.log_file.write("internal events logged\n")
241243
self.log_file.write("Begin Triggerblock %s\n" % now)
242-
self.log_file.write(" 0.0000 Start of measurement\n")
244+
self.log_event("Start of measurement")
243245

244246
def stop(self):
245247
"""Stops logging and closes the file."""
246-
if self.log_file:
248+
if self.log_file is not None:
247249
self.log_file.write("End TriggerBlock\n")
248250
self.log_file.close()
249251
self.log_file = None
250252

253+
def log_event(self, message):
254+
"""Add an arbitrary message to the log file."""
255+
timestamp = time.time() - self.started
256+
line = self.EVENT_STRING.format(time=timestamp, message=message)
257+
if self.log_file is not None:
258+
self.log_file.write(line)
259+
251260
def on_message_received(self, msg):
252261
data = ["{:02X}".format(byte) for byte in msg.data]
253262
arb_id = "{:X}".format(msg.arbitration_id)
@@ -258,9 +267,9 @@ def on_message_received(self, msg):
258267
timestamp -= self.started
259268

260269
line = self.LOG_STRING.format(time=timestamp,
261-
channel=1,
270+
channel=self.channel,
262271
id=arb_id,
263272
dlc=msg.dlc,
264273
data=" ".join(data))
265-
if self.log_file:
274+
if self.log_file is not None:
266275
self.log_file.write(line)

‎test/listener_test.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@ def testSQLWriterReceives(self):
6666
assert msg[1] == 0xDADADA
6767

6868
def testAscListener(self):
69-
a_listener = can.ASCWriter("test.asc")
69+
a_listener = can.ASCWriter("test.asc", channel=2)
70+
a_listener.log_event("This is some comment")
7071
msg = can.Message(extended_id=True,
7172
timestamp=a_listener.started + 0.5,
7273
arbitration_id=0xabcdef,

0 commit comments

Comments
 (0)