X-Git-Url: https://sigrok.org/gitweb/?p=libsigrokdecode.git;a=blobdiff_plain;f=decoders%2Fcan%2Fpd.py;h=0c96ad32a35bc56daa117fea73d36e90096d7901;hp=bf38b7fb9d0e1d23f9a9b83dd76ba82349ed7a84;hb=fd41596ace75474b122f697ba85ffab28cc0dca7;hpb=12851357e784b893e24880efc6cd22a0cbcc64ce diff --git a/decoders/can/pd.py b/decoders/can/pd.py index bf38b7f..0c96ad3 100644 --- a/decoders/can/pd.py +++ b/decoders/can/pd.py @@ -2,6 +2,7 @@ ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2012-2013 Uwe Hermann +## Copyright (C) 2019 Stephan Thiele ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by @@ -14,21 +15,24 @@ ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License -## along with this program; if not, write to the Free Software -## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +## along with this program; if not, see . ## import sigrokdecode as srd +class SamplerateError(Exception): + pass + class Decoder(srd.Decoder): - api_version = 2 + api_version = 3 id = 'can' name = 'CAN' longname = 'Controller Area Network' desc = 'Field bus protocol for distributed realtime control.' license = 'gplv2+' inputs = ['logic'] - outputs = ['can'] + outputs = [] + tags = ['Automotive'] channels = ( {'id': 'can_rx', 'name': 'CAN RX', 'desc': 'CAN bus line'}, ) @@ -54,9 +58,22 @@ class Decoder(srd.Decoder): ('ack-delimiter', 'ACK delimiter'), ('stuff-bit', 'Stuff bit'), ('warnings', 'Human-readable warnings'), + ('bit', 'Bit'), + ) + annotation_rows = ( + ('bits', 'Bits', (15, 17)), + ('fields', 'Fields', tuple(range(15))), + ('warnings', 'Warnings', (16,)), ) + fd = False + + def __init__(self): + self.reset() - def __init__(self, **kwargs): + def dlc2len(self, dlc): + return [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64][dlc] + + def reset(self): self.samplerate = None self.reset_variables() @@ -67,11 +84,11 @@ class Decoder(srd.Decoder): if key == srd.SRD_CONF_SAMPLERATE: self.samplerate = value self.bit_width = float(self.samplerate) / float(self.options['bitrate']) - self.bitpos = (self.bit_width / 100.0) * self.options['sample_point'] + self.sample_point = (self.bit_width / 100.0) * self.options['sample_point'] # Generic helper for CAN bit annotations. def putg(self, ss, es, data): - left, right = int(self.bitpos), int(self.bit_width - self.bitpos) + left, right = int(self.sample_point), int(self.bit_width - self.sample_point) self.put(ss - left, es + right, self.out_ann, data) # Single-CAN-bit annotation using the current samplenum. @@ -97,23 +114,37 @@ class Decoder(srd.Decoder): self.ss_bit12 = None self.ss_databytebits = [] - # Return True if we reached the desired bit position, False otherwise. - def reached_bit(self, bitnum): - bitpos = int(self.sof + (self.bit_width * bitnum) + self.bitpos) - if self.samplenum >= bitpos: - return True - return False + # Poor man's clock synchronization. Use signal edges which change to + # dominant state in rather simple ways. This naive approach is neither + # aware of the SYNC phase's width nor the specific location of the edge, + # but improves the decoder's reliability when the input signal's bitrate + # does not exactly match the nominal rate. + def dom_edge_seen(self, force = False): + self.dom_edge_snum = self.samplenum + self.dom_edge_bcount = self.curbit + + def bit_sampled(self): + # EMPTY + pass + + # Determine the position of the next desired bit's sample point. + def get_sample_point(self, bitnum): + samplenum = self.dom_edge_snum + samplenum += int(self.bit_width * (bitnum - self.dom_edge_bcount)) + samplenum += int(self.sample_point) + return samplenum def is_stuff_bit(self): # CAN uses NRZ encoding and bit stuffing. # After 5 identical bits, a stuff bit of opposite value is added. + # But not in the CRC delimiter, ACK, and end of frame fields. + if len(self.bits) > self.last_databit + 17: + return False last_6_bits = self.rawbits[-6:] if last_6_bits not in ([0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0]): return False # Stuff bit. Keep it in self.rawbits, but drop it from self.bits. - self.putx([15, ['Stuff bit: %d' % self.rawbits[-1], - 'SB: %d' % self.rawbits[-1], 'SB']]) self.bits.pop() # Drop last bit. return True @@ -135,38 +166,60 @@ class Decoder(srd.Decoder): if bitnum == (self.last_databit + 1): self.ss_block = self.samplenum - # CRC sequence (15 bits) - elif bitnum == (self.last_databit + 15): + if self.fd: + if self.dlc2len(self.dlc) < 16: + self.crc_len = 27 # 17 + SBC + stuff bits + else: + self.crc_len = 32 # 21 + SBC + stuff bits + else: + self.crc_len = 15 + + # CRC sequence (15 bits, 17 bits or 21 bits) + elif bitnum == (self.last_databit + self.crc_len): + if self.fd: + if self.dlc2len(self.dlc) < 16: + crc_type = "CRC-17" + else: + crc_type = "CRC-21" + else: + crc_type = "CRC-15" + x = self.last_databit + 1 - crc_bits = self.bits[x:x + 15 + 1] + crc_bits = self.bits[x:x + self.crc_len + 1] self.crc = int(''.join(str(d) for d in crc_bits), 2) - self.putb([11, ['CRC sequence: 0x%04x' % self.crc, - 'CRC: 0x%04x' % self.crc, 'CRC']]) + self.putb([11, ['%s sequence: 0x%04x' % (crc_type, self.crc), + '%s: 0x%04x' % (crc_type, self.crc), '%s' % crc_type]]) if not self.is_valid_crc(crc_bits): self.putb([16, ['CRC is invalid']]) # CRC delimiter bit (recessive) - elif bitnum == (self.last_databit + 16): + elif bitnum == (self.last_databit + self.crc_len + 1): self.putx([12, ['CRC delimiter: %d' % can_rx, 'CRC d: %d' % can_rx, 'CRC d']]) + if can_rx != 1: + self.putx([16, ['CRC delimiter must be a recessive bit']]) # ACK slot bit (dominant: ACK, recessive: NACK) - elif bitnum == (self.last_databit + 17): + elif bitnum == (self.last_databit + self.crc_len + 2): ack = 'ACK' if can_rx == 0 else 'NACK' self.putx([13, ['ACK slot: %s' % ack, 'ACK s: %s' % ack, 'ACK s']]) # ACK delimiter bit (recessive) - elif bitnum == (self.last_databit + 18): + elif bitnum == (self.last_databit + self.crc_len + 3): self.putx([14, ['ACK delimiter: %d' % can_rx, 'ACK d: %d' % can_rx, 'ACK d']]) + if can_rx != 1: + self.putx([16, ['ACK delimiter must be a recessive bit']]) # Remember start of EOF (see below). - elif bitnum == (self.last_databit + 19): + elif bitnum == (self.last_databit + self.crc_len + 4): self.ss_block = self.samplenum # End of frame (EOF), 7 recessive bits - elif bitnum == (self.last_databit + 25): + elif bitnum == (self.last_databit + self.crc_len + 11): self.putb([2, ['End of frame', 'EOF', 'E']]) + if self.rawbits[-7:] != [1, 1, 1, 1, 1, 1, 1]: + self.putb([16, ['End of frame (EOF) must be 7 recessive bits']]) self.reset_variables() return True @@ -175,40 +228,62 @@ class Decoder(srd.Decoder): # Returns True if the frame ended (EOF), False otherwise. def decode_standard_frame(self, can_rx, bitnum): - # Bit 14: RB0 (reserved bit) - # Has to be sent dominant, but receivers should accept recessive too. + # Bit 14: FDF (Flexible Data Format) + # Has to be sent dominant when FD frame, has to be sent recessive when classic CAN frame. if bitnum == 14: - self.putx([7, ['Reserved bit 0: %d' % can_rx, - 'RB0: %d' % can_rx, 'RB0']]) + self.fd = True if can_rx else False - # Bit 12: Remote transmission request (RTR) bit - # Data frame: dominant, remote frame: recessive - # Remote frames do not contain a data field. - rtr = 'remote' if self.bits[12] == 1 else 'data' - self.put12([8, ['Remote transmission request: %s frame' % rtr, - 'RTR: %s frame' % rtr, 'RTR']]) + self.putx([7, ['Flexible Data Format: %d' % can_rx, + 'FDF: %d' % can_rx, + 'FDF']]) + + # SRR Substitute Remote Request + if self.fd: + self.put12([8, ['Substitute Remote Request', 'SRR']]) + self.dlc_start = 18 + else: + # Bit 12: Remote transmission request (RTR) bit + # Data frame: dominant, remote frame: recessive + # Remote frames do not contain a data field. + rtr = 'remote' if self.bits[12] == 1 else 'data' + self.put12([8, ['Remote transmission request: %s frame' % rtr, + 'RTR: %s frame' % rtr, 'RTR']]) + self.dlc_start = 15 + + # TODO: add Res, BRS and ESI bits when FD format: + if bitnum == 15: + if self.fd: + self.putx([7, ['Reserved: %d' % can_rx, 'R0: %d' % can_rx, 'R0']]) + + if bitnum == 16: + if self.fd: + self.putx([7, ['Bit rate switch: %d' % can_rx, 'BRS: %d' % can_rx, 'BRS']]) + + if bitnum == 17: + if self.fd: + self.putx([7, ['Error state indicator: %d' % can_rx, 'ESI: %d' % can_rx, 'ESI']]) # Remember start of DLC (see below). - elif bitnum == 15: + elif bitnum == self.dlc_start: self.ss_block = self.samplenum # Bits 15-18: Data length code (DLC), in number of bytes (0-8). - elif bitnum == 18: - self.dlc = int(''.join(str(d) for d in self.bits[15:18 + 1]), 2) - self.putb([10, ['Data length code: %d' % self.dlc, - 'DLC: %d' % self.dlc, 'DLC']]) - self.last_databit = 18 + (self.dlc * 8) + elif bitnum == self.dlc_start + 3: + self.dlc = int(''.join(str(d) for d in self.bits[self.dlc_start:self.dlc_start + 4]), 2) + self.putb([10, ['Data length code: %d (%d Bytes)' % (self.dlc, self.dlc2len(self.dlc)), + 'DLC: %d (%d B)' % (self.dlc, self.dlc2len(self.dlc)), 'DLC']]) + self.last_databit = self.dlc_start + 3 + (self.dlc2len(self.dlc) * 8) # Remember all databyte bits, except the very last one. - elif bitnum in range(19, self.last_databit): + elif bitnum in range(self.dlc_start + 4, self.last_databit): self.ss_databytebits.append(self.samplenum) # Bits 19-X: Data field (0-8 bytes, depending on DLC) # The bits within a data byte are transferred MSB-first. elif bitnum == self.last_databit: self.ss_databytebits.append(self.samplenum) # Last databyte bit. - for i in range(self.dlc): - x = 18 + (8 * i) + 1 + for i in range(self.dlc2len(self.dlc)): + x = self.dlc_start + 4 + (8 * i) b = int(''.join(str(d) for d in self.bits[x:x + 8]), 2) ss = self.ss_databytebits[i * 8] es = self.ss_databytebits[((i + 1) * 8) - 1] @@ -269,9 +344,9 @@ class Decoder(srd.Decoder): # Bits 35-38: Data length code (DLC), in number of bytes (0-8). elif bitnum == 38: self.dlc = int(''.join(str(d) for d in self.bits[35:38 + 1]), 2) - self.putb([10, ['Data length code: %d' % self.dlc, - 'DLC: %d' % self.dlc, 'DLC']]) - self.last_databit = 38 + (self.dlc * 8) + self.putb([10, ['Data length code: %d (%d Bytes)' % (self.dlc, self.dlc2len(self.dlc)), + 'DLC: %d (%d B)' % (self.dlc, self.dlc2len(self.dlc)), 'DLC']]) + self.last_databit = 38 + (self.dlc2len(self.dlc) * 8) # Remember all databyte bits, except the very last one. elif bitnum in range(39, self.last_databit): @@ -281,7 +356,7 @@ class Decoder(srd.Decoder): # The bits within a data byte are transferred MSB-first. elif bitnum == self.last_databit: self.ss_databytebits.append(self.samplenum) # Last databyte bit. - for i in range(self.dlc): + for i in range(self.dlc2len(self.dlc)): x = 38 + (8 * i) + 1 b = int(''.join(str(d) for d in self.bits[x:x + 8]), 2) ss = self.ss_databytebits[i * 8] @@ -302,20 +377,18 @@ class Decoder(srd.Decoder): # Get the index of the current CAN frame bit (without stuff bits). bitnum = len(self.bits) - 1 - # For debugging. - # self.putx([0, ['Bit %d (CAN bit %d): %d' % \ - # (self.curbit, bitnum, can_rx)]]) - # If this is a stuff bit, remove it from self.bits and ignore it. if self.is_stuff_bit(): + self.putx([15, [str(can_rx)]]) self.curbit += 1 # Increase self.curbit (bitnum is not affected). return + else: + self.putx([17, [str(can_rx)]]) # Bit 0: Start of frame (SOF) bit if bitnum == 0: - if can_rx == 0: - self.putx([1, ['Start of frame', 'SOF', 'S']]) - else: + self.putx([1, ['Start of frame', 'SOF', 'S']]) + if can_rx != 0: self.putx([16, ['Start of frame (SOF) must be a dominant bit']]) # Remember start of ID (see below). @@ -328,6 +401,8 @@ class Decoder(srd.Decoder): self.id = int(''.join(str(d) for d in self.bits[1:]), 2) s = '%d (0x%x)' % (self.id, self.id), self.putb([3, ['Identifier: %s' % s, 'ID: %s' % s, 'ID']]) + if (self.id & 0x7f0) == 0x7f0: + self.putb([16, ['Identifier bits 10..4 must not be all recessive']]) # RTR or SRR bit, depending on frame type (gets handled later). elif bitnum == 12: @@ -357,25 +432,24 @@ class Decoder(srd.Decoder): self.curbit += 1 - def decode(self, ss, es, data): - if self.samplerate is None: - raise Exception("Cannot decode without samplerate.") - for (self.samplenum, pins) in data: - - (can_rx,) = pins + def decode(self): + if not self.samplerate: + raise SamplerateError('Cannot decode without samplerate.') + while True: # State machine. if self.state == 'IDLE': # Wait for a dominant state (logic 0) on the bus. - if can_rx == 1: - continue + (can_rx,) = self.wait({0: 'l'}) self.sof = self.samplenum + self.dom_edge_seen(force = True) self.state = 'GET BITS' elif self.state == 'GET BITS': # Wait until we're in the correct bit/sampling position. - if not self.reached_bit(self.curbit): - continue - self.handle_bit(can_rx) - else: - raise Exception("Invalid state: %s" % self.state) - + pos = self.get_sample_point(self.curbit) + (can_rx,) = self.wait([{'skip': pos - self.samplenum}, {0: 'f'}]) + if self.matched[1]: + self.dom_edge_seen() + if self.matched[0]: + self.handle_bit(can_rx) + self.bit_sampled()