]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2c/pd.py
i2c: unobfuscate ss/es passing for put, document BITS order
[libsigrokdecode.git] / decoders / i2c / pd.py
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.
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, see <http://www.gnu.org/licenses/>.
18 ##
19
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.
23
24 from common.srdhelper import bitpack_msb
25 import sigrokdecode as srd
26
27 '''
28 OUTPUT_PYTHON format:
29
30 Packet:
31 [<ptype>, <pdata>]
32
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)
44
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 '''
52
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 }
67
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'},
81     )
82     options = (
83         {'id': 'address_format', 'desc': 'Displayed slave address format',
84             'default': 'shifted', 'values': ('shifted', 'unshifted')},
85     )
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'),
98     )
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,)),
103     )
104     binary = (
105         ('address-read', 'Address read'),
106         ('address-write', 'Address write'),
107         ('data-read', 'Data read'),
108         ('data-write', 'Data write'),
109     )
110
111     def __init__(self):
112         self.reset()
113
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 = []
123
124     def metadata(self, key, value):
125         if key == srd.SRD_CONF_SAMPLERATE:
126             self.samplerate = value
127
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'))
134
135     def putg(self, ss, es, cls, text):
136         self.put(ss, es, self.out_ann, [cls, text])
137
138     def putp(self, ss, es, data):
139         self.put(ss, es, self.out_python, data)
140
141     def putb(self, ss, es, data):
142         self.put(ss, es, self.out_binary, data)
143
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()
160
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
165
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
181
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             is_seven = self.slave_addr_7 is not None
202             if self.is_write is None:
203                 read_bit = bool(addr_byte & 1)
204                 shift_seven = self.options['address_format'] == 'shifted'
205                 if is_seven and shift_seven:
206                     d = d >> 1
207                 self.is_write = False if read_bit else True
208             else:
209                 self.slave_addr_10 |= addr_byte
210
211         bin_class = -1
212         if self.state == 'FIND ADDRESS' and self.is_write:
213             cmd = 'ADDRESS WRITE'
214             bin_class = 1
215         elif self.state == 'FIND ADDRESS' and not self.is_write:
216             cmd = 'ADDRESS READ'
217             bin_class = 0
218         elif self.state == 'FIND DATA' and self.is_write:
219             cmd = 'DATA WRITE'
220             bin_class = 3
221         elif self.state == 'FIND DATA' and not self.is_write:
222             cmd = 'DATA READ'
223             bin_class = 2
224
225         ss_byte, es_byte = self.data_bits[0][1], self.data_bits[-1][2]
226
227         # Reverse the list of bits to LSB first order before emitting
228         # annotations and passing bits to upper layers. This may be
229         # unexpected because the protocol is MSB first, but it keeps
230         # backwards compatibility.
231         lsb_bits = self.data_bits[:]
232         lsb_bits.reverse()
233         self.putp(ss_byte, es_byte, ['BITS', lsb_bits])
234         self.putp(ss_byte, es_byte, [cmd, d])
235
236         self.putb(ss_byte, es_byte, [bin_class, bytes([d])])
237
238         for bit_value, ss_bit, es_bit in lsb_bits:
239             cls, texts = proto['BIT'][0], proto['BIT'][1:]
240             texts = [t.format(b = bit_value) for t in texts]
241             self.putg(ss_bit, es_bit, cls, texts)
242
243         if cmd.startswith('ADDRESS') and is_seven:
244             # Assign the last bit's location to the R/W annotation.
245             # Adjust the address value's location to the left.
246             ss_bit, es_bit = self.data_bits[-1][1], self.data_bits[-1][2]
247             es_byte = self.data_bits[-2][2]
248             cls = proto[cmd][0]
249             w = ['Write', 'Wr', 'W'] if self.is_write else ['Read', 'Rd', 'R']
250             self.putg(ss_bit, es_bit, cls, w)
251
252         cls, texts = proto[cmd][0], proto[cmd][1:]
253         texts = [t.format(b = d) for t in texts]
254         self.putg(ss_byte, es_byte, cls, texts)
255
256         # Done with this packet.
257         self.data_bits.clear()
258         self.state = 'FIND ACK'
259
260     def get_ack(self, pins):
261         scl, sda = pins
262         # NOTE! Re-uses the last data bit's width for ACK/NAK as well.
263         # Which might be acceptable because this decoder implementation
264         # only gets to handle ACK/NAK after all DATA BITS were seen.
265         ss_bit, es_bit = self.samplenum, self.samplenum + self.bitwidth
266         cmd = 'NACK' if (sda == 1) else 'ACK'
267         self.putp(ss_bit, es_bit, [cmd, None])
268         cls, texts = proto[cmd][0], proto[cmd][1:]
269         self.putg(ss_bit, es_bit, cls, texts)
270         # Slave addresses can span one or two bytes, before data bytes
271         # follow. There can be an arbitrary number of data bytes. Stick
272         # with getting more address bytes if applicable, or enter or
273         # remain in the data phase of the transfer otherwise.
274         if self.rem_addr_bytes:
275             self.rem_addr_bytes -= 1
276         if self.rem_addr_bytes:
277             self.state = 'FIND ADDRESS'
278         else:
279             self.state = 'FIND DATA'
280
281     def handle_stop(self, pins):
282         # Meta bitrate
283         if self.samplerate and self.pdu_start:
284             elapsed = self.samplenum - self.pdu_start + 1
285             elapsed /= self.samplerate
286             bitrate = int(1 / elapsed * self.pdu_bits)
287             ss_meta, es_meta = self.pdu_start, self.samplenum
288             self.put(ss_meta, es_meta, self.out_bitrate, bitrate)
289             self.pdu_start = None
290             self.pdu_bits = 0
291
292         cmd = 'STOP'
293         ss, es = self.samplenum, self.samplenum
294         self.putp(ss, es, [cmd, None])
295         cls, texts = proto[cmd][0], proto[cmd][1:]
296         self.putg(ss, es, cls, texts)
297         self.state = 'FIND START'
298         self.is_repeat_start = False
299         self.is_write = None
300         self.data_bits.clear()
301
302     def decode(self):
303         while True:
304             # State machine.
305             if self.state == 'FIND START':
306                 # Wait for a START condition (S): SCL = high, SDA = falling.
307                 self.handle_start(self.wait({0: 'h', 1: 'f'}))
308             elif self.state == 'FIND ADDRESS':
309                 # Wait for a data bit: SCL = rising.
310                 self.handle_address_or_data(self.wait({0: 'r'}))
311             elif self.state == 'FIND DATA':
312                 # Wait for any of the following conditions (or combinations):
313                 #  a) Data sampling of receiver: SCL = rising, and/or
314                 #  b) START condition (S): SCL = high, SDA = falling, and/or
315                 #  c) STOP condition (P): SCL = high, SDA = rising
316                 pins = self.wait([{0: 'r'}, {0: 'h', 1: 'f'}, {0: 'h', 1: 'r'}])
317
318                 # Check which of the condition(s) matched and handle them.
319                 if self.matched[0]:
320                     self.handle_address_or_data(pins)
321                 elif self.matched[1]:
322                     self.handle_start(pins)
323                 elif self.matched[2]:
324                     self.handle_stop(pins)
325             elif self.state == 'FIND ACK':
326                 # Wait for a data/ack bit: SCL = rising.
327                 self.get_ack(self.wait({0: 'r'}))