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