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