Source code for

#!/usr/bin/env python
# coding: utf-8

Contains handling of ASC logging files.

Example .asc file:

from datetime import datetime
import time
import logging

from can.listener import Listener
from can.message import Message
from can.util import channel2int

CAN_MSG_EXT = 0x80000000

logger = logging.getLogger('')

[docs]class ASCReader(object): """ Iterator of CAN messages from a ASC logging file. TODO: turn realtive timestamps back to absolute form """ def __init__(self, filename): self.file = open(filename, 'r') @staticmethod def _extract_can_id(str_can_id): if str_can_id[-1:].lower() == 'x': is_extended = True can_id = int(str_can_id[0:-1], 16) else: is_extended = False can_id = int(str_can_id, 16) logging.debug('ASCReader: _extract_can_id("%s") -> %x, %r', str_can_id, can_id, is_extended) return (can_id, is_extended) def __iter__(self): for line in self.file: logger.debug("ASCReader: parsing line: '%s'", line.splitlines()[0]) temp = line.strip() if not temp or not temp[0].isdigit(): continue try: (timestamp, channel, dummy) = temp.split(None, 2) # , frameType, dlc, frameData except ValueError: # we parsed an empty comment continue timestamp = float(timestamp) try: # See ASCWriter channel = int(channel) - 1 except ValueError: pass if dummy.strip()[0:10] == 'ErrorFrame': msg = Message(timestamp=timestamp, is_error_frame=True, channel=channel) yield msg elif not isinstance(channel, int) or dummy.strip()[0:10] == 'Statistic:': pass elif dummy[-1:].lower() == 'r': (can_id_str, _) = dummy.split(None, 1) (can_id_num, is_extended_id) = self._extract_can_id(can_id_str) msg = Message(timestamp=timestamp, arbitration_id=can_id_num & CAN_ID_MASK, extended_id=is_extended_id, is_remote_frame=True, channel=channel) yield msg else: try: # this only works if dlc > 0 and thus data is availabe (can_id_str, _, _, dlc, data) = dummy.split(None, 4) except ValueError: # but if not, we only want to get the stuff up to the dlc (can_id_str, _, _, dlc ) = dummy.split(None, 3) # and we set data to an empty sequence manually data = '' dlc = int(dlc) frame = bytearray() data = data.split() for byte in data[0:dlc]: frame.append(int(byte, 16)) (can_id_num, is_extended_id) = self._extract_can_id(can_id_str) msg = Message( timestamp=timestamp, arbitration_id=can_id_num & CAN_ID_MASK, extended_id=is_extended_id, is_remote_frame=False, dlc=dlc, data=frame, channel=channel) yield msg
[docs]class ASCWriter(Listener): """Logs CAN data to an ASCII log file (.asc). The measurement starts with the timestamp of the first registered message. If a message has a timestamp smaller than the previous one (or 0 or None), it gets assigned the timestamp that was written for the last message. It the first message does not have a timestamp, it is set to zero. """ FORMAT_MESSAGE = "{channel} {id:<15} Rx {dtype} {data}" FORMAT_DATE = "%a %b %m %I:%M:%S %p %Y" FORMAT_EVENT = "{timestamp: 9.4f} {message}\n" def __init__(self, filename, channel=1): # setup = channel self.log_file = open(filename, 'w') # write start of file header now ="%a %b %m %I:%M:%S %p %Y") self.log_file.write("date %s\n" % now) self.log_file.write("base hex timestamps absolute\n") self.log_file.write("internal events logged\n") # the last part is written with the timestamp of the first message self.header_written = False self.last_timestamp = None self.started = None
[docs] def stop(self): """Stops logging and closes the file.""" if not self.log_file.closed: self.log_file.write("End TriggerBlock\n") self.log_file.close()
[docs] def log_event(self, message, timestamp=None): """Add a message to the log file. :param str message: an arbitrary message :param float timestamp: the absolute timestamp of the event """ if not message: # if empty or None logger.debug("ASCWriter: ignoring empty message") return # this is the case for the very first message: if not self.header_written: self.last_timestamp = (timestamp or 0.0) self.started = self.last_timestamp formatted_date = time.strftime(self.FORMAT_DATE, time.localtime(self.last_timestamp)) self.log_file.write("base hex timestamps absolute\n") self.log_file.write("Begin Triggerblock %s\n" % formatted_date) self.header_written = True self.log_event("Start of measurement") # recursive call # figure out the correct timestamp if timestamp is None or timestamp < self.last_timestamp: timestamp = self.last_timestamp # turn into relative timestamps if necessary if timestamp >= self.started: timestamp -= self.started line = self.FORMAT_EVENT.format(timestamp=timestamp, message=message) if self.log_file.closed: logger.warn("ASCWriter: ignoring write call to closed file") else: self.log_file.write(line)
def on_message_received(self, msg): if msg.is_error_frame: self.log_event("{} ErrorFrame".format(, msg.timestamp) return if msg.is_remote_frame: dtype = 'r' data = [] else: dtype = "d {}".format(msg.dlc) data = ["{:02X}".format(byte) for byte in] arb_id = "{:X}".format(msg.arbitration_id) if msg.is_extended_id: arb_id += 'x' channel = channel2int( if channel is None: channel = else: # Many interfaces start channel numbering at 0 which is invalid channel += 1 serialized = self.FORMAT_MESSAGE.format(channel=channel, id=arb_id, dtype=dtype, data=' '.join(data)) self.log_event(serialized, msg.timestamp)