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