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