]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2c.py
f28b1583a1143a5cda6f79b88b5e5f3ab9df3aea
[libsigrokdecode.git] / decoders / i2c.py
1 ##
2 ## This file is part of the sigrok project.
3 ##
4 ## Copyright (C) 2010-2011 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, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19 ##
20
21 #
22 # I2C protocol decoder
23 #
24
25 #
26 # The Inter-Integrated Circuit (I2C) bus is a bidirectional, multi-master
27 # bus using two signals (SCL = serial clock line, SDA = serial data line).
28 #
29 # There can be many devices on the same bus. Each device can potentially be
30 # master or slave (and that can change during runtime). Both slave and master
31 # can potentially play the transmitter or receiver role (this can also
32 # change at runtime).
33 #
34 # Possible maximum data rates:
35 #  - Standard mode: 100 kbit/s
36 #  - Fast mode: 400 kbit/s
37 #  - Fast-mode Plus: 1 Mbit/s
38 #  - High-speed mode: 3.4 Mbit/s
39 #
40 # START condition (S): SDA = falling, SCL = high
41 # Repeated START condition (Sr): same as S
42 # Data bit sampling: SCL = rising
43 # STOP condition (P): SDA = rising, SCL = high
44 #
45 # All data bytes on SDA are exactly 8 bits long (transmitted MSB-first).
46 # Each byte has to be followed by a 9th ACK/NACK bit. If that bit is low,
47 # that indicates an ACK, if it's high that indicates a NACK.
48 #
49 # After the first START condition, a master sends the device address of the
50 # slave it wants to talk to. Slave addresses are 7 bits long (MSB-first).
51 # After those 7 bits, a data direction bit is sent. If the bit is low that
52 # indicates a WRITE operation, if it's high that indicates a READ operation.
53 #
54 # Later an optional 10bit slave addressing scheme was added.
55 #
56 # Documentation:
57 # http://www.nxp.com/acrobat/literature/9398/39340011.pdf (v2.1 spec)
58 # http://www.nxp.com/acrobat/usermanuals/UM10204_3.pdf (v3 spec)
59 # http://en.wikipedia.org/wiki/I2C
60 #
61
62 # TODO: Look into arbitration, collision detection, clock synchronisation, etc.
63 # TODO: Handle clock stretching.
64 # TODO: Handle combined messages / repeated START.
65 # TODO: Implement support for 7bit and 10bit slave addresses.
66 # TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
67 # TODO: Implement support for detecting various bus errors.
68 # TODO: I2C address of slaves.
69 # TODO: Handle multiple different I2C devices on same bus
70 #       -> we need to decode multiple protocols at the same time.
71
72 '''
73 Protocol output format:
74
75 I2C packet:
76 [<i2c_command>, <data>, <ack_bit>]
77
78 <i2c_command> is one of:
79   - 'START' (START condition)
80   - 'START REPEAT' (Repeated START)
81   - 'ADDRESS READ' (Address, read)
82   - 'ADDRESS WRITE' (Address, write)
83   - 'DATA READ' (Data, read)
84   - 'DATA WRITE' (Data, write)
85   - 'STOP' (STOP condition)
86
87 <data> is the data or address byte associated with the 'ADDRESS*' and 'DATA*'
88 command. For 'START', 'START REPEAT' and 'STOP', this is None.
89
90 <ack_bit> is either 'ACK' or 'NACK', but may also be None.
91 '''
92
93 import sigrokdecode as srd
94
95 # Annotation feed formats
96 ANN_SHIFTED       = 0
97 ANN_SHIFTED_SHORT = 1
98 ANN_RAW           = 2
99
100 # Values are verbose and short annotation, respectively.
101 protocol = {
102     'START':           ['START',         'S'],
103     'START REPEAT':    ['START REPEAT',  'Sr'],
104     'STOP':            ['STOP',          'P'],
105     'ACK':             ['ACK',           'A'],
106     'NACK':            ['NACK',          'N'],
107     'ADDRESS READ':    ['ADDRESS READ',  'AR'],
108     'ADDRESS WRITE':   ['ADDRESS WRITE', 'AW'],
109     'DATA READ':       ['DATA READ',     'DR'],
110     'DATA WRITE':      ['DATA WRITE',    'DW'],
111 }
112
113 # States
114 FIND_START = 0
115 FIND_ADDRESS = 1
116 FIND_DATA = 2
117
118 class Decoder(srd.Decoder):
119     id = 'i2c'
120     name = 'I2C'
121     longname = 'Inter-Integrated Circuit'
122     desc = 'I2C is a two-wire, multi-master, serial bus.'
123     longdesc = '...'
124     author = 'Uwe Hermann'
125     email = 'uwe@hermann-uwe.de'
126     license = 'gplv2+'
127     inputs = ['logic']
128     outputs = ['i2c']
129     probes = [
130         {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
131         {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
132     ]
133     options = {
134         'addressing': ['Slave addressing (in bits)', 7], # 7 or 10
135     }
136     annotations = [
137         # ANN_SHIFTED
138         ['7-bit shifted hex',
139          'Read/write bit shifted out from the 8-bit I2C slave address'],
140         # ANN_SHIFTED_SHORT
141         ['7-bit shifted hex (short)',
142          'Read/write bit shifted out from the 8-bit I2C slave address'],
143         # ANN_RAW
144         ['Raw hex', 'Unaltered raw data'],
145     ]
146
147     def __init__(self, **kwargs):
148         self.samplecnt = 0
149         self.bitcount = 0
150         self.databyte = 0
151         self.wr = -1
152         self.startsample = -1
153         self.is_repeat_start = 0
154         self.state = FIND_START
155         self.oldscl = None
156         self.oldsda = None
157
158         # Set protocol decoder option defaults.
159         self.addressing = Decoder.options['addressing'][1]
160
161     def start(self, metadata):
162         self.out_proto = self.add(srd.OUTPUT_PROTO, 'i2c')
163         self.out_ann = self.add(srd.OUTPUT_ANN, 'i2c')
164
165     def report(self):
166         pass
167
168     def is_start_condition(self, scl, sda):
169         # START condition (S): SDA = falling, SCL = high
170         if (self.oldsda == 1 and sda == 0) and scl == 1:
171             return True
172         return False
173
174     def is_data_bit(self, scl, sda):
175         # Data sampling of receiver: SCL = rising
176         if self.oldscl == 0 and scl == 1:
177             return True
178         return False
179
180     def is_stop_condition(self, scl, sda):
181         # STOP condition (P): SDA = rising, SCL = high
182         if (self.oldsda == 0 and sda == 1) and scl == 1:
183             return True
184         return False
185
186     def found_start(self, scl, sda):
187         cmd = 'START REPEAT' if (self.is_repeat_start == 1) else 'START'
188
189         self.put(self.out_proto, [cmd, None, None])
190         self.put(self.out_ann, [ANN_SHIFTED, [protocol[cmd][0]]])
191         self.put(self.out_ann, [ANN_SHIFTED_SHORT, [protocol[cmd][1]]])
192
193         self.state = FIND_ADDRESS
194         self.bitcount = self.databyte = 0
195         self.is_repeat_start = 1
196         self.wr = -1
197
198     def found_address_or_data(self, scl, sda):
199         # Gather 8 bits of data plus the ACK/NACK bit.
200
201         if self.startsample == -1:
202             # TODO: Should be samplenum, as received from the feed.
203             self.startsample = self.samplecnt
204         self.bitcount += 1
205
206         # Address and data are transmitted MSB-first.
207         self.databyte <<= 1
208         self.databyte |= sda
209
210         # Return if we haven't collected all 8 + 1 bits, yet.
211         if self.bitcount != 9:
212             return
213
214         # Send raw output annotation before we start shifting out
215         # read/write and ack/nack bits.
216         self.put(self.out_ann, [ANN_RAW, ['0x%.2x' % self.databyte]])
217
218         # We received 8 address/data bits and the ACK/NACK bit.
219         self.databyte >>= 1 # Shift out unwanted ACK/NACK bit here.
220
221         if self.state == FIND_ADDRESS:
222             # The READ/WRITE bit is only in address bytes, not data bytes.
223             self.wr = 0 if (self.databyte & 1) else 1
224             d = self.databyte >> 1
225         elif self.state == FIND_DATA:
226             d = self.databyte
227         else:
228             # TODO: Error?
229             pass
230
231         # Last bit that came in was the ACK/NACK bit (1 = NACK).
232         ack_bit = 'NACK' if (sda == 1) else 'ACK'
233
234         if self.state == FIND_ADDRESS and self.wr == 1:
235             cmd = 'ADDRESS WRITE'
236         elif self.state == FIND_ADDRESS and self.wr == 0:
237             cmd = 'ADDRESS READ'
238         elif self.state == FIND_DATA and self.wr == 1:
239             cmd = 'DATA WRITE'
240         elif self.state == FIND_DATA and self.wr == 0:
241             cmd = 'DATA READ'
242
243         self.put(self.out_proto, [cmd, d, ack_bit])
244         self.put(self.out_ann, [ANN_SHIFTED,
245                  [protocol[cmd][0], '0x%02x' % d, protocol[ack_bit][0]]])
246         self.put(self.out_ann, [ANN_SHIFTED_SHORT,
247                  [protocol[cmd][1], '0x%02x' % d, protocol[ack_bit][1]]])
248
249         self.bitcount = self.databyte = 0
250         self.startsample = -1
251
252         if self.state == FIND_ADDRESS:
253             self.state = FIND_DATA
254         elif self.state == FIND_DATA:
255             # There could be multiple data bytes in a row.
256             # So, either find a STOP condition or another data byte next.
257             pass
258
259     def found_stop(self, scl, sda):
260         self.put(self.out_proto, ['STOP', None, None])
261         self.put(self.out_ann, [ANN_SHIFTED, [protocol['STOP'][0]]])
262         self.put(self.out_ann, [ANN_SHIFTED_SHORT, [protocol['STOP'][1]]])
263
264         self.state = FIND_START
265         self.is_repeat_start = 0
266         self.wr = -1
267
268     def put(self, output_id, data):
269         # Inject sample range into the call up to sigrok.
270         # TODO: 0-0 sample range for now.
271         super(Decoder, self).put(0, 0, output_id, data)
272
273     def decode(self, ss, es, data):
274         for samplenum, (scl, sda) in data:
275             self.samplecnt += 1
276
277             # First sample: Save SCL/SDA value.
278             if self.oldscl == None:
279                 self.oldscl = scl
280                 self.oldsda = sda
281                 continue
282
283             # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
284
285             # State machine.
286             if self.state == FIND_START:
287                 if self.is_start_condition(scl, sda):
288                     self.found_start(scl, sda)
289             elif self.state == FIND_ADDRESS:
290                 if self.is_data_bit(scl, sda):
291                     self.found_address_or_data(scl, sda)
292             elif self.state == FIND_DATA:
293                 if self.is_data_bit(scl, sda):
294                     self.found_address_or_data(scl, sda)
295                 elif self.is_start_condition(scl, sda):
296                     self.found_start(scl, sda)
297                 elif self.is_stop_condition(scl, sda):
298                     self.found_stop(scl, sda)
299             else:
300                 # TODO: Error?
301                 pass
302
303             # Save current SDA/SCL values for the next round.
304             self.oldscl = scl
305             self.oldsda = sda
306