i2c: rephrase state machine, eliminate text matching
[libsigrokdecode/gsi.git] / decoders / i2c / pd.py
blob2259b4538654211128dc71e1bc7fd2e4228c5607
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2010-2016 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.
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.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
20 # TODO: Look into arbitration, collision detection, clock synchronisation, etc.
21 # TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
22 # TODO: Implement support for detecting various bus errors.
24 from common.srdhelper import bitpack_msb
25 import sigrokdecode as srd
27 '''
28 OUTPUT_PYTHON format:
30 Packet:
31 [<ptype>, <pdata>]
33 <ptype>:
34 - 'START' (START condition)
35 - 'START REPEAT' (Repeated START condition)
36 - 'ADDRESS READ' (Slave address, read)
37 - 'ADDRESS WRITE' (Slave address, write)
38 - 'DATA READ' (Data, read)
39 - 'DATA WRITE' (Data, write)
40 - 'STOP' (STOP condition)
41 - 'ACK' (ACK bit)
42 - 'NACK' (NACK bit)
43 - 'BITS' (<pdata>: list of data/address bits and their ss/es numbers)
45 <pdata> is the data or address byte associated with the 'ADDRESS*' and 'DATA*'
46 command. Slave addresses do not include bit 0 (the READ/WRITE indication bit).
47 For example, a slave address field could be 0x51 (instead of 0xa2).
48 For 'START', 'START REPEAT', 'STOP', 'ACK', and 'NACK' <pdata> is None.
49 For 'BITS' <pdata> is a sequence of tuples of bit values and their start and
50 stop positions, in LSB first order (although the I2C protocol is MSB first).
51 '''
53 # Meaning of table items:
54 # command -> [annotation class, annotation text in order of decreasing length]
55 proto = {
56 'START': [0, 'Start', 'S'],
57 'START REPEAT': [1, 'Start repeat', 'Sr'],
58 'STOP': [2, 'Stop', 'P'],
59 'ACK': [3, 'ACK', 'A'],
60 'NACK': [4, 'NACK', 'N'],
61 'BIT': [5, '{b:1d}'],
62 'ADDRESS READ': [6, 'Address read: {b:02X}', 'AR: {b:02X}', '{b:02X}'],
63 'ADDRESS WRITE': [7, 'Address write: {b:02X}', 'AW: {b:02X}', '{b:02X}'],
64 'DATA READ': [8, 'Data read: {b:02X}', 'DR: {b:02X}', '{b:02X}'],
65 'DATA WRITE': [9, 'Data write: {b:02X}', 'DW: {b:02X}', '{b:02X}'],
66 'WARN': [10, '{text}'],
69 class Decoder(srd.Decoder):
70 api_version = 3
71 id = 'i2c'
72 name = 'I²C'
73 longname = 'Inter-Integrated Circuit'
74 desc = 'Two-wire, multi-master, serial bus.'
75 license = 'gplv2+'
76 inputs = ['logic']
77 outputs = ['i2c']
78 tags = ['Embedded/industrial']
79 channels = (
80 {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
81 {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
83 options = (
84 {'id': 'address_format', 'desc': 'Displayed slave address format',
85 'default': 'shifted', 'values': ('shifted', 'unshifted')},
87 annotations = (
88 ('start', 'Start condition'),
89 ('repeat-start', 'Repeat start condition'),
90 ('stop', 'Stop condition'),
91 ('ack', 'ACK'),
92 ('nack', 'NACK'),
93 ('bit', 'Data/address bit'),
94 ('address-read', 'Address read'),
95 ('address-write', 'Address write'),
96 ('data-read', 'Data read'),
97 ('data-write', 'Data write'),
98 ('warning', 'Warning'),
100 annotation_rows = (
101 ('bits', 'Bits', (5,)),
102 ('addr-data', 'Address/data', (0, 1, 2, 3, 4, 6, 7, 8, 9)),
103 ('warnings', 'Warnings', (10,)),
105 binary = (
106 ('address-read', 'Address read'),
107 ('address-write', 'Address write'),
108 ('data-read', 'Data read'),
109 ('data-write', 'Data write'),
112 def __init__(self):
113 self.reset()
115 def reset(self):
116 self.samplerate = None
117 self.is_write = None
118 self.rem_addr_bytes = None
119 self.slave_addr_7 = None
120 self.slave_addr_10 = None
121 self.is_repeat_start = False
122 self.pdu_start = None
123 self.pdu_bits = 0
124 self.data_bits = []
125 self.bitwidth = 0
127 def metadata(self, key, value):
128 if key == srd.SRD_CONF_SAMPLERATE:
129 self.samplerate = value
131 def start(self):
132 self.out_python = self.register(srd.OUTPUT_PYTHON)
133 self.out_ann = self.register(srd.OUTPUT_ANN)
134 self.out_binary = self.register(srd.OUTPUT_BINARY)
135 self.out_bitrate = self.register(srd.OUTPUT_META,
136 meta=(int, 'Bitrate', 'Bitrate from Start bit to Stop bit'))
138 def putg(self, ss, es, cls, text):
139 self.put(ss, es, self.out_ann, [cls, text])
141 def putp(self, ss, es, data):
142 self.put(ss, es, self.out_python, data)
144 def putb(self, ss, es, data):
145 self.put(ss, es, self.out_binary, data)
147 def _wants_start(self):
148 # Check whether START is required (to sync to the input stream).
149 return self.pdu_start is None
151 def _collects_address(self):
152 # Check whether the transfer still is in the address phase (is
153 # still collecting address and r/w details, or has not started
154 # collecting it).
155 return self.rem_addr_bytes is None or self.rem_addr_bytes != 0
157 def _collects_byte(self):
158 # Check whether bits of a byte are being collected. Outside of
159 # the data byte, the bit is the ACK/NAK slot.
160 return self.data_bits is None or len(self.data_bits) < 8
162 def handle_start(self, ss, es):
163 if self.is_repeat_start:
164 cmd = 'START REPEAT'
165 else:
166 cmd = 'START'
167 self.pdu_start = ss
168 self.pdu_bits = 0
169 self.putp(ss, es, [cmd, None])
170 cls, texts = proto[cmd][0], proto[cmd][1:]
171 self.putg(ss, es, cls, texts)
172 self.is_repeat_start = True
173 self.is_write = None
174 self.slave_addr_7 = None
175 self.slave_addr_10 = None
176 self.rem_addr_bytes = None
177 self.data_bits.clear()
178 self.bitwidth = 0
180 # Gather 8 bits of data plus the ACK/NACK bit.
181 def handle_address_or_data(self, ss, es, value):
182 self.pdu_bits += 1
184 # Accumulate a byte's bits, including its start position.
185 # Accumulate individual bits and their start/end sample numbers
186 # as we see them. Get the start sample number at the time when
187 # the bit value gets sampled. Assume the start of the next bit
188 # as the end sample number of the previous bit. Guess the last
189 # bit's end sample number from the second last bit's width.
190 # Keep the bits in receive order (MSB first) during accumulation.
191 # (gsi: Strictly speaking falling SCL would be the end of the
192 # bit value's validity. That'd break compatibility though.)
193 if self.data_bits:
194 self.data_bits[-1][2] = ss
195 self.data_bits.append([value, ss, es])
196 if len(self.data_bits) < 8:
197 return
198 self.bitwidth = self.data_bits[-2][2] - self.data_bits[-3][2]
199 self.data_bits[-1][2] = self.data_bits[-1][1] + self.bitwidth
201 # Get the byte value. Address and data are transmitted MSB-first.
202 d = bitpack_msb(self.data_bits, 0)
203 ss_byte, es_byte = self.data_bits[0][1], self.data_bits[-1][2]
205 # Process the address bytes at the start of a transfer. The
206 # first byte will carry the R/W bit, and all of the 7bit address
207 # or part of a 10bit address. Bit pattern 0b11110xxx signals
208 # that another byte follows which carries the remaining bits of
209 # a 10bit slave address.
210 is_address = self._collects_address()
211 if is_address:
212 addr_byte = d
213 if self.rem_addr_bytes is None:
214 if (addr_byte & 0xf8) == 0xf0:
215 self.rem_addr_bytes = 2
216 self.slave_addr_7 = None
217 self.slave_addr_10 = addr_byte & 0x06
218 self.slave_addr_10 <<= 7
219 else:
220 self.rem_addr_bytes = 1
221 self.slave_addr_7 = addr_byte >> 1
222 self.slave_addr_10 = None
223 has_rw_bit = self.is_write is None
224 if self.is_write is None:
225 read_bit = bool(addr_byte & 1)
226 if self.options['address_format'] == 'shifted':
227 d >>= 1
228 self.is_write = False if read_bit else True
229 elif self.slave_addr_10 is not None:
230 self.slave_addr_10 |= addr_byte
231 else:
232 cls, texts = proto['WARN'][0], proto['WARN'][1:]
233 msg = 'Unhandled address byte'
234 texts = [t.format(text = msg) for t in texts]
235 self.putg(ss_byte, es_byte, cls, texts)
236 is_write = self.is_write
237 is_seven = self.slave_addr_7 is not None
239 # Determine annotation classes depending on whether the byte is
240 # an address or payload data, and whether it's written or read.
241 bin_class = -1
242 if is_address and is_write:
243 cmd = 'ADDRESS WRITE'
244 bin_class = 1
245 elif is_address and not is_write:
246 cmd = 'ADDRESS READ'
247 bin_class = 0
248 elif not is_address and is_write:
249 cmd = 'DATA WRITE'
250 bin_class = 3
251 elif not is_address and not is_write:
252 cmd = 'DATA READ'
253 bin_class = 2
255 # Reverse the list of bits to LSB first order before emitting
256 # annotations and passing bits to upper layers. This may be
257 # unexpected because the protocol is MSB first, but it keeps
258 # backwards compatibility.
259 lsb_bits = self.data_bits[:]
260 lsb_bits.reverse()
261 self.putp(ss_byte, es_byte, ['BITS', lsb_bits])
262 self.putp(ss_byte, es_byte, [cmd, d])
264 self.putb(ss_byte, es_byte, [bin_class, bytes([d])])
266 for bit_value, ss_bit, es_bit in lsb_bits:
267 cls, texts = proto['BIT'][0], proto['BIT'][1:]
268 texts = [t.format(b = bit_value) for t in texts]
269 self.putg(ss_bit, es_bit, cls, texts)
271 if is_address and has_rw_bit:
272 # Assign the last bit's location to the R/W annotation.
273 # Adjust the address value's location to the left.
274 ss_bit, es_bit = self.data_bits[-1][1], self.data_bits[-1][2]
275 es_byte = self.data_bits[-2][2]
276 cls = proto[cmd][0]
277 w = ['Write', 'Wr', 'W'] if self.is_write else ['Read', 'Rd', 'R']
278 self.putg(ss_bit, es_bit, cls, w)
280 cls, texts = proto[cmd][0], proto[cmd][1:]
281 texts = [t.format(b = d) for t in texts]
282 self.putg(ss_byte, es_byte, cls, texts)
284 def get_ack(self, ss, es, value):
285 ss_bit, es_bit = ss, es
286 cmd = 'ACK' if value == 0 else 'NACK'
287 self.putp(ss_bit, es_bit, [cmd, None])
288 cls, texts = proto[cmd][0], proto[cmd][1:]
289 self.putg(ss_bit, es_bit, cls, texts)
290 # Slave addresses can span one or two bytes, before data bytes
291 # follow. There can be an arbitrary number of data bytes. Stick
292 # with getting more address bytes if applicable, or enter or
293 # remain in the data phase of the transfer otherwise.
294 if self.rem_addr_bytes:
295 self.rem_addr_bytes -= 1
296 self.data_bits.clear()
298 def handle_stop(self, ss, es):
299 # Meta bitrate
300 if self.samplerate and self.pdu_start:
301 elapsed = es - self.pdu_start + 1
302 elapsed /= self.samplerate
303 bitrate = int(1 / elapsed * self.pdu_bits)
304 ss_meta, es_meta = self.pdu_start, es
305 self.put(ss_meta, es_meta, self.out_bitrate, bitrate)
306 self.pdu_start = None
307 self.pdu_bits = 0
309 cmd = 'STOP'
310 self.putp(ss, es, [cmd, None])
311 cls, texts = proto[cmd][0], proto[cmd][1:]
312 self.putg(ss, es, cls, texts)
313 self.is_repeat_start = False
314 self.is_write = None
315 self.data_bits.clear()
317 def decode(self):
318 # Check for several bus conditions. Determine sample numbers
319 # here and pass ss, es, and bit values to handling routines.
320 while True:
321 # State machine.
322 # BEWARE! This implementation expects to see valid traffic,
323 # is rather picky in which phase which symbols get handled.
324 # This attempts to support severely undersampled captures,
325 # which a previous implementation happened to read instead
326 # of rejecting the inadequate input data.
327 # NOTE that handling bits at the start of their validity,
328 # and assuming that they remain valid until the next bit
329 # starts, is also done for backwards compatibility.
330 if self._wants_start():
331 # Wait for a START condition (S): SCL = high, SDA = falling.
332 pins = self.wait({0: 'h', 1: 'f'})
333 ss, es = self.samplenum, self.samplenum
334 self.handle_start(ss, es)
335 elif self._collects_address() and self._collects_byte():
336 # Wait for a data bit: SCL = rising.
337 pins = self.wait({0: 'r'})
338 _, sda = pins
339 ss, es = self.samplenum, self.samplenum + self.bitwidth
340 self.handle_address_or_data(ss, es, sda)
341 elif self._collects_byte():
342 # Wait for any of the following conditions (or combinations):
343 # a) Data sampling of receiver: SCL = rising, and/or
344 # b) START condition (S): SCL = high, SDA = falling, and/or
345 # c) STOP condition (P): SCL = high, SDA = rising
346 pins = self.wait([{0: 'r'}, {0: 'h', 1: 'f'}, {0: 'h', 1: 'r'}])
348 # Check which of the condition(s) matched and handle them.
349 if self.matched[0]:
350 _, sda = pins
351 ss, es = self.samplenum, self.samplenum + self.bitwidth
352 self.handle_address_or_data(ss, es, sda)
353 elif self.matched[1]:
354 ss, es = self.samplenum, self.samplenum
355 self.handle_start(ss, es)
356 elif self.matched[2]:
357 ss, es = self.samplenum, self.samplenum
358 self.handle_stop(ss, es)
359 else:
360 # Wait for a data/ack bit: SCL = rising.
361 pins = self.wait({0: 'r'})
362 _, sda = pins
363 ss, es = self.samplenum, self.samplenum + self.bitwidth
364 self.get_ack(ss, es, sda)