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