]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2c/pd.py
1f53e873d41684d0b8dcac09552e297a59ac4d19
[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         self.bitwidth = 0
124
125     def metadata(self, key, value):
126         if key == srd.SRD_CONF_SAMPLERATE:
127             self.samplerate = value
128
129     def start(self):
130         self.out_python = self.register(srd.OUTPUT_PYTHON)
131         self.out_ann = self.register(srd.OUTPUT_ANN)
132         self.out_binary = self.register(srd.OUTPUT_BINARY)
133         self.out_bitrate = self.register(srd.OUTPUT_META,
134                 meta=(int, 'Bitrate', 'Bitrate from Start bit to Stop bit'))
135
136     def putg(self, ss, es, cls, text):
137         self.put(ss, es, self.out_ann, [cls, text])
138
139     def putp(self, ss, es, data):
140         self.put(ss, es, self.out_python, data)
141
142     def putb(self, ss, es, data):
143         self.put(ss, es, self.out_binary, data)
144
145     def handle_start(self, ss, es):
146         if self.is_repeat_start:
147             cmd = 'START REPEAT'
148         else:
149             cmd = 'START'
150             self.pdu_start = ss
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         self.bitwidth = 0
161
162     # Gather 8 bits of data plus the ACK/NACK bit.
163     def handle_address_or_data(self, ss, es, value):
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] = ss
176         self.data_bits.append([value, ss, es])
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.data_bits[-1][1] + 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             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
209
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
223
224         ss_byte, es_byte = self.data_bits[0][1], self.data_bits[-1][2]
225
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])
234
235         self.putb(ss_byte, es_byte, [bin_class, bytes([d])])
236
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)
241
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)
250
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)
254
255         # Done with this packet.
256         self.data_bits.clear()
257         self.state = 'FIND ACK'
258
259     def get_ack(self, ss, es, value):
260         ss_bit, es_bit = ss, es
261         cmd = 'NACK' if value == 1 else 'ACK'
262         self.putp(ss_bit, es_bit, [cmd, None])
263         cls, texts = proto[cmd][0], proto[cmd][1:]
264         self.putg(ss_bit, es_bit, cls, texts)
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'
275
276     def handle_stop(self, ss, es):
277         # Meta bitrate
278         if self.samplerate and self.pdu_start:
279             elapsed = es - self.pdu_start + 1
280             elapsed /= self.samplerate
281             bitrate = int(1 / elapsed * self.pdu_bits)
282             ss_meta, es_meta = self.pdu_start, es
283             self.put(ss_meta, es_meta, self.out_bitrate, bitrate)
284             self.pdu_start = None
285             self.pdu_bits = 0
286
287         cmd = 'STOP'
288         self.putp(ss, es, [cmd, None])
289         cls, texts = proto[cmd][0], proto[cmd][1:]
290         self.putg(ss, es, cls, texts)
291         self.state = 'FIND START'
292         self.is_repeat_start = False
293         self.is_write = None
294         self.data_bits.clear()
295
296     def decode(self):
297         # Check for several bus conditions. Determine sample numbers
298         # here and pass ss, es, and bit values to handling routines.
299         while True:
300             # State machine.
301             if self.state == 'FIND START':
302                 # Wait for a START condition (S): SCL = high, SDA = falling.
303                 pins = self.wait({0: 'h', 1: 'f'})
304                 ss, es = self.samplenum, self.samplenum
305                 self.handle_start(ss, es)
306             elif self.state == 'FIND ADDRESS':
307                 # Wait for a data bit: SCL = rising.
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)
312             elif self.state == 'FIND DATA':
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
317                 pins = self.wait([{0: 'r'}, {0: 'h', 1: 'f'}, {0: 'h', 1: 'r'}])
318
319                 # Check which of the condition(s) matched and handle them.
320                 if self.matched[0]:
321                     _, sda = pins
322                     ss, es = self.samplenum, self.samplenum # TODO plus bitwidth
323                     self.handle_address_or_data(ss, es, sda)
324                 elif self.matched[1]:
325                     ss, es = self.samplenum, self.samplenum
326                     self.handle_start(ss, es)
327                 elif self.matched[2]:
328                     ss, es = self.samplenum, self.samplenum
329                     self.handle_stop(ss, es)
330             elif self.state == 'FIND ACK':
331                 # Wait for a data/ack bit: SCL = rising.
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)