]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2c.py
srd: i2c.py: States are global, not per-instance.
[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
69 #
70 # I2C output format:
71 #
72 # The output consists of a (Python) list of I2C "packets", each of which
73 # has an (implicit) index number (its index in the list).
74 # Each packet consists of a Python dict with certain key/value pairs.
75 #
76 # TODO: Make this a list later instead of a dict?
77 #
78 # 'type': (string)
79 #   - 'S' (START condition)
80 #   - 'Sr' (Repeated START)
81 #   - 'AR' (Address, read)
82 #   - 'AW' (Address, write)
83 #   - 'DR' (Data, read)
84 #   - 'DW' (Data, write)
85 #   - 'P' (STOP condition)
86 # 'range': (tuple of 2 integers, the min/max samplenumber of this range)
87 #   - (min, max)
88 #   - min/max can also be identical.
89 # 'data': (actual data as integer ???) TODO: This can be very variable...
90 # 'ann': (string; additional annotations / comments)
91 #
92 # Example output:
93 # [{'type': 'S',  'range': (150, 160), 'data': None, 'ann': 'Foobar'},
94 #  {'type': 'AW', 'range': (200, 300), 'data': 0x50, 'ann': 'Slave 4'},
95 #  {'type': 'DW', 'range': (310, 370), 'data': 0x00, 'ann': 'Init cmd'},
96 #  {'type': 'AR', 'range': (500, 560), 'data': 0x50, 'ann': 'Get stat'},
97 #  {'type': 'DR', 'range': (580, 640), 'data': 0xfe, 'ann': 'OK'},
98 #  {'type': 'P',  'range': (650, 660), 'data': None, 'ann': None}]
99 #
100 # Possible other events:
101 #   - Error event in case protocol looks broken:
102 #     [{'type': 'ERROR', 'range': (min, max),
103 #      'data': TODO, 'ann': 'This is not a Microchip 24XX64 EEPROM'},
104 #     [{'type': 'ERROR', 'range': (min, max),
105 #      'data': TODO, 'ann': 'TODO'},
106 #   - TODO: Make list of possible errors accessible as metadata?
107 #
108 # TODO: I2C address of slaves.
109 # TODO: Handle multiple different I2C devices on same bus
110 #       -> we need to decode multiple protocols at the same time.
111 # TODO: range: Always contiguous? Splitted ranges? Multiple per event?
112 #
113
114 #
115 # I2C input format:
116 #
117 # signals:
118 # [[id, channel, description], ...] # TODO
119 #
120 # Example:
121 # {'id': 'SCL', 'ch': 5, 'desc': 'Serial clock line'}
122 # {'id': 'SDA', 'ch': 7, 'desc': 'Serial data line'}
123 # ...
124 #
125 # {'inbuf': [...],
126 #  'signals': [{'SCL': }]}
127 #
128
129 # States
130 FIND_START = 0
131 FIND_ADDRESS = 1
132 FIND_DATA = 2
133
134 class Sample():
135     def __init__(self, data):
136         self.data = data
137     def probe(self, probe):
138         s = ord(self.data[probe / 8]) & (1 << (probe % 8))
139         return True if s else False
140
141 def sampleiter(data, unitsize):
142     for i in range(0, len(data), unitsize):
143         yield(Sample(data[i:i+unitsize]))
144
145 class Decoder():
146     name = 'I2C'
147     longname = 'Inter-Integrated Circuit (I2C) bus'
148     desc = 'I2C is a two-wire, multi-master, serial bus.'
149     longdesc = '...'
150     author = 'Uwe Hermann'
151     email = 'uwe@hermann-uwe.de'
152     license = 'gplv2+'
153     inputs = ['logic']
154     outputs = ['i2c']
155     probes = {
156         'scl': {'ch': 0, 'name': 'SCL', 'desc': 'Serial clock line'},
157         'sda': {'ch': 1, 'name': 'SDA', 'desc': 'Serial data line'},
158     }
159     options = {
160         'address-space': ['Address space (in bits)', 7],
161     }
162
163     def __init__(self, **kwargs):
164         self.probes = Decoder.probes.copy()
165
166         # TODO: Don't hardcode the number of channels.
167         self.channels = 8
168
169         self.samplenum = 0
170         self.bitcount = 0
171         self.databyte = 0
172         self.wr = -1
173         self.startsample = -1
174         self.is_repeat_start = 0
175
176         self.state = FIND_START
177
178         # Get the channel/probe number of the SCL/SDA signals.
179         self.scl_bit = self.probes['scl']['ch']
180         self.sda_bit = self.probes['sda']['ch']
181
182         self.oldscl = None
183         self.oldsda = None
184
185     def start(self, metadata):
186         self.unitsize = metadata["unitsize"]
187
188     def report(self):
189         pass
190
191     def is_start_condition(self, scl, sda):
192         """START condition (S): SDA = falling, SCL = high"""
193         if (self.oldsda == 1 and sda == 0) and scl == 1:
194             return True
195         return False
196
197     def is_data_bit(self, scl, sda):
198         """Data sampling of receiver: SCL = rising"""
199         if self.oldscl == 0 and scl == 1:
200             return True
201         return False
202
203     def is_stop_condition(self, scl, sda):
204         """STOP condition (P): SDA = rising, SCL = high"""
205         if (self.oldsda == 0 and sda == 1) and scl == 1:
206             return True
207         return False
208
209     def find_start(self, scl, sda):
210         out = []
211         # o = {'type': 'S', 'range': (self.samplenum, self.samplenum),
212         #      'data': None, 'ann': None},
213         o = (self.is_repeat_start == 1) and 'Sr' or 'S'
214         out.append(o)
215         self.state = FIND_ADDRESS
216         self.bitcount = self.databyte = 0
217         self.is_repeat_start = 1
218         self.wr = -1
219         return out
220
221     def find_address_or_data(self, scl, sda):
222         """Gather 8 bits of data plus the ACK/NACK bit."""
223         out = o = []
224
225         if self.startsample == -1:
226             self.startsample = self.samplenum
227         self.bitcount += 1
228
229         # Address and data are transmitted MSB-first.
230         self.databyte <<= 1
231         self.databyte |= sda
232
233         # Return if we haven't collected all 8 + 1 bits, yet.
234         if self.bitcount != 9:
235             return []
236
237         # We received 8 address/data bits and the ACK/NACK bit.
238         self.databyte >>= 1 # Shift out unwanted ACK/NACK bit here.
239
240         ack = (sda == 1) and 'N' or 'A'
241
242         if self.state == FIND_ADDRESS:
243             d = self.databyte & 0xfe
244             # The READ/WRITE bit is only in address bytes, not data bytes.
245             self.wr = (self.databyte & 1) and 1 or 0
246         elif self.state == FIND_DATA:
247             d = self.databyte
248         else:
249             # TODO: Error?
250             pass
251
252         # o = {'type': self.state,
253         #      'range': (self.startsample, self.samplenum - 1),
254         #      'data': d, 'ann': None}
255
256         o = {'data': '0x%02x' % d}
257
258         # TODO: Simplify.
259         if self.state == FIND_ADDRESS and self.wr == 1:
260             o['type'] = 'AW'
261         elif self.state == FIND_ADDRESS and self.wr == 0:
262             o['type'] = 'AR'
263         elif self.state == FIND_DATA and self.wr == 1:
264             o['type'] = 'DW'
265         elif self.state == FIND_DATA and self.wr == 0:
266             o['type'] = 'DR'
267
268         out.append(o)
269
270         # o = {'type': ack, 'range': (self.samplenum, self.samplenum),
271         #      'data': None, 'ann': None}
272         o = ack
273         out.append(o)
274         self.bitcount = self.databyte = 0
275         self.startsample = -1
276
277         if self.state == FIND_ADDRESS:
278             self.state = FIND_DATA
279         elif self.state == FIND_DATA:
280             # There could be multiple data bytes in a row.
281             # So, either find a STOP condition or another data byte next.
282             pass
283
284         return out
285
286     def find_stop(self, scl, sda):
287         out = o = []
288
289         # o = {'type': 'P', 'range': (self.samplenum, self.samplenum),
290         #      'data': None, 'ann': None},
291         o = 'P'
292         out.append(o)
293         self.state = FIND_START
294         self.is_repeat_start = 0
295         self.wr = -1
296
297         return out
298
299     def decode(self, data):
300         """I2C protocol decoder"""
301
302         out = []
303         o = ack = d = ''
304
305         # We should accept a list of samples and iterate...
306         for sample in sampleiter(data['data'], self.unitsize):
307
308             # TODO: Eliminate the need for ord().
309             s = ord(sample.data)
310
311             # TODO: Start counting at 0 or 1?
312             self.samplenum += 1
313
314             # First sample: Save SCL/SDA value.
315             if self.oldscl == None:
316                 # Get SCL/SDA bit values (0/1 for low/high) of the first sample.
317                 self.oldscl = (s & (1 << self.scl_bit)) >> self.scl_bit
318                 self.oldsda = (s & (1 << self.sda_bit)) >> self.sda_bit
319                 continue
320
321             # Get SCL/SDA bit values (0/1 for low/high).
322             scl = (s & (1 << self.scl_bit)) >> self.scl_bit
323             sda = (s & (1 << self.sda_bit)) >> self.sda_bit
324
325             # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
326
327             # State machine.
328             if self.state == FIND_START:
329                 if self.is_start_condition(scl, sda):
330                     out += self.find_start(scl, sda)
331             elif self.state == FIND_ADDRESS:
332                 if self.is_data_bit(scl, sda):
333                     out += self.find_address_or_data(scl, sda)
334             elif self.state == FIND_DATA:
335                 if self.is_data_bit(scl, sda):
336                     out += self.find_address_or_data(scl, sda)
337                 elif self.is_start_condition(scl, sda):
338                     out += self.find_start(scl, sda)
339                 elif self.is_stop_condition(scl, sda):
340                     out += self.find_stop(scl, sda)
341             else:
342                 # TODO: Error?
343                 pass
344
345             # Save current SDA/SCL values for the next round.
346             self.oldscl = scl
347             self.oldsda = sda
348
349         if out != []:
350             sigrok.put(out)
351
352 import sigrok
353