]> sigrok.org Git - libsigrokdecode.git/blob - decoders/can/pd.py
a981b002d302cf4de5da671dd930e3c5c768008a
[libsigrokdecode.git] / decoders / can / pd.py
1 ##
2 ## This file is part of the sigrok project.
3 ##
4 ## Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
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
23 import sigrokdecode as srd
24
25 class Decoder(srd.Decoder):
26     api_version = 1
27     id = 'can'
28     name = 'CAN'
29     longname = 'Controller Area Network'
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
61     def reset_variables(self):
62         self.state = 'IDLE'
63         self.sof = self.frame_type = self.dlc = None
64         self.rawbits = [] # All bits, including stuff bits
65         self.bits = [] # Only actual CAN frame bits (no stuff bits)
66         self.curbit = 0 # Current bit of CAN frame (bit 0 == SOF)
67         self.last_databit = 999 # Positive value that bitnum+x will never match
68
69     # Return True if we reached the desired bit position, False otherwise.
70     def reached_bit(self, bitnum):
71         bitpos = int(self.sof + (self.bit_width * bitnum) + self.bitpos)
72         if self.samplenum >= bitpos:
73             return True
74         return False
75
76     def is_stuff_bit(self):
77         # CAN uses NRZ encoding and bit stuffing.
78         # After 5 identical bits, a stuff bit of opposite value is added.
79         last_6_bits = self.rawbits[-6:]
80         if last_6_bits not in ([0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0]):
81             return False
82
83         # Stuff bit. Keep it in self.rawbits, but drop it from self.bits.
84         self.put(0, 0, self.out_ann, [0, ['Stuff bit: %d' % self.rawbits[-1]]])
85         self.bits.pop() # Drop last bit.
86         return True
87
88     def is_valid_crc(self, crc_bits):
89         return True # TODO
90
91     def decode_error_frame(self, bits):
92         pass # TODO
93
94     def decode_overload_frame(self, bits):
95         pass # TODO
96
97     # Both standard and extended frames end with CRC, CRC delimiter, ACK,
98     # ACK delimiter, and EOF fields. Handle them in a common function.
99     # Returns True if the frame ended (EOF), False otherwise.
100     def decode_frame_end(self, can_rx, bitnum):
101
102         # CRC sequence (15 bits)
103         if bitnum == (self.last_databit + 15):
104             x = self.last_databit + 1
105             crc_bits = self.bits[x:x + 15 + 1]
106             self.crc = int(''.join(str(d) for d in crc_bits), 2)
107             self.put(0, 0, self.out_ann, [0, ['CRC: 0x%04x' % self.crc]])
108
109             if not self.is_valid_crc(crc_bits):
110                 self.put(0, 0, self.out_ann, [0, ['CRC is invalid']])
111
112         # CRC delimiter bit (recessive)
113         elif bitnum == (self.last_databit + 16):
114             self.put(0, 0, self.out_ann, [0, ['CRC delimiter: %d' % can_rx]])
115
116         # ACK slot bit (dominant: ACK, recessive: NACK)
117         elif bitnum == (self.last_databit + 17):
118             ack = 'ACK' if can_rx == 0 else 'NACK'
119             self.put(0, 0, self.out_ann, [0, ['ACK slot: %s' % ack]])
120
121         # ACK delimiter bit (recessive)
122         elif bitnum == (self.last_databit + 18):
123             self.put(0, 0, self.out_ann, [0, ['ACK delimiter: %d' % can_rx]])
124
125         # End of frame (EOF), 7 recessive bits
126         elif bitnum == (self.last_databit + 25):
127             self.put(0, 0, self.out_ann, [0, ['End of frame', 'EOF']])
128             self.reset_variables()
129             return True
130
131         return False
132
133     # Returns True if the frame ended (EOF), False otherwise.
134     def decode_standard_frame(self, can_rx, bitnum):
135
136         # Bit 14: RB0 (reserved bit)
137         # Has to be sent dominant, but receivers should accept recessive too.
138         if bitnum == 14:
139             self.put(0, 0, self.out_ann, [0, ['RB0: %d' % can_rx]])
140
141             # Bit 12: Remote transmission request (RTR) bit
142             # Data frame: dominant, remote frame: recessive
143             # Remote frames do not contain a data field.
144             rtr = 'remote' if self.bits[12] == 1 else 'data'
145             self.put(0, 0, self.out_ann, [0, ['RTR: %s frame' % rtr]])
146
147         # Bits 15-18: Data length code (DLC), in number of bytes (0-8).
148         elif bitnum == 18:
149             self.dlc = int(''.join(str(d) for d in self.bits[15:18 + 1]), 2)
150             self.put(0, 0, self.out_ann, [0, ['DLC: %d' % self.dlc]])
151             self.last_databit = 18 + (self.dlc * 8)
152
153         # Bits 19-X: Data field (0-8 bytes, depending on DLC)
154         # The bits within a data byte are transferred MSB-first.
155         elif bitnum == self.last_databit:
156             for i in range(self.dlc):
157                 x = 18 + (8 * i) + 1
158                 b = int(''.join(str(d) for d in self.bits[x:x + 8]), 2)
159                 self.put(0, 0, self.out_ann,
160                          [0, ['Data byte %d: 0x%02x' % (i, b)]])
161
162         elif bitnum > self.last_databit:
163             return self.decode_frame_end(can_rx, bitnum)
164
165         return False
166
167     # Returns True if the frame ended (EOF), False otherwise.
168     def decode_extended_frame(self, can_rx, bitnum):
169
170         # Bits 14-31: Extended identifier (EID[17..0])
171         if bitnum == 31:
172             self.eid = int(''.join(str(d) for d in self.bits[14:]), 2)
173             self.put(0, 0, self.out_ann,
174                      [0, ['Extended ID: %d (0x%x)' % (self.eid, self.eid)]])
175
176             self.fullid = self.id << 18 | self.eid
177             self.put(0, 0, self.out_ann,
178                      [0, ['Full ID: %d (0x%x)' % (self.fullid, self.fullid)]])
179
180             # Bit 12: Substitute remote request (SRR) bit
181             self.put(0, 0, self.out_ann, [0, ['SRR: %d' % self.bits[12]]])
182
183         # Bit 32: Remote transmission request (RTR) bit
184         # Data frame: dominant, remote frame: recessive
185         # Remote frames do not contain a data field.
186         if bitnum == 32:
187             rtr = 'remote' if can_rx == 1 else 'data'
188             self.put(0, 0, self.out_ann, [0, ['RTR: %s frame' % rtr]])
189
190         # Bit 33: RB1 (reserved bit)
191         elif bitnum == 33:
192             self.put(0, 0, self.out_ann, [0, ['RB1: %d' % can_rx]])
193
194         # Bit 34: RB0 (reserved bit)
195         elif bitnum == 34:
196             self.put(0, 0, self.out_ann, [0, ['RB0: %d' % can_rx]])
197
198         # Bits 35-38: Data length code (DLC), in number of bytes (0-8).
199         elif bitnum == 38:
200             self.dlc = int(''.join(str(d) for d in self.bits[35:38 + 1]), 2)
201             self.put(0, 0, self.out_ann, [0, ['DLC: %d' % self.dlc]])
202             self.last_databit = 38 + (self.dlc * 8)
203
204         # Bits 39-X: Data field (0-8 bytes, depending on DLC)
205         # The bits within a data byte are transferred MSB-first.
206         elif bitnum == self.last_databit:
207             for i in range(self.dlc):
208                 x = 38 + (8 * i) + 1
209                 b = int(''.join(str(d) for d in self.bits[x:x + 8]), 2)
210                 self.put(0, 0, self.out_ann,
211                          [0, ['Data byte %d: 0x%02x' % (i, b)]])
212
213         elif bitnum > self.last_databit:
214             return self.decode_frame_end(can_rx, bitnum)
215
216         return False
217
218     def handle_bit(self, can_rx):
219         self.rawbits.append(can_rx)
220         self.bits.append(can_rx)
221
222         # Get the index of the current CAN frame bit (without stuff bits).
223         bitnum = len(self.bits) - 1
224
225         # For debugging.
226         # self.put(0, 0, self.out_ann, [0, ['Bit %d (CAN bit %d): %d' % \
227         #          (self.curbit, bitnum, can_rx)]])
228
229         # If this is a stuff bit, remove it from self.bits and ignore it.
230         if self.is_stuff_bit():
231             self.curbit += 1 # Increase self.curbit (bitnum is not affected).
232             return
233
234         # Bit 0: Start of frame (SOF) bit
235         if bitnum == 0:
236             if can_rx == 0:
237                 self.put(0, 0, self.out_ann, [0, ['Start of frame', 'SOF']])
238             else:
239                 self.put(self.ss, self.es, self.out_ann,
240                          [1, ['Start of frame (SOF) must be a dominant bit']])
241
242         # Bits 1-11: Identifier (ID[10..0])
243         # The bits ID[10..4] must NOT be all recessive.
244         elif bitnum == 11:
245             self.id = int(''.join(str(d) for d in self.bits[1:]), 2)
246             self.put(0, 0, self.out_ann,
247                      [0, ['ID: %d (0x%x)' % (self.id, self.id)]])
248
249         # RTR or SRR bit, depending on frame type (gets handled later).
250         elif bitnum == 12:
251             # self.put(0, 0, self.out_ann, [0, ['RTR/SRR: %d' % can_rx]])
252             pass
253
254         # Bit 13: Identifier extension (IDE) bit
255         # Standard frame: dominant, extended frame: recessive
256         elif bitnum == 13:
257             ide = self.frame_type = 'standard' if can_rx == 0 else 'extended'
258             self.put(0, 0, self.out_ann, [0, ['IDE: %s frame' % ide]])
259
260         # Bits 14-X: Frame-type dependent, passed to the resp. handlers.
261         elif bitnum >= 14:
262             if self.frame_type == 'standard':
263                 done = self.decode_standard_frame(can_rx, bitnum)
264             else:
265                 done = self.decode_extended_frame(can_rx, bitnum)
266
267             # The handlers return True if a frame ended (EOF).
268             if done:
269                 return
270
271         # After a frame there are 3 intermission bits (recessive).
272         # After these bits, the bus is considered free.
273
274         self.curbit += 1
275
276     def decode(self, ss, es, data):
277         for (self.samplenum, pins) in data:
278
279             (can_rx,) = pins
280
281             # State machine.
282             if self.state == 'IDLE':
283                 # Wait for a dominant state (logic 0) on the bus.
284                 if can_rx == 1:
285                     continue
286                 self.sof = self.samplenum
287                 # self.put(self.sof, self.sof, self.out_ann, [0, ['SOF']])
288                 self.state = 'GET BITS'
289             elif self.state == 'GET BITS':
290                 # Wait until we're in the correct bit/sampling position.
291                 if not self.reached_bit(self.curbit):
292                     continue
293                 self.handle_bit(can_rx)
294             else:
295                 raise Exception("Invalid state: %s" % self.state)
296