]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2c/i2c.py
srd: Performance improvements for various PDs.
[libsigrokdecode.git] / decoders / i2c / 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 # I2C protocol decoder
22
23 # TODO: Look into arbitration, collision detection, clock synchronisation, etc.
24 # TODO: Handle clock stretching.
25 # TODO: Handle combined messages / repeated START.
26 # TODO: Implement support for 7bit and 10bit slave addresses.
27 # TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
28 # TODO: Implement support for detecting various bus errors.
29 # TODO: I2C address of slaves.
30 # TODO: Handle multiple different I2C devices on same bus
31 #       -> we need to decode multiple protocols at the same time.
32
33 import sigrokdecode as srd
34
35 # Annotation feed formats
36 ANN_SHIFTED = 0
37 ANN_SHIFTED_SHORT = 1
38 ANN_RAW = 2
39
40 # Values are verbose and short annotation, respectively.
41 proto = {
42     'START':           ['START',         'S'],
43     'START REPEAT':    ['START REPEAT',  'Sr'],
44     'STOP':            ['STOP',          'P'],
45     'ACK':             ['ACK',           'A'],
46     'NACK':            ['NACK',          'N'],
47     'ADDRESS READ':    ['ADDRESS READ',  'AR'],
48     'ADDRESS WRITE':   ['ADDRESS WRITE', 'AW'],
49     'DATA READ':       ['DATA READ',     'DR'],
50     'DATA WRITE':      ['DATA WRITE',    'DW'],
51 }
52
53 class Decoder(srd.Decoder):
54     api_version = 1
55     id = 'i2c'
56     name = 'I2C'
57     longname = 'Inter-Integrated Circuit'
58     desc = 'Two-wire, multi-master, serial bus.'
59     license = 'gplv2+'
60     inputs = ['logic']
61     outputs = ['i2c']
62     probes = [
63         {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
64         {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
65     ]
66     optional_probes = []
67     options = {
68         'addressing': ['Slave addressing (in bits)', 7], # 7 or 10
69     }
70     annotations = [
71         # ANN_SHIFTED
72         ['7-bit shifted hex',
73          'Read/write bit shifted out from the 8-bit I2C slave address'],
74         # ANN_SHIFTED_SHORT
75         ['7-bit shifted hex (short)',
76          'Read/write bit shifted out from the 8-bit I2C slave address'],
77         # ANN_RAW
78         ['Raw hex', 'Unaltered raw data'],
79     ]
80
81     def __init__(self, **kwargs):
82         self.startsample = -1
83         self.samplenum = None
84         self.bitcount = 0
85         self.databyte = 0
86         self.wr = -1
87         self.is_repeat_start = 0
88         self.state = 'FIND START'
89         self.oldscl = None
90         self.oldsda = None
91         self.oldpins = None
92
93     def start(self, metadata):
94         self.out_proto = self.add(srd.OUTPUT_PROTO, 'i2c')
95         self.out_ann = self.add(srd.OUTPUT_ANN, 'i2c')
96
97     def report(self):
98         pass
99
100     def is_start_condition(self, scl, sda):
101         # START condition (S): SDA = falling, SCL = high
102         if (self.oldsda == 1 and sda == 0) and scl == 1:
103             return True
104         return False
105
106     def is_data_bit(self, scl, sda):
107         # Data sampling of receiver: SCL = rising
108         if self.oldscl == 0 and scl == 1:
109             return True
110         return False
111
112     def is_stop_condition(self, scl, sda):
113         # STOP condition (P): SDA = rising, SCL = high
114         if (self.oldsda == 0 and sda == 1) and scl == 1:
115             return True
116         return False
117
118     def found_start(self, scl, sda):
119         self.startsample = self.samplenum
120
121         cmd = 'START REPEAT' if (self.is_repeat_start == 1) else 'START'
122         self.put(self.out_proto, [cmd, None])
123         self.put(self.out_ann, [ANN_SHIFTED, [proto[cmd][0]]])
124         self.put(self.out_ann, [ANN_SHIFTED_SHORT, [proto[cmd][1]]])
125
126         self.state = 'FIND ADDRESS'
127         self.bitcount = self.databyte = 0
128         self.is_repeat_start = 1
129         self.wr = -1
130
131     # Gather 8 bits of data plus the ACK/NACK bit.
132     def found_address_or_data(self, scl, sda):
133         # Address and data are transmitted MSB-first.
134         self.databyte <<= 1
135         self.databyte |= sda
136
137         if self.bitcount == 0:
138             self.startsample = self.samplenum
139
140         # Return if we haven't collected all 8 + 1 bits, yet.
141         self.bitcount += 1
142         if self.bitcount != 8:
143             return
144
145         # We triggered on the ACK/NACK bit, but won't report that until later.
146         self.startsample -= 1
147
148         # Send raw output annotation before we start shifting out
149         # read/write and ACK/NACK bits.
150         self.put(self.out_ann, [ANN_RAW, ['0x%.2x' % self.databyte]])
151
152         if self.state == 'FIND ADDRESS':
153             # The READ/WRITE bit is only in address bytes, not data bytes.
154             self.wr = 0 if (self.databyte & 1) else 1
155             d = self.databyte >> 1
156         elif self.state == 'FIND DATA':
157             d = self.databyte
158
159         if self.state == 'FIND ADDRESS' and self.wr == 1:
160             cmd = 'ADDRESS WRITE'
161         elif self.state == 'FIND ADDRESS' and self.wr == 0:
162             cmd = 'ADDRESS READ'
163         elif self.state == 'FIND DATA' and self.wr == 1:
164             cmd = 'DATA WRITE'
165         elif self.state == 'FIND DATA' and self.wr == 0:
166             cmd = 'DATA READ'
167
168         self.put(self.out_proto, [cmd, d])
169         self.put(self.out_ann, [ANN_SHIFTED, [proto[cmd][0], '0x%02x' % d]])
170         self.put(self.out_ann, [ANN_SHIFTED_SHORT, [proto[cmd][1], '0x%02x' % d]])
171
172         # Done with this packet.
173         self.startsample = -1
174         self.bitcount = self.databyte = 0
175         self.state = 'FIND ACK'
176
177     def get_ack(self, scl, sda):
178         self.startsample = self.samplenum
179         ack_bit = 'NACK' if (sda == 1) else 'ACK'
180         self.put(self.out_proto, [ack_bit, None])
181         self.put(self.out_ann, [ANN_SHIFTED, [proto[ack_bit][0]]])
182         self.put(self.out_ann, [ANN_SHIFTED_SHORT, [proto[ack_bit][1]]])
183         # There could be multiple data bytes in a row, so either find
184         # another data byte or a STOP condition next.
185         self.state = 'FIND DATA'
186
187     def found_stop(self, scl, sda):
188         self.startsample = self.samplenum
189         self.put(self.out_proto, ['STOP', None])
190         self.put(self.out_ann, [ANN_SHIFTED, [proto['STOP'][0]]])
191         self.put(self.out_ann, [ANN_SHIFTED_SHORT, [proto['STOP'][1]]])
192
193         self.state = 'FIND START'
194         self.is_repeat_start = 0
195         self.wr = -1
196
197     def put(self, output_id, data):
198         # Inject sample range into the call up to sigrok.
199         super(Decoder, self).put(self.startsample, self.samplenum, output_id, data)
200
201     def decode(self, ss, es, data):
202         for (self.samplenum, pins) in data:
203
204             # Ignore identical samples early on (for performance reasons).
205             if self.oldpins == pins:
206                 continue
207             self.oldpins, (scl, sda) = pins, pins
208
209             # First sample: Save SCL/SDA value.
210             if self.oldscl == None:
211                 self.oldscl = scl
212                 self.oldsda = sda
213                 continue
214
215             # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
216
217             # State machine.
218             if self.state == 'FIND START':
219                 if self.is_start_condition(scl, sda):
220                     self.found_start(scl, sda)
221             elif self.state == 'FIND ADDRESS':
222                 if self.is_data_bit(scl, sda):
223                     self.found_address_or_data(scl, sda)
224             elif self.state == 'FIND DATA':
225                 if self.is_data_bit(scl, sda):
226                     self.found_address_or_data(scl, sda)
227                 elif self.is_start_condition(scl, sda):
228                     self.found_start(scl, sda)
229                 elif self.is_stop_condition(scl, sda):
230                     self.found_stop(scl, sda)
231             elif self.state == 'FIND ACK':
232                 if self.is_data_bit(scl, sda):
233                     self.get_ack(scl, sda)
234             else:
235                 raise Exception('Invalid state %d' % self.STATE)
236
237             # Save current SDA/SCL values for the next round.
238             self.oldscl = scl
239             self.oldsda = sda
240