]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2c/pd.py
6beb251442ef0d7f6b22864bf4b10068175119b3
[libsigrokdecode.git] / decoders / i2c / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2010-2013 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 '''
36 Protocol output format:
37
38 I2C packet:
39 [<cmd>, <data>]
40
41 <cmd> is one of:
42  - 'START' (START condition)
43  - 'START REPEAT' (Repeated START condition)
44  - 'ADDRESS READ' (Slave address, read)
45  - 'ADDRESS WRITE' (Slave address, write)
46  - 'DATA READ' (Data, read)
47  - 'DATA WRITE' (Data, write)
48  - 'STOP' (STOP condition)
49  - 'ACK' (ACK bit)
50  - 'NACK' (NACK bit)
51
52 <data> is the data or address byte associated with the 'ADDRESS*' and 'DATA*'
53 command. Slave addresses do not include bit 0 (the READ/WRITE indication bit).
54 For example, a slave address field could be 0x51 (instead of 0xa2).
55 For 'START', 'START REPEAT', 'STOP', 'ACK', and 'NACK' <data> is None.
56 '''
57
58 # CMD: [annotation-type-index, long annotation, short annotation]
59 proto = {
60     'START':           [0, 'Start',         'S'],
61     'START REPEAT':    [1, 'Start repeat',  'Sr'],
62     'STOP':            [2, 'Stop',          'P'],
63     'ACK':             [3, 'ACK',           'A'],
64     'NACK':            [4, 'NACK',          'N'],
65     'ADDRESS READ':    [5, 'Address read',  'AR'],
66     'ADDRESS WRITE':   [6, 'Address write', 'AW'],
67     'DATA READ':       [7, 'Data read',     'DR'],
68     'DATA WRITE':      [8, 'Data write',    'DW'],
69 }
70
71 class Decoder(srd.Decoder):
72     api_version = 1
73     id = 'i2c'
74     name = 'I2C'
75     longname = 'Inter-Integrated Circuit'
76     desc = 'Two-wire, multi-master, serial bus.'
77     license = 'gplv2+'
78     inputs = ['logic']
79     outputs = ['i2c']
80     probes = [
81         {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
82         {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
83     ]
84     optional_probes = []
85     options = {
86         'addressing': ['Slave addressing (in bits)', 7], # 7 or 10
87         'address_format': ['Displayed slave address format', 'shifted'],
88     }
89     annotations = [
90         ['Start', 'Start condition'],
91         ['Repeat start', 'Repeat start condition'],
92         ['Stop', 'Stop condition'],
93         ['ACK', 'ACK'],
94         ['NACK', 'NACK'],
95         ['Address read', 'Address read'],
96         ['Address write', 'Address write'],
97         ['Data read', 'Data read'],
98         ['Data write', 'Data write'],
99         ['Warnings', 'Human-readable warnings'],
100     ]
101
102     def __init__(self, **kwargs):
103         self.startsample = -1
104         self.samplenum = None
105         self.bitcount = 0
106         self.databyte = 0
107         self.wr = -1
108         self.is_repeat_start = 0
109         self.state = 'FIND START'
110         self.oldscl = 1
111         self.oldsda = 1
112         self.oldpins = [1, 1]
113
114     def start(self, metadata):
115         self.out_proto = self.add(srd.OUTPUT_PROTO, 'i2c')
116         self.out_ann = self.add(srd.OUTPUT_ANN, 'i2c')
117
118     def report(self):
119         pass
120
121     def putx(self, data):
122         self.put(self.startsample, self.samplenum, self.out_ann, data)
123
124     def putp(self, data):
125         self.put(self.startsample, self.samplenum, self.out_proto, data)
126
127     def is_start_condition(self, scl, sda):
128         # START condition (S): SDA = falling, SCL = high
129         if (self.oldsda == 1 and sda == 0) and scl == 1:
130             return True
131         return False
132
133     def is_data_bit(self, scl, sda):
134         # Data sampling of receiver: SCL = rising
135         if self.oldscl == 0 and scl == 1:
136             return True
137         return False
138
139     def is_stop_condition(self, scl, sda):
140         # STOP condition (P): SDA = rising, SCL = high
141         if (self.oldsda == 0 and sda == 1) and scl == 1:
142             return True
143         return False
144
145     def found_start(self, scl, sda):
146         self.startsample = self.samplenum
147         cmd = 'START REPEAT' if (self.is_repeat_start == 1) else 'START'
148         self.putp([cmd, None])
149         self.putx([proto[cmd][0], proto[cmd][1:]])
150         self.state = 'FIND ADDRESS'
151         self.bitcount = self.databyte = 0
152         self.is_repeat_start = 1
153         self.wr = -1
154
155     # Gather 8 bits of data plus the ACK/NACK bit.
156     def found_address_or_data(self, scl, sda):
157         # Address and data are transmitted MSB-first.
158         self.databyte <<= 1
159         self.databyte |= sda
160
161         if self.bitcount == 0:
162             self.startsample = self.samplenum
163
164         # Return if we haven't collected all 8 + 1 bits, yet.
165         self.bitcount += 1
166         if self.bitcount != 8:
167             return
168
169         # We triggered on the ACK/NACK bit, but won't report that until later.
170         self.startsample -= 1
171
172         d = self.databyte
173         if self.state == 'FIND ADDRESS':
174             # The READ/WRITE bit is only in address bytes, not data bytes.
175             self.wr = 0 if (self.databyte & 1) else 1
176             if self.options['address_format'] == 'shifted':
177                 d = d >> 1
178
179         if self.state == 'FIND ADDRESS' and self.wr == 1:
180             cmd = 'ADDRESS WRITE'
181         elif self.state == 'FIND ADDRESS' and self.wr == 0:
182             cmd = 'ADDRESS READ'
183         elif self.state == 'FIND DATA' and self.wr == 1:
184             cmd = 'DATA WRITE'
185         elif self.state == 'FIND DATA' and self.wr == 0:
186             cmd = 'DATA READ'
187
188         self.putp([cmd, d])
189         self.putx([proto[cmd][0], ['%s: %02X' % (proto[cmd][1], d),
190                   '%s: %02X' % (proto[cmd][2], d), '%02X' % d]])
191
192         # Done with this packet.
193         self.startsample = -1
194         self.bitcount = self.databyte = 0
195         self.state = 'FIND ACK'
196
197     def get_ack(self, scl, sda):
198         self.startsample = self.samplenum
199         cmd = 'NACK' if (sda == 1) else 'ACK'
200         self.putp([cmd, None])
201         self.putx([proto[cmd][0], proto[cmd][1:]])
202         # There could be multiple data bytes in a row, so either find
203         # another data byte or a STOP condition next.
204         self.state = 'FIND DATA'
205
206     def found_stop(self, scl, sda):
207         self.startsample = self.samplenum
208         cmd = 'STOP'
209         self.putp([cmd, None])
210         self.putx([proto[cmd][0], proto[cmd][1:]])
211         self.state = 'FIND START'
212         self.is_repeat_start = 0
213         self.wr = -1
214
215     def decode(self, ss, es, data):
216         for (self.samplenum, pins) in data:
217
218             # Ignore identical samples early on (for performance reasons).
219             if self.oldpins == pins:
220                 continue
221             self.oldpins, (scl, sda) = pins, pins
222
223             # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
224
225             # State machine.
226             if self.state == 'FIND START':
227                 if self.is_start_condition(scl, sda):
228                     self.found_start(scl, sda)
229             elif self.state == 'FIND ADDRESS':
230                 if self.is_data_bit(scl, sda):
231                     self.found_address_or_data(scl, sda)
232             elif self.state == 'FIND DATA':
233                 if self.is_data_bit(scl, sda):
234                     self.found_address_or_data(scl, sda)
235                 elif self.is_start_condition(scl, sda):
236                     self.found_start(scl, sda)
237                 elif self.is_stop_condition(scl, sda):
238                     self.found_stop(scl, sda)
239             elif self.state == 'FIND ACK':
240                 if self.is_data_bit(scl, sda):
241                     self.get_ack(scl, sda)
242             else:
243                 raise Exception('Invalid state: %s' % self.state)
244
245             # Save current SDA/SCL values for the next round.
246             self.oldscl = scl
247             self.oldsda = sda
248