]> sigrok.org Git - libsigrokdecode.git/blame - decoders/i2c/pd.py
i2c: concentrate sample number and value getting in main loop
[libsigrokdecode.git] / decoders / i2c / pd.py
CommitLineData
0588ed70 1##
50bd5d25 2## This file is part of the libsigrokdecode project.
0588ed70 3##
592f355b 4## Copyright (C) 2010-2016 Uwe Hermann <uwe@hermann-uwe.de>
0588ed70
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
4539e9ca 17## along with this program; if not, see <http://www.gnu.org/licenses/>.
0588ed70
UH
18##
19
0588ed70 20# TODO: Look into arbitration, collision detection, clock synchronisation, etc.
0588ed70
UH
21# TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
22# TODO: Implement support for detecting various bus errors.
23fb2e12 23
647aba6a 24from common.srdhelper import bitpack_msb
677d597b 25import sigrokdecode as srd
b2c19614 26
f1428c4c 27'''
c515eed7 28OUTPUT_PYTHON format:
f1428c4c 29
bf69977d
UH
30Packet:
31[<ptype>, <pdata>]
f1428c4c 32
bf69977d 33<ptype>:
f1428c4c
UH
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)
bf69977d 43 - 'BITS' (<pdata>: list of data/address bits and their ss/es numbers)
f1428c4c 44
bf69977d 45<pdata> is the data or address byte associated with the 'ADDRESS*' and 'DATA*'
f1428c4c
UH
46command. Slave addresses do not include bit 0 (the READ/WRITE indication bit).
47For example, a slave address field could be 0x51 (instead of 0xa2).
bf69977d 48For 'START', 'START REPEAT', 'STOP', 'ACK', and 'NACK' <pdata> is None.
e7c6af6e
GS
49For 'BITS' <pdata> is a sequence of tuples of bit values and their start and
50stop positions, in LSB first order (although the I2C protocol is MSB first).
f1428c4c
UH
51'''
52
01416b98
GS
53# Meaning of table items:
54# command -> [annotation class, annotation text in order of decreasing length]
1541976f 55proto = {
01416b98
GS
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}'],
15969949 66}
e5080882 67
677d597b 68class Decoder(srd.Decoder):
592f355b 69 api_version = 3
67e847fd 70 id = 'i2c'
ab4aa33c 71 name = 'I²C'
9a12a6e7 72 longname = 'Inter-Integrated Circuit'
a465436e 73 desc = 'Two-wire, multi-master, serial bus.'
f39d2404
UH
74 license = 'gplv2+'
75 inputs = ['logic']
76 outputs = ['i2c']
d6d8a8a4 77 tags = ['Embedded/industrial']
6a15597a 78 channels = (
bc5f5a43
BV
79 {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
80 {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
da9bcbd9 81 )
84c1c0b5
BV
82 options = (
83 {'id': 'address_format', 'desc': 'Displayed slave address format',
84 'default': 'shifted', 'values': ('shifted', 'unshifted')},
85 )
da9bcbd9
BV
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'),
e144452b 97 ('warning', 'Warning'),
da9bcbd9 98 )
de038c47
UH
99 annotation_rows = (
100 ('bits', 'Bits', (5,)),
e144452b 101 ('addr-data', 'Address/data', (0, 1, 2, 3, 4, 6, 7, 8, 9)),
de038c47
UH
102 ('warnings', 'Warnings', (10,)),
103 )
a929afa6 104 binary = (
5cb2cb02
BV
105 ('address-read', 'Address read'),
106 ('address-write', 'Address write'),
107 ('data-read', 'Data read'),
108 ('data-write', 'Data write'),
a929afa6 109 )
0588ed70 110
92b7b49f 111 def __init__(self):
10aeb8ea
GS
112 self.reset()
113
114 def reset(self):
8d2a9636 115 self.samplerate = None
14ba515b 116 self.is_write = None
4f139c28 117 self.rem_addr_bytes = None
14ba515b 118 self.is_repeat_start = False
2b716038 119 self.state = 'FIND START'
8d2a9636
BV
120 self.pdu_start = None
121 self.pdu_bits = 0
14ba515b 122 self.data_bits = []
0fbf1528 123 self.bitwidth = 0
8d2a9636
BV
124
125 def metadata(self, key, value):
126 if key == srd.SRD_CONF_SAMPLERATE:
127 self.samplerate = value
f39d2404 128
8915b346 129 def start(self):
c515eed7 130 self.out_python = self.register(srd.OUTPUT_PYTHON)
8d2a9636 131 self.out_ann = self.register(srd.OUTPUT_ANN)
be6733ca 132 self.out_binary = self.register(srd.OUTPUT_BINARY)
8d2a9636
BV
133 self.out_bitrate = self.register(srd.OUTPUT_META,
134 meta=(int, 'Bitrate', 'Bitrate from Start bit to Stop bit'))
3643fc3f 135
e7c6af6e
GS
136 def putg(self, ss, es, cls, text):
137 self.put(ss, es, self.out_ann, [cls, text])
d94ff143 138
e7c6af6e
GS
139 def putp(self, ss, es, data):
140 self.put(ss, es, self.out_python, data)
d94ff143 141
e7c6af6e
GS
142 def putb(self, ss, es, data):
143 self.put(ss, es, self.out_binary, data)
a929afa6 144
0fbf1528 145 def handle_start(self, ss, es):
5eb66408
GS
146 if self.is_repeat_start:
147 cmd = 'START REPEAT'
148 else:
149 cmd = 'START'
0fbf1528 150 self.pdu_start = ss
5eb66408 151 self.pdu_bits = 0
e7c6af6e 152 self.putp(ss, es, [cmd, None])
01416b98 153 cls, texts = proto[cmd][0], proto[cmd][1:]
e7c6af6e 154 self.putg(ss, es, cls, texts)
2b716038 155 self.state = 'FIND ADDRESS'
14ba515b
GS
156 self.is_repeat_start = True
157 self.is_write = None
4f139c28 158 self.rem_addr_bytes = None
647aba6a 159 self.data_bits.clear()
0fbf1528 160 self.bitwidth = 0
7b86f0bc 161
c4975078 162 # Gather 8 bits of data plus the ACK/NACK bit.
0fbf1528 163 def handle_address_or_data(self, ss, es, value):
592f355b
UH
164 self.pdu_bits += 1
165
647aba6a
GS
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.
647aba6a 174 if self.data_bits:
0fbf1528
GS
175 self.data_bits[-1][2] = ss
176 self.data_bits.append([value, ss, es])
647aba6a 177 if len(self.data_bits) < 8:
eb7082c9 178 return
647aba6a 179 self.bitwidth = self.data_bits[-2][2] - self.data_bits[-3][2]
0fbf1528 180 self.data_bits[-1][2] = self.data_bits[-1][1] + self.bitwidth
7b86f0bc 181
647aba6a
GS
182 # Get the byte value. Address and data are transmitted MSB-first.
183 d = bitpack_msb(self.data_bits, 0)
2b716038 184 if self.state == 'FIND ADDRESS':
4f139c28
GS
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
35753cca 201 has_rw_bit = self.is_write is None
4f139c28
GS
202 if self.is_write is None:
203 read_bit = bool(addr_byte & 1)
35753cca 204 if self.options['address_format'] == 'shifted':
4f139c28
GS
205 d = d >> 1
206 self.is_write = False if read_bit else True
207 else:
208 self.slave_addr_10 |= addr_byte
15969949 209
a929afa6 210 bin_class = -1
14ba515b 211 if self.state == 'FIND ADDRESS' and self.is_write:
a2d2aff2 212 cmd = 'ADDRESS WRITE'
a929afa6 213 bin_class = 1
14ba515b 214 elif self.state == 'FIND ADDRESS' and not self.is_write:
a2d2aff2 215 cmd = 'ADDRESS READ'
a929afa6 216 bin_class = 0
14ba515b 217 elif self.state == 'FIND DATA' and self.is_write:
a2d2aff2 218 cmd = 'DATA WRITE'
a929afa6 219 bin_class = 3
14ba515b 220 elif self.state == 'FIND DATA' and not self.is_write:
a2d2aff2 221 cmd = 'DATA READ'
a929afa6 222 bin_class = 2
eb7082c9 223
e7c6af6e 224 ss_byte, es_byte = self.data_bits[0][1], self.data_bits[-1][2]
de038c47 225
647aba6a
GS
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.
e7c6af6e
GS
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])
de038c47 234
e7c6af6e 235 self.putb(ss_byte, es_byte, [bin_class, bytes([d])])
7b86f0bc 236
e7c6af6e 237 for bit_value, ss_bit, es_bit in lsb_bits:
01416b98 238 cls, texts = proto['BIT'][0], proto['BIT'][1:]
e7c6af6e
GS
239 texts = [t.format(b = bit_value) for t in texts]
240 self.putg(ss_bit, es_bit, cls, texts)
de038c47 241
35753cca 242 if cmd.startswith('ADDRESS') and has_rw_bit:
e7c6af6e
GS
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]
01416b98 247 cls = proto[cmd][0]
14ba515b 248 w = ['Write', 'Wr', 'W'] if self.is_write else ['Read', 'Rd', 'R']
e7c6af6e 249 self.putg(ss_bit, es_bit, cls, w)
de038c47 250
01416b98
GS
251 cls, texts = proto[cmd][0], proto[cmd][1:]
252 texts = [t.format(b = d) for t in texts]
e7c6af6e 253 self.putg(ss_byte, es_byte, cls, texts)
de038c47 254
1b75abfd 255 # Done with this packet.
647aba6a 256 self.data_bits.clear()
2b716038 257 self.state = 'FIND ACK'
7b86f0bc 258
0fbf1528
GS
259 def get_ack(self, ss, es, value):
260 ss_bit, es_bit = ss, es
261 cmd = 'NACK' if value == 1 else 'ACK'
e7c6af6e 262 self.putp(ss_bit, es_bit, [cmd, None])
01416b98 263 cls, texts = proto[cmd][0], proto[cmd][1:]
e7c6af6e 264 self.putg(ss_bit, es_bit, cls, texts)
4f139c28
GS
265 # Slave addresses can span one or two bytes, before data bytes
266 # follow. There can be an arbitrary number of data bytes. Stick
267 # with getting more address bytes if applicable, or enter or
268 # remain in the data phase of the transfer otherwise.
269 if self.rem_addr_bytes:
270 self.rem_addr_bytes -= 1
271 if self.rem_addr_bytes:
272 self.state = 'FIND ADDRESS'
273 else:
274 self.state = 'FIND DATA'
7b86f0bc 275
0fbf1528 276 def handle_stop(self, ss, es):
8d2a9636 277 # Meta bitrate
5eb66408 278 if self.samplerate and self.pdu_start:
0fbf1528 279 elapsed = es - self.pdu_start + 1
5eb66408 280 elapsed /= self.samplerate
8accc30b 281 bitrate = int(1 / elapsed * self.pdu_bits)
0fbf1528 282 ss_meta, es_meta = self.pdu_start, es
e7c6af6e 283 self.put(ss_meta, es_meta, self.out_bitrate, bitrate)
5eb66408
GS
284 self.pdu_start = None
285 self.pdu_bits = 0
8d2a9636 286
d94ff143 287 cmd = 'STOP'
e7c6af6e 288 self.putp(ss, es, [cmd, None])
01416b98 289 cls, texts = proto[cmd][0], proto[cmd][1:]
e7c6af6e 290 self.putg(ss, es, cls, texts)
2b716038 291 self.state = 'FIND START'
14ba515b
GS
292 self.is_repeat_start = False
293 self.is_write = None
647aba6a 294 self.data_bits.clear()
7b86f0bc 295
592f355b 296 def decode(self):
0fbf1528
GS
297 # Check for several bus conditions. Determine sample numbers
298 # here and pass ss, es, and bit values to handling routines.
592f355b 299 while True:
7b86f0bc 300 # State machine.
2b716038 301 if self.state == 'FIND START':
592f355b 302 # Wait for a START condition (S): SCL = high, SDA = falling.
0fbf1528
GS
303 pins = self.wait({0: 'h', 1: 'f'})
304 ss, es = self.samplenum, self.samplenum
305 self.handle_start(ss, es)
2b716038 306 elif self.state == 'FIND ADDRESS':
592f355b 307 # Wait for a data bit: SCL = rising.
0fbf1528
GS
308 pins = self.wait({0: 'r'})
309 _, sda = pins
310 ss, es = self.samplenum, self.samplenum # TODO plus bitwidth
311 self.handle_address_or_data(ss, es, sda)
2b716038 312 elif self.state == 'FIND DATA':
592f355b
UH
313 # Wait for any of the following conditions (or combinations):
314 # a) Data sampling of receiver: SCL = rising, and/or
315 # b) START condition (S): SCL = high, SDA = falling, and/or
316 # c) STOP condition (P): SCL = high, SDA = rising
fcd5d23a 317 pins = self.wait([{0: 'r'}, {0: 'h', 1: 'f'}, {0: 'h', 1: 'r'}])
592f355b
UH
318
319 # Check which of the condition(s) matched and handle them.
320 if self.matched[0]:
0fbf1528
GS
321 _, sda = pins
322 ss, es = self.samplenum, self.samplenum # TODO plus bitwidth
323 self.handle_address_or_data(ss, es, sda)
592f355b 324 elif self.matched[1]:
0fbf1528
GS
325 ss, es = self.samplenum, self.samplenum
326 self.handle_start(ss, es)
592f355b 327 elif self.matched[2]:
0fbf1528
GS
328 ss, es = self.samplenum, self.samplenum
329 self.handle_stop(ss, es)
2b716038 330 elif self.state == 'FIND ACK':
592f355b 331 # Wait for a data/ack bit: SCL = rising.
0fbf1528
GS
332 pins = self.wait({0: 'r'})
333 _, sda = pins
334 ss, es = self.samplenum, self.samplenum + self.bitwidth
335 self.get_ack(ss, es, sda)