i2c: also shift first address byte for 10bit slave addresses
[libsigrokdecode/gsi.git] / decoders / i2c / pd.py
bloba6c7437d77f7e156768eb6868f06f67f0caf9d09
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}'],
68 class Decoder(srd.Decoder):
69 api_version = 3
70 id = 'i2c'
71 name = 'I²C'
72 longname = 'Inter-Integrated Circuit'
73 desc = 'Two-wire, multi-master, serial bus.'
74 license = 'gplv2+'
75 inputs = ['logic']
76 outputs = ['i2c']
77 tags = ['Embedded/industrial']
78 channels = (
79 {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
80 {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
82 options = (
83 {'id': 'address_format', 'desc': 'Displayed slave address format',
84 'default': 'shifted', 'values': ('shifted', 'unshifted')},
86 annotations = (
87 ('start', 'Start condition'),
88 ('repeat-start', 'Repeat start condition'),
89 ('stop', 'Stop condition'),
90 ('ack', 'ACK'),
91 ('nack', 'NACK'),
92 ('bit', 'Data/address bit'),
93 ('address-read', 'Address read'),
94 ('address-write', 'Address write'),
95 ('data-read', 'Data read'),
96 ('data-write', 'Data write'),
97 ('warning', 'Warning'),
99 annotation_rows = (
100 ('bits', 'Bits', (5,)),
101 ('addr-data', 'Address/data', (0, 1, 2, 3, 4, 6, 7, 8, 9)),
102 ('warnings', 'Warnings', (10,)),
104 binary = (
105 ('address-read', 'Address read'),
106 ('address-write', 'Address write'),
107 ('data-read', 'Data read'),
108 ('data-write', 'Data write'),
111 def __init__(self):
112 self.reset()
114 def reset(self):
115 self.samplerate = None
116 self.is_write = None
117 self.rem_addr_bytes = None
118 self.is_repeat_start = False
119 self.state = 'FIND START'
120 self.pdu_start = None
121 self.pdu_bits = 0
122 self.data_bits = []
124 def metadata(self, key, value):
125 if key == srd.SRD_CONF_SAMPLERATE:
126 self.samplerate = value
128 def start(self):
129 self.out_python = self.register(srd.OUTPUT_PYTHON)
130 self.out_ann = self.register(srd.OUTPUT_ANN)
131 self.out_binary = self.register(srd.OUTPUT_BINARY)
132 self.out_bitrate = self.register(srd.OUTPUT_META,
133 meta=(int, 'Bitrate', 'Bitrate from Start bit to Stop bit'))
135 def putg(self, ss, es, cls, text):
136 self.put(ss, es, self.out_ann, [cls, text])
138 def putp(self, ss, es, data):
139 self.put(ss, es, self.out_python, data)
141 def putb(self, ss, es, data):
142 self.put(ss, es, self.out_binary, data)
144 def handle_start(self, pins):
145 ss, es = self.samplenum, self.samplenum
146 if self.is_repeat_start:
147 cmd = 'START REPEAT'
148 else:
149 cmd = 'START'
150 self.pdu_start = self.samplenum
151 self.pdu_bits = 0
152 self.putp(ss, es, [cmd, None])
153 cls, texts = proto[cmd][0], proto[cmd][1:]
154 self.putg(ss, es, cls, texts)
155 self.state = 'FIND ADDRESS'
156 self.is_repeat_start = True
157 self.is_write = None
158 self.rem_addr_bytes = None
159 self.data_bits.clear()
161 # Gather 8 bits of data plus the ACK/NACK bit.
162 def handle_address_or_data(self, pins):
163 scl, sda = pins
164 self.pdu_bits += 1
166 # Accumulate a byte's bits, including its start position.
167 # Accumulate individual bits and their start/end sample numbers
168 # as we see them. Get the start sample number at the time when
169 # the bit value gets sampled. Assume the start of the next bit
170 # as the end sample number of the previous bit. Guess the last
171 # bit's end sample number from the second last bit's width.
172 # (gsi: Shouldn't falling SCL be the end of the bit value?)
173 # Keep the bits in receive order (MSB first) during accumulation.
174 if self.data_bits:
175 self.data_bits[-1][2] = self.samplenum
176 self.data_bits.append([sda, self.samplenum, self.samplenum])
177 if len(self.data_bits) < 8:
178 return
179 self.bitwidth = self.data_bits[-2][2] - self.data_bits[-3][2]
180 self.data_bits[-1][2] += self.bitwidth
182 # Get the byte value. Address and data are transmitted MSB-first.
183 d = bitpack_msb(self.data_bits, 0)
184 if self.state == 'FIND ADDRESS':
185 # The READ/WRITE bit is only in the first address byte, not
186 # in data bytes. Address bit pattern 0b1111_0xxx means that
187 # this is a 10bit slave address, another byte follows. Get
188 # the R/W direction and the address bytes count from the
189 # first byte in the I2C transfer.
190 addr_byte = d
191 if self.rem_addr_bytes is None:
192 if (addr_byte & 0xf8) == 0xf0:
193 self.rem_addr_bytes = 2
194 self.slave_addr_7 = None
195 self.slave_addr_10 = addr_byte & 0x06
196 self.slave_addr_10 <<= 7
197 else:
198 self.rem_addr_bytes = 1
199 self.slave_addr_7 = addr_byte >> 1
200 self.slave_addr_10 = None
201 has_rw_bit = self.is_write is None
202 if self.is_write is None:
203 read_bit = bool(addr_byte & 1)
204 if self.options['address_format'] == 'shifted':
205 d = d >> 1
206 self.is_write = False if read_bit else True
207 else:
208 self.slave_addr_10 |= addr_byte
210 bin_class = -1
211 if self.state == 'FIND ADDRESS' and self.is_write:
212 cmd = 'ADDRESS WRITE'
213 bin_class = 1
214 elif self.state == 'FIND ADDRESS' and not self.is_write:
215 cmd = 'ADDRESS READ'
216 bin_class = 0
217 elif self.state == 'FIND DATA' and self.is_write:
218 cmd = 'DATA WRITE'
219 bin_class = 3
220 elif self.state == 'FIND DATA' and not self.is_write:
221 cmd = 'DATA READ'
222 bin_class = 2
224 ss_byte, es_byte = self.data_bits[0][1], self.data_bits[-1][2]
226 # Reverse the list of bits to LSB first order before emitting
227 # annotations and passing bits to upper layers. This may be
228 # unexpected because the protocol is MSB first, but it keeps
229 # backwards compatibility.
230 lsb_bits = self.data_bits[:]
231 lsb_bits.reverse()
232 self.putp(ss_byte, es_byte, ['BITS', lsb_bits])
233 self.putp(ss_byte, es_byte, [cmd, d])
235 self.putb(ss_byte, es_byte, [bin_class, bytes([d])])
237 for bit_value, ss_bit, es_bit in lsb_bits:
238 cls, texts = proto['BIT'][0], proto['BIT'][1:]
239 texts = [t.format(b = bit_value) for t in texts]
240 self.putg(ss_bit, es_bit, cls, texts)
242 if cmd.startswith('ADDRESS') and has_rw_bit:
243 # Assign the last bit's location to the R/W annotation.
244 # Adjust the address value's location to the left.
245 ss_bit, es_bit = self.data_bits[-1][1], self.data_bits[-1][2]
246 es_byte = self.data_bits[-2][2]
247 cls = proto[cmd][0]
248 w = ['Write', 'Wr', 'W'] if self.is_write else ['Read', 'Rd', 'R']
249 self.putg(ss_bit, es_bit, cls, w)
251 cls, texts = proto[cmd][0], proto[cmd][1:]
252 texts = [t.format(b = d) for t in texts]
253 self.putg(ss_byte, es_byte, cls, texts)
255 # Done with this packet.
256 self.data_bits.clear()
257 self.state = 'FIND ACK'
259 def get_ack(self, pins):
260 scl, sda = pins
261 # NOTE! Re-uses the last data bit's width for ACK/NAK as well.
262 # Which might be acceptable because this decoder implementation
263 # only gets to handle ACK/NAK after all DATA BITS were seen.
264 ss_bit, es_bit = self.samplenum, self.samplenum + self.bitwidth
265 cmd = 'NACK' if (sda == 1) else 'ACK'
266 self.putp(ss_bit, es_bit, [cmd, None])
267 cls, texts = proto[cmd][0], proto[cmd][1:]
268 self.putg(ss_bit, es_bit, cls, texts)
269 # Slave addresses can span one or two bytes, before data bytes
270 # follow. There can be an arbitrary number of data bytes. Stick
271 # with getting more address bytes if applicable, or enter or
272 # remain in the data phase of the transfer otherwise.
273 if self.rem_addr_bytes:
274 self.rem_addr_bytes -= 1
275 if self.rem_addr_bytes:
276 self.state = 'FIND ADDRESS'
277 else:
278 self.state = 'FIND DATA'
280 def handle_stop(self, pins):
281 # Meta bitrate
282 if self.samplerate and self.pdu_start:
283 elapsed = self.samplenum - self.pdu_start + 1
284 elapsed /= self.samplerate
285 bitrate = int(1 / elapsed * self.pdu_bits)
286 ss_meta, es_meta = self.pdu_start, self.samplenum
287 self.put(ss_meta, es_meta, self.out_bitrate, bitrate)
288 self.pdu_start = None
289 self.pdu_bits = 0
291 cmd = 'STOP'
292 ss, es = self.samplenum, self.samplenum
293 self.putp(ss, es, [cmd, None])
294 cls, texts = proto[cmd][0], proto[cmd][1:]
295 self.putg(ss, es, cls, texts)
296 self.state = 'FIND START'
297 self.is_repeat_start = False
298 self.is_write = None
299 self.data_bits.clear()
301 def decode(self):
302 while True:
303 # State machine.
304 if self.state == 'FIND START':
305 # Wait for a START condition (S): SCL = high, SDA = falling.
306 self.handle_start(self.wait({0: 'h', 1: 'f'}))
307 elif self.state == 'FIND ADDRESS':
308 # Wait for a data bit: SCL = rising.
309 self.handle_address_or_data(self.wait({0: 'r'}))
310 elif self.state == 'FIND DATA':
311 # Wait for any of the following conditions (or combinations):
312 # a) Data sampling of receiver: SCL = rising, and/or
313 # b) START condition (S): SCL = high, SDA = falling, and/or
314 # c) STOP condition (P): SCL = high, SDA = rising
315 pins = self.wait([{0: 'r'}, {0: 'h', 1: 'f'}, {0: 'h', 1: 'r'}])
317 # Check which of the condition(s) matched and handle them.
318 if self.matched[0]:
319 self.handle_address_or_data(pins)
320 elif self.matched[1]:
321 self.handle_start(pins)
322 elif self.matched[2]:
323 self.handle_stop(pins)
324 elif self.state == 'FIND ACK':
325 # Wait for a data/ack bit: SCL = rising.
326 self.get_ack(self.wait({0: 'r'}))