]> sigrok.org Git - libsigrokdecode.git/blame - decoders/can/pd.py
uart: Output data in separate RX and TX annotation types.
[libsigrokdecode.git] / decoders / can / pd.py
CommitLineData
702fa251 1##
50bd5d25 2## This file is part of the libsigrokdecode project.
702fa251 3##
e20f455c 4## Copyright (C) 2012-2013 Uwe Hermann <uwe@hermann-uwe.de>
702fa251
UH
5##
6## This program is free software; you can redistribute it and/or modify
7## it under the terms of the GNU General Public License as published by
8## the Free Software Foundation; either version 2 of the License, or
9## (at your option) any later version.
10##
11## This program is distributed in the hope that it will be useful,
12## but WITHOUT ANY WARRANTY; without even the implied warranty of
13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14## GNU General Public License for more details.
15##
16## You should have received a copy of the GNU General Public License
17## along with this program; if not, write to the Free Software
18## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19##
20
21# CAN protocol decoder
22
23import sigrokdecode as srd
24
25class Decoder(srd.Decoder):
26 api_version = 1
27 id = 'can'
28 name = 'CAN'
9e1437a0 29 longname = 'Controller Area Network'
702fa251
UH
30 desc = 'Field bus protocol for distributed realtime control.'
31 license = 'gplv2+'
32 inputs = ['logic']
33 outputs = ['can']
34 probes = [
35 {'id': 'can_rx', 'name': 'CAN RX', 'desc': 'CAN bus line'},
36 ]
37 optional_probes = []
38 options = {
39 'bitrate': ['Bitrate', 1000000], # 1Mbit/s
40 'sample_point': ['Sample point', 70], # 70%
41 }
42 annotations = [
43 ['Text', 'Human-readable text'],
44 ['Warnings', 'Human-readable warnings'],
45 ]
46
47 def __init__(self, **kwargs):
48 self.reset_variables()
49
50 def start(self, metadata):
51 # self.out_proto = self.add(srd.OUTPUT_PROTO, 'can')
52 self.out_ann = self.add(srd.OUTPUT_ANN, 'can')
53
54 self.samplerate = metadata['samplerate']
55 self.bit_width = float(self.samplerate) / float(self.options['bitrate'])
56 self.bitpos = (self.bit_width / 100.0) * self.options['sample_point']
57
58 def report(self):
59 pass
60
4b1813b4
UH
61 # Generic helper for CAN bit annotations.
62 def putg(self, ss, es, data):
63 left, right = int(self.bitpos), int(self.bit_width - self.bitpos)
64 self.put(ss - left, es + right, self.out_ann, data)
65
66 # Single-CAN-bit annotation using the current samplenum.
e20f455c 67 def putx(self, data):
4b1813b4
UH
68 self.putg(self.samplenum, self.samplenum, data)
69
70 # Single-CAN-bit annotation using the samplenum of CAN bit 12.
71 def put12(self, data):
72 self.putg(self.ss_bit12, self.ss_bit12, data)
73
74 # Multi-CAN-bit annotation from self.ss_block to current samplenum.
75 def putb(self, data):
76 self.putg(self.ss_block, self.samplenum, data)
e20f455c 77
702fa251
UH
78 def reset_variables(self):
79 self.state = 'IDLE'
80 self.sof = self.frame_type = self.dlc = None
81 self.rawbits = [] # All bits, including stuff bits
82 self.bits = [] # Only actual CAN frame bits (no stuff bits)
83 self.curbit = 0 # Current bit of CAN frame (bit 0 == SOF)
84 self.last_databit = 999 # Positive value that bitnum+x will never match
4b1813b4
UH
85 self.ss_block = None
86 self.ss_bit12 = None
87 self.ss_databytebits = []
702fa251
UH
88
89 # Return True if we reached the desired bit position, False otherwise.
90 def reached_bit(self, bitnum):
91 bitpos = int(self.sof + (self.bit_width * bitnum) + self.bitpos)
92 if self.samplenum >= bitpos:
93 return True
94 return False
95
96 def is_stuff_bit(self):
97 # CAN uses NRZ encoding and bit stuffing.
98 # After 5 identical bits, a stuff bit of opposite value is added.
99 last_6_bits = self.rawbits[-6:]
100 if last_6_bits not in ([0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0]):
101 return False
102
103 # Stuff bit. Keep it in self.rawbits, but drop it from self.bits.
534ae912
UH
104 self.putx([0, ['Stuff bit: %d' % self.rawbits[-1],
105 'SB: %d' % self.rawbits[-1], 'SB']])
702fa251
UH
106 self.bits.pop() # Drop last bit.
107 return True
108
109 def is_valid_crc(self, crc_bits):
110 return True # TODO
111
112 def decode_error_frame(self, bits):
113 pass # TODO
114
115 def decode_overload_frame(self, bits):
116 pass # TODO
117
118 # Both standard and extended frames end with CRC, CRC delimiter, ACK,
119 # ACK delimiter, and EOF fields. Handle them in a common function.
120 # Returns True if the frame ended (EOF), False otherwise.
121 def decode_frame_end(self, can_rx, bitnum):
122
4b1813b4
UH
123 # Remember start of CRC sequence (see below).
124 if bitnum == (self.last_databit + 1):
125 self.ss_block = self.samplenum
126
702fa251 127 # CRC sequence (15 bits)
4b1813b4 128 elif bitnum == (self.last_databit + 15):
702fa251
UH
129 x = self.last_databit + 1
130 crc_bits = self.bits[x:x + 15 + 1]
131 self.crc = int(''.join(str(d) for d in crc_bits), 2)
534ae912
UH
132 self.putb([0, ['CRC sequence: 0x%04x' % self.crc,
133 'CRC: 0x%04x' % self.crc, 'CRC']])
702fa251 134 if not self.is_valid_crc(crc_bits):
4b1813b4 135 self.putb([0, ['CRC is invalid']])
702fa251
UH
136
137 # CRC delimiter bit (recessive)
138 elif bitnum == (self.last_databit + 16):
534ae912
UH
139 self.putx([0, ['CRC delimiter: %d' % can_rx,
140 'CRC d: %d' % can_rx, 'CRC d']])
702fa251
UH
141
142 # ACK slot bit (dominant: ACK, recessive: NACK)
143 elif bitnum == (self.last_databit + 17):
144 ack = 'ACK' if can_rx == 0 else 'NACK'
534ae912 145 self.putx([0, ['ACK slot: %s' % ack, 'ACK s: %s' % ack, 'ACK s']])
702fa251
UH
146
147 # ACK delimiter bit (recessive)
148 elif bitnum == (self.last_databit + 18):
534ae912
UH
149 self.putx([0, ['ACK delimiter: %d' % can_rx,
150 'ACK d: %d' % can_rx, 'ACK d']])
702fa251 151
4b1813b4
UH
152 # Remember start of EOF (see below).
153 elif bitnum == (self.last_databit + 19):
154 self.ss_block = self.samplenum
155
702fa251
UH
156 # End of frame (EOF), 7 recessive bits
157 elif bitnum == (self.last_databit + 25):
534ae912 158 self.putb([0, ['End of frame', 'EOF', 'E']])
702fa251
UH
159 self.reset_variables()
160 return True
161
162 return False
163
164 # Returns True if the frame ended (EOF), False otherwise.
165 def decode_standard_frame(self, can_rx, bitnum):
166
167 # Bit 14: RB0 (reserved bit)
168 # Has to be sent dominant, but receivers should accept recessive too.
169 if bitnum == 14:
534ae912
UH
170 self.putx([0, ['Reserved bit 0: %d' % can_rx,
171 'RB0: %d' % can_rx, 'RB0']])
702fa251
UH
172
173 # Bit 12: Remote transmission request (RTR) bit
174 # Data frame: dominant, remote frame: recessive
175 # Remote frames do not contain a data field.
176 rtr = 'remote' if self.bits[12] == 1 else 'data'
534ae912
UH
177 self.put12([0, ['Remote transmission request: %s frame' % rtr,
178 'RTR: %s frame' % rtr, 'RTR']])
4b1813b4
UH
179
180 # Remember start of DLC (see below).
181 elif bitnum == 15:
182 self.ss_block = self.samplenum
702fa251
UH
183
184 # Bits 15-18: Data length code (DLC), in number of bytes (0-8).
185 elif bitnum == 18:
186 self.dlc = int(''.join(str(d) for d in self.bits[15:18 + 1]), 2)
534ae912
UH
187 self.putb([0, ['Data length code: %d' % self.dlc,
188 'DLC: %d' % self.dlc, 'DLC']])
702fa251
UH
189 self.last_databit = 18 + (self.dlc * 8)
190
4b1813b4
UH
191 # Remember all databyte bits, except the very last one.
192 elif bitnum in range(19, self.last_databit):
193 self.ss_databytebits.append(self.samplenum)
194
702fa251
UH
195 # Bits 19-X: Data field (0-8 bytes, depending on DLC)
196 # The bits within a data byte are transferred MSB-first.
197 elif bitnum == self.last_databit:
4b1813b4 198 self.ss_databytebits.append(self.samplenum) # Last databyte bit.
702fa251
UH
199 for i in range(self.dlc):
200 x = 18 + (8 * i) + 1
201 b = int(''.join(str(d) for d in self.bits[x:x + 8]), 2)
4b1813b4
UH
202 ss = self.ss_databytebits[i * 8]
203 es = self.ss_databytebits[((i + 1) * 8) - 1]
534ae912
UH
204 self.putg(ss, es, [0, ['Data byte %d: 0x%02x' % (i, b),
205 'DB %d: 0x%02x' % (i, b), 'DB']])
4b1813b4 206 self.ss_databytebits = []
702fa251
UH
207
208 elif bitnum > self.last_databit:
209 return self.decode_frame_end(can_rx, bitnum)
210
211 return False
212
213 # Returns True if the frame ended (EOF), False otherwise.
214 def decode_extended_frame(self, can_rx, bitnum):
215
4b1813b4
UH
216 # Remember start of EID (see below).
217 if bitnum == 14:
218 self.ss_block = self.samplenum
219
702fa251 220 # Bits 14-31: Extended identifier (EID[17..0])
4b1813b4 221 elif bitnum == 31:
702fa251 222 self.eid = int(''.join(str(d) for d in self.bits[14:]), 2)
534ae912
UH
223 s = '%d (0x%x)' % (self.eid, self.eid)
224 self.putb([0, ['Extended Identifier: %s' % s,
225 'Extended ID: %s' % s, 'Extended ID', 'EID']])
702fa251
UH
226
227 self.fullid = self.id << 18 | self.eid
534ae912
UH
228 s = '%d (0x%x)' % (self.fullid, self.fullid)
229 self.putb([0, ['Full Identifier: %s' % s, 'Full ID: %s' % s,
230 'Full ID', 'FID']])
702fa251
UH
231
232 # Bit 12: Substitute remote request (SRR) bit
534ae912
UH
233 self.put12([0, ['Substitute remote request: %d' % self.bits[12],
234 'SRR: %d' % self.bits[12], 'SRR']])
702fa251
UH
235
236 # Bit 32: Remote transmission request (RTR) bit
237 # Data frame: dominant, remote frame: recessive
238 # Remote frames do not contain a data field.
239 if bitnum == 32:
240 rtr = 'remote' if can_rx == 1 else 'data'
534ae912
UH
241 self.putx([0, ['Remote transmission request: %s frame' % rtr,
242 'RTR: %s frame' % rtr, 'RTR']])
702fa251
UH
243
244 # Bit 33: RB1 (reserved bit)
245 elif bitnum == 33:
534ae912
UH
246 self.putx([0, ['Reserved bit 1: %d' % can_rx,
247 'RB1: %d' % can_rx, 'RB1']])
702fa251
UH
248
249 # Bit 34: RB0 (reserved bit)
250 elif bitnum == 34:
534ae912
UH
251 self.putx([0, ['Reserved bit 0: %d' % can_rx,
252 'RB0: %d' % can_rx, 'RB0']])
702fa251 253
4b1813b4
UH
254 # Remember start of DLC (see below).
255 elif bitnum == 35:
256 self.ss_block = self.samplenum
257
702fa251
UH
258 # Bits 35-38: Data length code (DLC), in number of bytes (0-8).
259 elif bitnum == 38:
260 self.dlc = int(''.join(str(d) for d in self.bits[35:38 + 1]), 2)
534ae912
UH
261 self.putb([0, ['Data length code: %d' % self.dlc,
262 'DLC: %d' % self.dlc, 'DLC']])
702fa251
UH
263 self.last_databit = 38 + (self.dlc * 8)
264
4b1813b4
UH
265 # Remember all databyte bits, except the very last one.
266 elif bitnum in range(39, self.last_databit):
267 self.ss_databytebits.append(self.samplenum)
268
702fa251
UH
269 # Bits 39-X: Data field (0-8 bytes, depending on DLC)
270 # The bits within a data byte are transferred MSB-first.
271 elif bitnum == self.last_databit:
4b1813b4 272 self.ss_databytebits.append(self.samplenum) # Last databyte bit.
702fa251
UH
273 for i in range(self.dlc):
274 x = 38 + (8 * i) + 1
275 b = int(''.join(str(d) for d in self.bits[x:x + 8]), 2)
4b1813b4
UH
276 ss = self.ss_databytebits[i * 8]
277 es = self.ss_databytebits[((i + 1) * 8) - 1]
534ae912
UH
278 self.putg(ss, es, [0, ['Data byte %d: 0x%02x' % (i, b),
279 'DB %d: 0x%02x' % (i, b), 'DB']])
4b1813b4 280 self.ss_databytebits = []
702fa251
UH
281
282 elif bitnum > self.last_databit:
283 return self.decode_frame_end(can_rx, bitnum)
284
285 return False
286
287 def handle_bit(self, can_rx):
288 self.rawbits.append(can_rx)
289 self.bits.append(can_rx)
290
291 # Get the index of the current CAN frame bit (without stuff bits).
292 bitnum = len(self.bits) - 1
293
294 # For debugging.
e20f455c
UH
295 # self.putx([0, ['Bit %d (CAN bit %d): %d' % \
296 # (self.curbit, bitnum, can_rx)]])
702fa251
UH
297
298 # If this is a stuff bit, remove it from self.bits and ignore it.
299 if self.is_stuff_bit():
300 self.curbit += 1 # Increase self.curbit (bitnum is not affected).
301 return
302
303 # Bit 0: Start of frame (SOF) bit
304 if bitnum == 0:
305 if can_rx == 0:
534ae912 306 self.putx([0, ['Start of frame', 'SOF', 'S']])
702fa251 307 else:
e20f455c 308 self.putx([1, ['Start of frame (SOF) must be a dominant bit']])
702fa251 309
4b1813b4
UH
310 # Remember start of ID (see below).
311 elif bitnum == 1:
312 self.ss_block = self.samplenum
313
702fa251
UH
314 # Bits 1-11: Identifier (ID[10..0])
315 # The bits ID[10..4] must NOT be all recessive.
316 elif bitnum == 11:
317 self.id = int(''.join(str(d) for d in self.bits[1:]), 2)
534ae912
UH
318 s = '%d (0x%x)' % (self.id, self.id),
319 self.putb([0, ['Identifier: %s' % s, 'ID: %s' % s, 'ID']])
702fa251
UH
320
321 # RTR or SRR bit, depending on frame type (gets handled later).
322 elif bitnum == 12:
4b1813b4
UH
323 # self.putx([0, ['RTR/SRR: %d' % can_rx]]) # Debug only.
324 self.ss_bit12 = self.samplenum
702fa251
UH
325
326 # Bit 13: Identifier extension (IDE) bit
327 # Standard frame: dominant, extended frame: recessive
328 elif bitnum == 13:
329 ide = self.frame_type = 'standard' if can_rx == 0 else 'extended'
534ae912
UH
330 self.putx([0, ['Identifier extension bit: %s frame' % ide,
331 'IDE: %s frame' % ide, 'IDE']])
702fa251
UH
332
333 # Bits 14-X: Frame-type dependent, passed to the resp. handlers.
334 elif bitnum >= 14:
335 if self.frame_type == 'standard':
336 done = self.decode_standard_frame(can_rx, bitnum)
337 else:
338 done = self.decode_extended_frame(can_rx, bitnum)
339
340 # The handlers return True if a frame ended (EOF).
341 if done:
342 return
343
344 # After a frame there are 3 intermission bits (recessive).
345 # After these bits, the bus is considered free.
346
347 self.curbit += 1
348
349 def decode(self, ss, es, data):
350 for (self.samplenum, pins) in data:
351
352 (can_rx,) = pins
353
354 # State machine.
355 if self.state == 'IDLE':
356 # Wait for a dominant state (logic 0) on the bus.
357 if can_rx == 1:
358 continue
359 self.sof = self.samplenum
702fa251
UH
360 self.state = 'GET BITS'
361 elif self.state == 'GET BITS':
362 # Wait until we're in the correct bit/sampling position.
363 if not self.reached_bit(self.curbit):
364 continue
365 self.handle_bit(can_rx)
366 else:
367 raise Exception("Invalid state: %s" % self.state)
368