]>
Commit | Line | Data |
---|---|---|
1 | ## | |
2 | ## This file is part of the libsigrokdecode project. | |
3 | ## | |
4 | ## Copyright (C) 2012-2013 Uwe Hermann <uwe@hermann-uwe.de> | |
5 | ## Copyright (C) 2019 Stephan Thiele <stephan.thiele@mailbox.org> | |
6 | ## | |
7 | ## This program is free software; you can redistribute it and/or modify | |
8 | ## it under the terms of the GNU General Public License as published by | |
9 | ## the Free Software Foundation; either version 2 of the License, or | |
10 | ## (at your option) any later version. | |
11 | ## | |
12 | ## This program is distributed in the hope that it will be useful, | |
13 | ## but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 | ## GNU General Public License for more details. | |
16 | ## | |
17 | ## You should have received a copy of the GNU General Public License | |
18 | ## along with this program; if not, see <http://www.gnu.org/licenses/>. | |
19 | ## | |
20 | ||
21 | import sigrokdecode as srd | |
22 | ||
23 | class SamplerateError(Exception): | |
24 | pass | |
25 | ||
26 | class Decoder(srd.Decoder): | |
27 | api_version = 3 | |
28 | id = 'can' | |
29 | name = 'CAN' | |
30 | longname = 'Controller Area Network' | |
31 | desc = 'Field bus protocol for distributed realtime control.' | |
32 | license = 'gplv2+' | |
33 | inputs = ['logic'] | |
34 | outputs = [] | |
35 | tags = ['Automotive'] | |
36 | channels = ( | |
37 | {'id': 'can_rx', 'name': 'CAN RX', 'desc': 'CAN bus line'}, | |
38 | ) | |
39 | options = ( | |
40 | {'id': 'bitrate', 'desc': 'Bitrate (bits/s)', 'default': 1000000}, | |
41 | {'id': 'sample_point', 'desc': 'Sample point (%)', 'default': 70.0}, | |
42 | ) | |
43 | annotations = ( | |
44 | ('data', 'CAN payload data'), | |
45 | ('sof', 'Start of frame'), | |
46 | ('eof', 'End of frame'), | |
47 | ('id', 'Identifier'), | |
48 | ('ext-id', 'Extended identifier'), | |
49 | ('full-id', 'Full identifier'), | |
50 | ('ide', 'Identifier extension bit'), | |
51 | ('reserved-bit', 'Reserved bit 0 and 1'), | |
52 | ('rtr', 'Remote transmission request'), | |
53 | ('srr', 'Substitute remote request'), | |
54 | ('dlc', 'Data length count'), | |
55 | ('crc-sequence', 'CRC sequence'), | |
56 | ('crc-delimiter', 'CRC delimiter'), | |
57 | ('ack-slot', 'ACK slot'), | |
58 | ('ack-delimiter', 'ACK delimiter'), | |
59 | ('stuff-bit', 'Stuff bit'), | |
60 | ('warnings', 'Human-readable warnings'), | |
61 | ('bit', 'Bit'), | |
62 | ) | |
63 | annotation_rows = ( | |
64 | ('bits', 'Bits', (15, 17)), | |
65 | ('fields', 'Fields', tuple(range(15))), | |
66 | ('warnings', 'Warnings', (16,)), | |
67 | ) | |
68 | fd = False | |
69 | ||
70 | def __init__(self): | |
71 | self.reset() | |
72 | ||
73 | def dlc2len(self, dlc): | |
74 | return [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64][dlc] | |
75 | ||
76 | def reset(self): | |
77 | self.samplerate = None | |
78 | self.reset_variables() | |
79 | ||
80 | def start(self): | |
81 | self.out_ann = self.register(srd.OUTPUT_ANN) | |
82 | ||
83 | def metadata(self, key, value): | |
84 | if key == srd.SRD_CONF_SAMPLERATE: | |
85 | self.samplerate = value | |
86 | self.bit_width = float(self.samplerate) / float(self.options['bitrate']) | |
87 | self.sample_point = (self.bit_width / 100.0) * self.options['sample_point'] | |
88 | ||
89 | # Generic helper for CAN bit annotations. | |
90 | def putg(self, ss, es, data): | |
91 | left, right = int(self.sample_point), int(self.bit_width - self.sample_point) | |
92 | self.put(ss - left, es + right, self.out_ann, data) | |
93 | ||
94 | # Single-CAN-bit annotation using the current samplenum. | |
95 | def putx(self, data): | |
96 | self.putg(self.samplenum, self.samplenum, data) | |
97 | ||
98 | # Single-CAN-bit annotation using the samplenum of CAN bit 12. | |
99 | def put12(self, data): | |
100 | self.putg(self.ss_bit12, self.ss_bit12, data) | |
101 | ||
102 | # Multi-CAN-bit annotation from self.ss_block to current samplenum. | |
103 | def putb(self, data): | |
104 | self.putg(self.ss_block, self.samplenum, data) | |
105 | ||
106 | def reset_variables(self): | |
107 | self.state = 'IDLE' | |
108 | self.sof = self.frame_type = self.dlc = None | |
109 | self.rawbits = [] # All bits, including stuff bits | |
110 | self.bits = [] # Only actual CAN frame bits (no stuff bits) | |
111 | self.curbit = 0 # Current bit of CAN frame (bit 0 == SOF) | |
112 | self.last_databit = 999 # Positive value that bitnum+x will never match | |
113 | self.ss_block = None | |
114 | self.ss_bit12 = None | |
115 | self.ss_databytebits = [] | |
116 | ||
117 | # Poor man's clock synchronization. Use signal edges which change to | |
118 | # dominant state in rather simple ways. This naive approach is neither | |
119 | # aware of the SYNC phase's width nor the specific location of the edge, | |
120 | # but improves the decoder's reliability when the input signal's bitrate | |
121 | # does not exactly match the nominal rate. | |
122 | def dom_edge_seen(self, force = False): | |
123 | self.dom_edge_snum = self.samplenum | |
124 | self.dom_edge_bcount = self.curbit | |
125 | ||
126 | def bit_sampled(self): | |
127 | # EMPTY | |
128 | pass | |
129 | ||
130 | # Determine the position of the next desired bit's sample point. | |
131 | def get_sample_point(self, bitnum): | |
132 | samplenum = self.dom_edge_snum | |
133 | samplenum += int(self.bit_width * (bitnum - self.dom_edge_bcount)) | |
134 | samplenum += int(self.sample_point) | |
135 | return samplenum | |
136 | ||
137 | def is_stuff_bit(self): | |
138 | # CAN uses NRZ encoding and bit stuffing. | |
139 | # After 5 identical bits, a stuff bit of opposite value is added. | |
140 | # But not in the CRC delimiter, ACK, and end of frame fields. | |
141 | if len(self.bits) > self.last_databit + 17: | |
142 | return False | |
143 | last_6_bits = self.rawbits[-6:] | |
144 | if last_6_bits not in ([0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0]): | |
145 | return False | |
146 | ||
147 | # Stuff bit. Keep it in self.rawbits, but drop it from self.bits. | |
148 | self.bits.pop() # Drop last bit. | |
149 | return True | |
150 | ||
151 | def is_valid_crc(self, crc_bits): | |
152 | return True # TODO | |
153 | ||
154 | def decode_error_frame(self, bits): | |
155 | pass # TODO | |
156 | ||
157 | def decode_overload_frame(self, bits): | |
158 | pass # TODO | |
159 | ||
160 | # Both standard and extended frames end with CRC, CRC delimiter, ACK, | |
161 | # ACK delimiter, and EOF fields. Handle them in a common function. | |
162 | # Returns True if the frame ended (EOF), False otherwise. | |
163 | def decode_frame_end(self, can_rx, bitnum): | |
164 | ||
165 | # Remember start of CRC sequence (see below). | |
166 | if bitnum == (self.last_databit + 1): | |
167 | self.ss_block = self.samplenum | |
168 | ||
169 | if self.fd: | |
170 | if self.dlc2len(self.dlc) < 16: | |
171 | self.crc_len = 27 # 17 + SBC + stuff bits | |
172 | else: | |
173 | self.crc_len = 32 # 21 + SBC + stuff bits | |
174 | else: | |
175 | self.crc_len = 15 | |
176 | ||
177 | # CRC sequence (15 bits, 17 bits or 21 bits) | |
178 | elif bitnum == (self.last_databit + self.crc_len): | |
179 | if self.fd: | |
180 | if self.dlc2len(self.dlc) < 16: | |
181 | crc_type = "CRC-17" | |
182 | else: | |
183 | crc_type = "CRC-21" | |
184 | else: | |
185 | crc_type = "CRC-15" | |
186 | ||
187 | x = self.last_databit + 1 | |
188 | crc_bits = self.bits[x:x + self.crc_len + 1] | |
189 | self.crc = int(''.join(str(d) for d in crc_bits), 2) | |
190 | self.putb([11, ['%s sequence: 0x%04x' % (crc_type, self.crc), | |
191 | '%s: 0x%04x' % (crc_type, self.crc), '%s' % crc_type]]) | |
192 | if not self.is_valid_crc(crc_bits): | |
193 | self.putb([16, ['CRC is invalid']]) | |
194 | ||
195 | # CRC delimiter bit (recessive) | |
196 | elif bitnum == (self.last_databit + self.crc_len + 1): | |
197 | self.putx([12, ['CRC delimiter: %d' % can_rx, | |
198 | 'CRC d: %d' % can_rx, 'CRC d']]) | |
199 | if can_rx != 1: | |
200 | self.putx([16, ['CRC delimiter must be a recessive bit']]) | |
201 | ||
202 | # ACK slot bit (dominant: ACK, recessive: NACK) | |
203 | elif bitnum == (self.last_databit + self.crc_len + 2): | |
204 | ack = 'ACK' if can_rx == 0 else 'NACK' | |
205 | self.putx([13, ['ACK slot: %s' % ack, 'ACK s: %s' % ack, 'ACK s']]) | |
206 | ||
207 | # ACK delimiter bit (recessive) | |
208 | elif bitnum == (self.last_databit + self.crc_len + 3): | |
209 | self.putx([14, ['ACK delimiter: %d' % can_rx, | |
210 | 'ACK d: %d' % can_rx, 'ACK d']]) | |
211 | if can_rx != 1: | |
212 | self.putx([16, ['ACK delimiter must be a recessive bit']]) | |
213 | ||
214 | # Remember start of EOF (see below). | |
215 | elif bitnum == (self.last_databit + self.crc_len + 4): | |
216 | self.ss_block = self.samplenum | |
217 | ||
218 | # End of frame (EOF), 7 recessive bits | |
219 | elif bitnum == (self.last_databit + self.crc_len + 11): | |
220 | self.putb([2, ['End of frame', 'EOF', 'E']]) | |
221 | if self.rawbits[-7:] != [1, 1, 1, 1, 1, 1, 1]: | |
222 | self.putb([16, ['End of frame (EOF) must be 7 recessive bits']]) | |
223 | self.reset_variables() | |
224 | return True | |
225 | ||
226 | return False | |
227 | ||
228 | # Returns True if the frame ended (EOF), False otherwise. | |
229 | def decode_standard_frame(self, can_rx, bitnum): | |
230 | ||
231 | # Bit 14: FDF (Flexible Data Format) | |
232 | # Has to be sent dominant when FD frame, has to be sent recessive when classic CAN frame. | |
233 | if bitnum == 14: | |
234 | self.fd = True if can_rx else False | |
235 | ||
236 | self.putx([7, ['Flexible Data Format: %d' % can_rx, | |
237 | 'FDF: %d' % can_rx, | |
238 | 'FDF']]) | |
239 | ||
240 | # SRR Substitute Remote Request | |
241 | if self.fd: | |
242 | self.put12([8, ['Substitute Remote Request', 'SRR']]) | |
243 | self.dlc_start = 18 | |
244 | else: | |
245 | # Bit 12: Remote transmission request (RTR) bit | |
246 | # Data frame: dominant, remote frame: recessive | |
247 | # Remote frames do not contain a data field. | |
248 | rtr = 'remote' if self.bits[12] == 1 else 'data' | |
249 | self.put12([8, ['Remote transmission request: %s frame' % rtr, | |
250 | 'RTR: %s frame' % rtr, 'RTR']]) | |
251 | self.dlc_start = 15 | |
252 | ||
253 | # TODO: add Res, BRS and ESI bits when FD format: | |
254 | if bitnum == 15: | |
255 | if self.fd: | |
256 | self.putx([7, ['Reserved: %d' % can_rx, 'R0: %d' % can_rx, 'R0']]) | |
257 | ||
258 | if bitnum == 16: | |
259 | if self.fd: | |
260 | self.putx([7, ['Bit rate switch: %d' % can_rx, 'BRS: %d' % can_rx, 'BRS']]) | |
261 | ||
262 | if bitnum == 17: | |
263 | if self.fd: | |
264 | self.putx([7, ['Error state indicator: %d' % can_rx, 'ESI: %d' % can_rx, 'ESI']]) | |
265 | ||
266 | # Remember start of DLC (see below). | |
267 | elif bitnum == self.dlc_start: | |
268 | self.ss_block = self.samplenum | |
269 | ||
270 | # Bits 15-18: Data length code (DLC), in number of bytes (0-8). | |
271 | elif bitnum == self.dlc_start + 3: | |
272 | self.dlc = int(''.join(str(d) for d in self.bits[self.dlc_start:self.dlc_start + 4]), 2) | |
273 | self.putb([10, ['Data length code: %d (%d Bytes)' % (self.dlc, self.dlc2len(self.dlc)), | |
274 | 'DLC: %d (%d B)' % (self.dlc, self.dlc2len(self.dlc)), 'DLC']]) | |
275 | self.last_databit = self.dlc_start + 3 + (self.dlc2len(self.dlc) * 8) | |
276 | ||
277 | # Remember all databyte bits, except the very last one. | |
278 | elif bitnum in range(self.dlc_start + 4, self.last_databit): | |
279 | self.ss_databytebits.append(self.samplenum) | |
280 | ||
281 | # Bits 19-X: Data field (0-8 bytes, depending on DLC) | |
282 | # The bits within a data byte are transferred MSB-first. | |
283 | elif bitnum == self.last_databit: | |
284 | self.ss_databytebits.append(self.samplenum) # Last databyte bit. | |
285 | for i in range(self.dlc2len(self.dlc)): | |
286 | x = self.dlc_start + 4 + (8 * i) | |
287 | b = int(''.join(str(d) for d in self.bits[x:x + 8]), 2) | |
288 | ss = self.ss_databytebits[i * 8] | |
289 | es = self.ss_databytebits[((i + 1) * 8) - 1] | |
290 | self.putg(ss, es, [0, ['Data byte %d: 0x%02x' % (i, b), | |
291 | 'DB %d: 0x%02x' % (i, b), 'DB']]) | |
292 | self.ss_databytebits = [] | |
293 | ||
294 | elif bitnum > self.last_databit: | |
295 | return self.decode_frame_end(can_rx, bitnum) | |
296 | ||
297 | return False | |
298 | ||
299 | # Returns True if the frame ended (EOF), False otherwise. | |
300 | def decode_extended_frame(self, can_rx, bitnum): | |
301 | ||
302 | # Remember start of EID (see below). | |
303 | if bitnum == 14: | |
304 | self.ss_block = self.samplenum | |
305 | ||
306 | # Bits 14-31: Extended identifier (EID[17..0]) | |
307 | elif bitnum == 31: | |
308 | self.eid = int(''.join(str(d) for d in self.bits[14:]), 2) | |
309 | s = '%d (0x%x)' % (self.eid, self.eid) | |
310 | self.putb([4, ['Extended Identifier: %s' % s, | |
311 | 'Extended ID: %s' % s, 'Extended ID', 'EID']]) | |
312 | ||
313 | self.fullid = self.id << 18 | self.eid | |
314 | s = '%d (0x%x)' % (self.fullid, self.fullid) | |
315 | self.putb([5, ['Full Identifier: %s' % s, 'Full ID: %s' % s, | |
316 | 'Full ID', 'FID']]) | |
317 | ||
318 | # Bit 12: Substitute remote request (SRR) bit | |
319 | self.put12([9, ['Substitute remote request: %d' % self.bits[12], | |
320 | 'SRR: %d' % self.bits[12], 'SRR']]) | |
321 | ||
322 | # Bit 32: Remote transmission request (RTR) bit | |
323 | # Data frame: dominant, remote frame: recessive | |
324 | # Remote frames do not contain a data field. | |
325 | if bitnum == 32: | |
326 | rtr = 'remote' if can_rx == 1 else 'data' | |
327 | self.putx([8, ['Remote transmission request: %s frame' % rtr, | |
328 | 'RTR: %s frame' % rtr, 'RTR']]) | |
329 | ||
330 | # Bit 33: RB1 (reserved bit) | |
331 | elif bitnum == 33: | |
332 | self.putx([7, ['Reserved bit 1: %d' % can_rx, | |
333 | 'RB1: %d' % can_rx, 'RB1']]) | |
334 | ||
335 | # Bit 34: RB0 (reserved bit) | |
336 | elif bitnum == 34: | |
337 | self.putx([7, ['Reserved bit 0: %d' % can_rx, | |
338 | 'RB0: %d' % can_rx, 'RB0']]) | |
339 | ||
340 | # Remember start of DLC (see below). | |
341 | elif bitnum == 35: | |
342 | self.ss_block = self.samplenum | |
343 | ||
344 | # Bits 35-38: Data length code (DLC), in number of bytes (0-8). | |
345 | elif bitnum == 38: | |
346 | self.dlc = int(''.join(str(d) for d in self.bits[35:38 + 1]), 2) | |
347 | self.putb([10, ['Data length code: %d (%d Bytes)' % (self.dlc, self.dlc2len(self.dlc)), | |
348 | 'DLC: %d (%d B)' % (self.dlc, self.dlc2len(self.dlc)), 'DLC']]) | |
349 | self.last_databit = 38 + (self.dlc2len(self.dlc) * 8) | |
350 | ||
351 | # Remember all databyte bits, except the very last one. | |
352 | elif bitnum in range(39, self.last_databit): | |
353 | self.ss_databytebits.append(self.samplenum) | |
354 | ||
355 | # Bits 39-X: Data field (0-8 bytes, depending on DLC) | |
356 | # The bits within a data byte are transferred MSB-first. | |
357 | elif bitnum == self.last_databit: | |
358 | self.ss_databytebits.append(self.samplenum) # Last databyte bit. | |
359 | for i in range(self.dlc2len(self.dlc)): | |
360 | x = 38 + (8 * i) + 1 | |
361 | b = int(''.join(str(d) for d in self.bits[x:x + 8]), 2) | |
362 | ss = self.ss_databytebits[i * 8] | |
363 | es = self.ss_databytebits[((i + 1) * 8) - 1] | |
364 | self.putg(ss, es, [0, ['Data byte %d: 0x%02x' % (i, b), | |
365 | 'DB %d: 0x%02x' % (i, b), 'DB']]) | |
366 | self.ss_databytebits = [] | |
367 | ||
368 | elif bitnum > self.last_databit: | |
369 | return self.decode_frame_end(can_rx, bitnum) | |
370 | ||
371 | return False | |
372 | ||
373 | def handle_bit(self, can_rx): | |
374 | self.rawbits.append(can_rx) | |
375 | self.bits.append(can_rx) | |
376 | ||
377 | # Get the index of the current CAN frame bit (without stuff bits). | |
378 | bitnum = len(self.bits) - 1 | |
379 | ||
380 | # If this is a stuff bit, remove it from self.bits and ignore it. | |
381 | if self.is_stuff_bit(): | |
382 | self.putx([15, [str(can_rx)]]) | |
383 | self.curbit += 1 # Increase self.curbit (bitnum is not affected). | |
384 | return | |
385 | else: | |
386 | self.putx([17, [str(can_rx)]]) | |
387 | ||
388 | # Bit 0: Start of frame (SOF) bit | |
389 | if bitnum == 0: | |
390 | self.putx([1, ['Start of frame', 'SOF', 'S']]) | |
391 | if can_rx != 0: | |
392 | self.putx([16, ['Start of frame (SOF) must be a dominant bit']]) | |
393 | ||
394 | # Remember start of ID (see below). | |
395 | elif bitnum == 1: | |
396 | self.ss_block = self.samplenum | |
397 | ||
398 | # Bits 1-11: Identifier (ID[10..0]) | |
399 | # The bits ID[10..4] must NOT be all recessive. | |
400 | elif bitnum == 11: | |
401 | self.id = int(''.join(str(d) for d in self.bits[1:]), 2) | |
402 | s = '%d (0x%x)' % (self.id, self.id), | |
403 | self.putb([3, ['Identifier: %s' % s, 'ID: %s' % s, 'ID']]) | |
404 | if (self.id & 0x7f0) == 0x7f0: | |
405 | self.putb([16, ['Identifier bits 10..4 must not be all recessive']]) | |
406 | ||
407 | # RTR or SRR bit, depending on frame type (gets handled later). | |
408 | elif bitnum == 12: | |
409 | # self.putx([0, ['RTR/SRR: %d' % can_rx]]) # Debug only. | |
410 | self.ss_bit12 = self.samplenum | |
411 | ||
412 | # Bit 13: Identifier extension (IDE) bit | |
413 | # Standard frame: dominant, extended frame: recessive | |
414 | elif bitnum == 13: | |
415 | ide = self.frame_type = 'standard' if can_rx == 0 else 'extended' | |
416 | self.putx([6, ['Identifier extension bit: %s frame' % ide, | |
417 | 'IDE: %s frame' % ide, 'IDE']]) | |
418 | ||
419 | # Bits 14-X: Frame-type dependent, passed to the resp. handlers. | |
420 | elif bitnum >= 14: | |
421 | if self.frame_type == 'standard': | |
422 | done = self.decode_standard_frame(can_rx, bitnum) | |
423 | else: | |
424 | done = self.decode_extended_frame(can_rx, bitnum) | |
425 | ||
426 | # The handlers return True if a frame ended (EOF). | |
427 | if done: | |
428 | return | |
429 | ||
430 | # After a frame there are 3 intermission bits (recessive). | |
431 | # After these bits, the bus is considered free. | |
432 | ||
433 | self.curbit += 1 | |
434 | ||
435 | def decode(self): | |
436 | if not self.samplerate: | |
437 | raise SamplerateError('Cannot decode without samplerate.') | |
438 | ||
439 | while True: | |
440 | # State machine. | |
441 | if self.state == 'IDLE': | |
442 | # Wait for a dominant state (logic 0) on the bus. | |
443 | (can_rx,) = self.wait({0: 'l'}) | |
444 | self.sof = self.samplenum | |
445 | self.dom_edge_seen(force = True) | |
446 | self.state = 'GET BITS' | |
447 | elif self.state == 'GET BITS': | |
448 | # Wait until we're in the correct bit/sampling position. | |
449 | pos = self.get_sample_point(self.curbit) | |
450 | (can_rx,) = self.wait([{'skip': pos - self.samplenum}, {0: 'f'}]) | |
451 | if self.matched[1]: | |
452 | self.dom_edge_seen() | |
453 | if self.matched[0]: | |
454 | self.handle_bit(can_rx) | |
455 | self.bit_sampled() |